1 //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This checker tries to find nullability violations. There are several kinds of
10 // possible violations:
11 // * Null pointer is passed to a pointer which has a _Nonnull type.
12 // * Null pointer is returned from a function which has a _Nonnull return type.
13 // * Nullable pointer is passed to a pointer which has a _Nonnull type.
14 // * Nullable pointer is returned from a function which has a _Nonnull return
15 //   type.
16 // * Nullable pointer is dereferenced.
17 //
18 // This checker propagates the nullability information of the pointers and looks
19 // for the patterns that are described above. Explicit casts are trusted and are
20 // considered a way to suppress false positives for this checker. The other way
21 // to suppress warnings would be to add asserts or guarding if statements to the
22 // code. In addition to the nullability propagation this checker also uses some
23 // heuristics to suppress potential false positives.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
28 
29 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
30 #include "clang/StaticAnalyzer/Core/Checker.h"
31 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
35 
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/Path.h"
38 
39 using namespace clang;
40 using namespace ento;
41 
42 namespace {
43 
44 /// Returns the most nullable nullability. This is used for message expressions
45 /// like [receiver method], where the nullability of this expression is either
46 /// the nullability of the receiver or the nullability of the return type of the
47 /// method, depending on which is more nullable. Contradicted is considered to
48 /// be the most nullable, to avoid false positive results.
49 Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
50   return static_cast<Nullability>(
51       std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
52 }
53 
54 const char *getNullabilityString(Nullability Nullab) {
55   switch (Nullab) {
56   case Nullability::Contradicted:
57     return "contradicted";
58   case Nullability::Nullable:
59     return "nullable";
60   case Nullability::Unspecified:
61     return "unspecified";
62   case Nullability::Nonnull:
63     return "nonnull";
64   }
65   llvm_unreachable("Unexpected enumeration.");
66   return "";
67 }
68 
69 // These enums are used as an index to ErrorMessages array.
70 enum class ErrorKind : int {
71   NilAssignedToNonnull,
72   NilPassedToNonnull,
73   NilReturnedToNonnull,
74   NullableAssignedToNonnull,
75   NullableReturnedToNonnull,
76   NullableDereferenced,
77   NullablePassedToNonnull
78 };
79 
80 class NullabilityChecker
81     : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
82                      check::PostCall, check::PostStmt<ExplicitCastExpr>,
83                      check::PostObjCMessage, check::DeadSymbols,
84                      check::Event<ImplicitNullDerefEvent>> {
85   mutable std::unique_ptr<BugType> BT;
86 
87 public:
88   // If true, the checker will not diagnose nullabilility issues for calls
89   // to system headers. This option is motivated by the observation that large
90   // projects may have many nullability warnings. These projects may
91   // find warnings about nullability annotations that they have explicitly
92   // added themselves higher priority to fix than warnings on calls to system
93   // libraries.
94   DefaultBool NoDiagnoseCallsToSystemHeaders;
95 
96   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
97   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
98   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
99   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
100   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
101   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
102   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
103   void checkEvent(ImplicitNullDerefEvent Event) const;
104 
105   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
106                   const char *Sep) const override;
107 
108   struct NullabilityChecksFilter {
109     DefaultBool CheckNullPassedToNonnull;
110     DefaultBool CheckNullReturnedFromNonnull;
111     DefaultBool CheckNullableDereferenced;
112     DefaultBool CheckNullablePassedToNonnull;
113     DefaultBool CheckNullableReturnedFromNonnull;
114 
115     CheckName CheckNameNullPassedToNonnull;
116     CheckName CheckNameNullReturnedFromNonnull;
117     CheckName CheckNameNullableDereferenced;
118     CheckName CheckNameNullablePassedToNonnull;
119     CheckName CheckNameNullableReturnedFromNonnull;
120   };
121 
122   NullabilityChecksFilter Filter;
123   // When set to false no nullability information will be tracked in
124   // NullabilityMap. It is possible to catch errors like passing a null pointer
125   // to a callee that expects nonnull argument without the information that is
126   // stroed in the NullabilityMap. This is an optimization.
127   DefaultBool NeedTracking;
128 
129 private:
130   class NullabilityBugVisitor : public BugReporterVisitor {
131   public:
132     NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
133 
134     void Profile(llvm::FoldingSetNodeID &ID) const override {
135       static int X = 0;
136       ID.AddPointer(&X);
137       ID.AddPointer(Region);
138     }
139 
140     PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
141                                      BugReporterContext &BRC,
142                                      PathSensitiveBugReport &BR) override;
143 
144   private:
145     // The tracked region.
146     const MemRegion *Region;
147   };
148 
149   /// When any of the nonnull arguments of the analyzed function is null, do not
150   /// report anything and turn off the check.
151   ///
152   /// When \p SuppressPath is set to true, no more bugs will be reported on this
153   /// path by this checker.
154   void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error,
155                                  ExplodedNode *N, const MemRegion *Region,
156                                  CheckerContext &C,
157                                  const Stmt *ValueExpr = nullptr,
158                                   bool SuppressPath = false) const;
159 
160   void reportBug(StringRef Msg, ErrorKind Error, ExplodedNode *N,
161                  const MemRegion *Region, BugReporter &BR,
162                  const Stmt *ValueExpr = nullptr) const {
163     if (!BT)
164       BT.reset(new BugType(this, "Nullability", categories::MemoryError));
165 
166     auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
167     if (Region) {
168       R->markInteresting(Region);
169       R->addVisitor(std::make_unique<NullabilityBugVisitor>(Region));
170     }
171     if (ValueExpr) {
172       R->addRange(ValueExpr->getSourceRange());
173       if (Error == ErrorKind::NilAssignedToNonnull ||
174           Error == ErrorKind::NilPassedToNonnull ||
175           Error == ErrorKind::NilReturnedToNonnull)
176         if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
177           bugreporter::trackExpressionValue(N, Ex, *R);
178     }
179     BR.emitReport(std::move(R));
180   }
181 
182   /// If an SVal wraps a region that should be tracked, it will return a pointer
183   /// to the wrapped region. Otherwise it will return a nullptr.
184   const SymbolicRegion *getTrackRegion(SVal Val,
185                                        bool CheckSuperRegion = false) const;
186 
187   /// Returns true if the call is diagnosable in the current analyzer
188   /// configuration.
189   bool isDiagnosableCall(const CallEvent &Call) const {
190     if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
191       return false;
192 
193     return true;
194   }
195 };
196 
197 class NullabilityState {
198 public:
199   NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
200       : Nullab(Nullab), Source(Source) {}
201 
202   const Stmt *getNullabilitySource() const { return Source; }
203 
204   Nullability getValue() const { return Nullab; }
205 
206   void Profile(llvm::FoldingSetNodeID &ID) const {
207     ID.AddInteger(static_cast<char>(Nullab));
208     ID.AddPointer(Source);
209   }
210 
211   void print(raw_ostream &Out) const {
212     Out << getNullabilityString(Nullab) << "\n";
213   }
214 
215 private:
216   Nullability Nullab;
217   // Source is the expression which determined the nullability. For example in a
218   // message like [nullable nonnull_returning] has nullable nullability, because
219   // the receiver is nullable. Here the receiver will be the source of the
220   // nullability. This is useful information when the diagnostics are generated.
221   const Stmt *Source;
222 };
223 
224 bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
225   return Lhs.getValue() == Rhs.getValue() &&
226          Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
227 }
228 
229 } // end anonymous namespace
230 
231 REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
232                                NullabilityState)
233 
234 // We say "the nullability type invariant is violated" when a location with a
235 // non-null type contains NULL or a function with a non-null return type returns
236 // NULL. Violations of the nullability type invariant can be detected either
237 // directly (for example, when NULL is passed as an argument to a nonnull
238 // parameter) or indirectly (for example, when, inside a function, the
239 // programmer defensively checks whether a nonnull parameter contains NULL and
240 // finds that it does).
241 //
242 // As a matter of policy, the nullability checker typically warns on direct
243 // violations of the nullability invariant (although it uses various
244 // heuristics to suppress warnings in some cases) but will not warn if the
245 // invariant has already been violated along the path (either directly or
246 // indirectly). As a practical matter, this prevents the analyzer from
247 // (1) warning on defensive code paths where a nullability precondition is
248 // determined to have been violated, (2) warning additional times after an
249 // initial direct violation has been discovered, and (3) warning after a direct
250 // violation that has been implicitly or explicitly suppressed (for
251 // example, with a cast of NULL to _Nonnull). In essence, once an invariant
252 // violation is detected on a path, this checker will be essentially turned off
253 // for the rest of the analysis
254 //
255 // The analyzer takes this approach (rather than generating a sink node) to
256 // ensure coverage of defensive paths, which may be important for backwards
257 // compatibility in codebases that were developed without nullability in mind.
258 REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
259 
260 enum class NullConstraint { IsNull, IsNotNull, Unknown };
261 
262 static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
263                                         ProgramStateRef State) {
264   ConditionTruthVal Nullness = State->isNull(Val);
265   if (Nullness.isConstrainedFalse())
266     return NullConstraint::IsNotNull;
267   if (Nullness.isConstrainedTrue())
268     return NullConstraint::IsNull;
269   return NullConstraint::Unknown;
270 }
271 
272 const SymbolicRegion *
273 NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
274   if (!NeedTracking)
275     return nullptr;
276 
277   auto RegionSVal = Val.getAs<loc::MemRegionVal>();
278   if (!RegionSVal)
279     return nullptr;
280 
281   const MemRegion *Region = RegionSVal->getRegion();
282 
283   if (CheckSuperRegion) {
284     if (auto FieldReg = Region->getAs<FieldRegion>())
285       return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
286     if (auto ElementReg = Region->getAs<ElementRegion>())
287       return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
288   }
289 
290   return dyn_cast<SymbolicRegion>(Region);
291 }
292 
293 PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
294     const ExplodedNode *N, BugReporterContext &BRC,
295     PathSensitiveBugReport &BR) {
296   ProgramStateRef State = N->getState();
297   ProgramStateRef StatePrev = N->getFirstPred()->getState();
298 
299   const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
300   const NullabilityState *TrackedNullabPrev =
301       StatePrev->get<NullabilityMap>(Region);
302   if (!TrackedNullab)
303     return nullptr;
304 
305   if (TrackedNullabPrev &&
306       TrackedNullabPrev->getValue() == TrackedNullab->getValue())
307     return nullptr;
308 
309   // Retrieve the associated statement.
310   const Stmt *S = TrackedNullab->getNullabilitySource();
311   if (!S || S->getBeginLoc().isInvalid()) {
312     S = PathDiagnosticLocation::getStmt(N);
313   }
314 
315   if (!S)
316     return nullptr;
317 
318   std::string InfoText =
319       (llvm::Twine("Nullability '") +
320        getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
321           .str();
322 
323   // Generate the extra diagnostic.
324   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
325                              N->getLocationContext());
326   return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true,
327                                                     nullptr);
328 }
329 
330 /// Returns true when the value stored at the given location has been
331 /// constrained to null after being passed through an object of nonnnull type.
332 static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
333                                                   SVal LV, QualType T) {
334   if (getNullabilityAnnotation(T) != Nullability::Nonnull)
335     return false;
336 
337   auto RegionVal = LV.getAs<loc::MemRegionVal>();
338   if (!RegionVal)
339     return false;
340 
341   // If the value was constrained to null *after* it was passed through that
342   // location, it could not have been a concrete pointer *when* it was passed.
343   // In that case we would have handled the situation when the value was
344   // bound to that location, by emitting (or not emitting) a report.
345   // Therefore we are only interested in symbolic regions that can be either
346   // null or non-null depending on the value of their respective symbol.
347   auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
348   if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
349     return false;
350 
351   if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
352     return true;
353 
354   return false;
355 }
356 
357 static bool
358 checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
359                                     ProgramStateRef State,
360                                     const LocationContext *LocCtxt) {
361   for (const auto *ParamDecl : Params) {
362     if (ParamDecl->isParameterPack())
363       break;
364 
365     SVal LV = State->getLValue(ParamDecl, LocCtxt);
366     if (checkValueAtLValForInvariantViolation(State, LV,
367                                               ParamDecl->getType())) {
368       return true;
369     }
370   }
371   return false;
372 }
373 
374 static bool
375 checkSelfIvarsForInvariantViolation(ProgramStateRef State,
376                                     const LocationContext *LocCtxt) {
377   auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
378   if (!MD || !MD->isInstanceMethod())
379     return false;
380 
381   const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
382   if (!SelfDecl)
383     return false;
384 
385   SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
386 
387   const ObjCObjectPointerType *SelfType =
388       dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
389   if (!SelfType)
390     return false;
391 
392   const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
393   if (!ID)
394     return false;
395 
396   for (const auto *IvarDecl : ID->ivars()) {
397     SVal LV = State->getLValue(IvarDecl, SelfVal);
398     if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
399       return true;
400     }
401   }
402   return false;
403 }
404 
405 static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
406                                     CheckerContext &C) {
407   if (State->get<InvariantViolated>())
408     return true;
409 
410   const LocationContext *LocCtxt = C.getLocationContext();
411   const Decl *D = LocCtxt->getDecl();
412   if (!D)
413     return false;
414 
415   ArrayRef<ParmVarDecl*> Params;
416   if (const auto *BD = dyn_cast<BlockDecl>(D))
417     Params = BD->parameters();
418   else if (const auto *FD = dyn_cast<FunctionDecl>(D))
419     Params = FD->parameters();
420   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
421     Params = MD->parameters();
422   else
423     return false;
424 
425   if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
426       checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
427     if (!N->isSink())
428       C.addTransition(State->set<InvariantViolated>(true), N);
429     return true;
430   }
431   return false;
432 }
433 
434 void NullabilityChecker::reportBugIfInvariantHolds(StringRef Msg,
435     ErrorKind Error, ExplodedNode *N, const MemRegion *Region,
436     CheckerContext &C, const Stmt *ValueExpr, bool SuppressPath) const {
437   ProgramStateRef OriginalState = N->getState();
438 
439   if (checkInvariantViolation(OriginalState, N, C))
440     return;
441   if (SuppressPath) {
442     OriginalState = OriginalState->set<InvariantViolated>(true);
443     N = C.addTransition(OriginalState, N);
444   }
445 
446   reportBug(Msg, Error, N, Region, C.getBugReporter(), ValueExpr);
447 }
448 
449 /// Cleaning up the program state.
450 void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
451                                           CheckerContext &C) const {
452   ProgramStateRef State = C.getState();
453   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
454   for (NullabilityMapTy::iterator I = Nullabilities.begin(),
455                                   E = Nullabilities.end();
456        I != E; ++I) {
457     const auto *Region = I->first->getAs<SymbolicRegion>();
458     assert(Region && "Non-symbolic region is tracked.");
459     if (SR.isDead(Region->getSymbol())) {
460       State = State->remove<NullabilityMap>(I->first);
461     }
462   }
463   // When one of the nonnull arguments are constrained to be null, nullability
464   // preconditions are violated. It is not enough to check this only when we
465   // actually report an error, because at that time interesting symbols might be
466   // reaped.
467   if (checkInvariantViolation(State, C.getPredecessor(), C))
468     return;
469   C.addTransition(State);
470 }
471 
472 /// This callback triggers when a pointer is dereferenced and the analyzer does
473 /// not know anything about the value of that pointer. When that pointer is
474 /// nullable, this code emits a warning.
475 void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
476   if (Event.SinkNode->getState()->get<InvariantViolated>())
477     return;
478 
479   const MemRegion *Region =
480       getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
481   if (!Region)
482     return;
483 
484   ProgramStateRef State = Event.SinkNode->getState();
485   const NullabilityState *TrackedNullability =
486       State->get<NullabilityMap>(Region);
487 
488   if (!TrackedNullability)
489     return;
490 
491   if (Filter.CheckNullableDereferenced &&
492       TrackedNullability->getValue() == Nullability::Nullable) {
493     BugReporter &BR = *Event.BR;
494     // Do not suppress errors on defensive code paths, because dereferencing
495     // a nullable pointer is always an error.
496     if (Event.IsDirectDereference)
497       reportBug("Nullable pointer is dereferenced",
498                 ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR);
499     else {
500       reportBug("Nullable pointer is passed to a callee that requires a "
501                 "non-null", ErrorKind::NullablePassedToNonnull,
502                 Event.SinkNode, Region, BR);
503     }
504   }
505 }
506 
507 /// Find the outermost subexpression of E that is not an implicit cast.
508 /// This looks through the implicit casts to _Nonnull that ARC adds to
509 /// return expressions of ObjC types when the return type of the function or
510 /// method is non-null but the express is not.
511 static const Expr *lookThroughImplicitCasts(const Expr *E) {
512   assert(E);
513 
514   while (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
515     E = ICE->getSubExpr();
516   }
517 
518   return E;
519 }
520 
521 /// This method check when nullable pointer or null value is returned from a
522 /// function that has nonnull return type.
523 void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
524                                       CheckerContext &C) const {
525   auto RetExpr = S->getRetValue();
526   if (!RetExpr)
527     return;
528 
529   if (!RetExpr->getType()->isAnyPointerType())
530     return;
531 
532   ProgramStateRef State = C.getState();
533   if (State->get<InvariantViolated>())
534     return;
535 
536   auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
537   if (!RetSVal)
538     return;
539 
540   bool InSuppressedMethodFamily = false;
541 
542   QualType RequiredRetType;
543   AnalysisDeclContext *DeclCtxt =
544       C.getLocationContext()->getAnalysisDeclContext();
545   const Decl *D = DeclCtxt->getDecl();
546   if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
547     // HACK: This is a big hammer to avoid warning when there are defensive
548     // nil checks in -init and -copy methods. We should add more sophisticated
549     // logic here to suppress on common defensive idioms but still
550     // warn when there is a likely problem.
551     ObjCMethodFamily Family = MD->getMethodFamily();
552     if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
553       InSuppressedMethodFamily = true;
554 
555     RequiredRetType = MD->getReturnType();
556   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
557     RequiredRetType = FD->getReturnType();
558   } else {
559     return;
560   }
561 
562   NullConstraint Nullness = getNullConstraint(*RetSVal, State);
563 
564   Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
565 
566   // If the returned value is null but the type of the expression
567   // generating it is nonnull then we will suppress the diagnostic.
568   // This enables explicit suppression when returning a nil literal in a
569   // function with a _Nonnull return type:
570   //    return (NSString * _Nonnull)0;
571   Nullability RetExprTypeLevelNullability =
572         getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
573 
574   bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
575                                   Nullness == NullConstraint::IsNull);
576   if (Filter.CheckNullReturnedFromNonnull &&
577       NullReturnedFromNonNull &&
578       RetExprTypeLevelNullability != Nullability::Nonnull &&
579       !InSuppressedMethodFamily &&
580       C.getLocationContext()->inTopFrame()) {
581     static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
582     ExplodedNode *N = C.generateErrorNode(State, &Tag);
583     if (!N)
584       return;
585 
586     SmallString<256> SBuf;
587     llvm::raw_svector_ostream OS(SBuf);
588     OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
589     OS << " returned from a " << C.getDeclDescription(D) <<
590           " that is expected to return a non-null value";
591     reportBugIfInvariantHolds(OS.str(),
592                               ErrorKind::NilReturnedToNonnull, N, nullptr, C,
593                               RetExpr);
594     return;
595   }
596 
597   // If null was returned from a non-null function, mark the nullability
598   // invariant as violated even if the diagnostic was suppressed.
599   if (NullReturnedFromNonNull) {
600     State = State->set<InvariantViolated>(true);
601     C.addTransition(State);
602     return;
603   }
604 
605   const MemRegion *Region = getTrackRegion(*RetSVal);
606   if (!Region)
607     return;
608 
609   const NullabilityState *TrackedNullability =
610       State->get<NullabilityMap>(Region);
611   if (TrackedNullability) {
612     Nullability TrackedNullabValue = TrackedNullability->getValue();
613     if (Filter.CheckNullableReturnedFromNonnull &&
614         Nullness != NullConstraint::IsNotNull &&
615         TrackedNullabValue == Nullability::Nullable &&
616         RequiredNullability == Nullability::Nonnull) {
617       static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
618       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
619 
620       SmallString<256> SBuf;
621       llvm::raw_svector_ostream OS(SBuf);
622       OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
623             " that is expected to return a non-null value";
624 
625       reportBugIfInvariantHolds(OS.str(),
626                                 ErrorKind::NullableReturnedToNonnull, N,
627                                 Region, C);
628     }
629     return;
630   }
631   if (RequiredNullability == Nullability::Nullable) {
632     State = State->set<NullabilityMap>(Region,
633                                        NullabilityState(RequiredNullability,
634                                                         S));
635     C.addTransition(State);
636   }
637 }
638 
639 /// This callback warns when a nullable pointer or a null value is passed to a
640 /// function that expects its argument to be nonnull.
641 void NullabilityChecker::checkPreCall(const CallEvent &Call,
642                                       CheckerContext &C) const {
643   if (!Call.getDecl())
644     return;
645 
646   ProgramStateRef State = C.getState();
647   if (State->get<InvariantViolated>())
648     return;
649 
650   ProgramStateRef OrigState = State;
651 
652   unsigned Idx = 0;
653   for (const ParmVarDecl *Param : Call.parameters()) {
654     if (Param->isParameterPack())
655       break;
656 
657     if (Idx >= Call.getNumArgs())
658       break;
659 
660     const Expr *ArgExpr = Call.getArgExpr(Idx);
661     auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
662     if (!ArgSVal)
663       continue;
664 
665     if (!Param->getType()->isAnyPointerType() &&
666         !Param->getType()->isReferenceType())
667       continue;
668 
669     NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
670 
671     Nullability RequiredNullability =
672         getNullabilityAnnotation(Param->getType());
673     Nullability ArgExprTypeLevelNullability =
674         getNullabilityAnnotation(ArgExpr->getType());
675 
676     unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
677 
678     if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull &&
679         ArgExprTypeLevelNullability != Nullability::Nonnull &&
680         RequiredNullability == Nullability::Nonnull &&
681         isDiagnosableCall(Call)) {
682       ExplodedNode *N = C.generateErrorNode(State);
683       if (!N)
684         return;
685 
686       SmallString<256> SBuf;
687       llvm::raw_svector_ostream OS(SBuf);
688       OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
689       OS << " passed to a callee that requires a non-null " << ParamIdx
690          << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
691       reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull, N,
692                                 nullptr, C,
693                                 ArgExpr, /*SuppressPath=*/false);
694       return;
695     }
696 
697     const MemRegion *Region = getTrackRegion(*ArgSVal);
698     if (!Region)
699       continue;
700 
701     const NullabilityState *TrackedNullability =
702         State->get<NullabilityMap>(Region);
703 
704     if (TrackedNullability) {
705       if (Nullness == NullConstraint::IsNotNull ||
706           TrackedNullability->getValue() != Nullability::Nullable)
707         continue;
708 
709       if (Filter.CheckNullablePassedToNonnull &&
710           RequiredNullability == Nullability::Nonnull &&
711           isDiagnosableCall(Call)) {
712         ExplodedNode *N = C.addTransition(State);
713         SmallString<256> SBuf;
714         llvm::raw_svector_ostream OS(SBuf);
715         OS << "Nullable pointer is passed to a callee that requires a non-null "
716            << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
717         reportBugIfInvariantHolds(OS.str(),
718                                   ErrorKind::NullablePassedToNonnull, N,
719                                   Region, C, ArgExpr, /*SuppressPath=*/true);
720         return;
721       }
722       if (Filter.CheckNullableDereferenced &&
723           Param->getType()->isReferenceType()) {
724         ExplodedNode *N = C.addTransition(State);
725         reportBugIfInvariantHolds("Nullable pointer is dereferenced",
726                                   ErrorKind::NullableDereferenced, N, Region,
727                                   C, ArgExpr, /*SuppressPath=*/true);
728         return;
729       }
730       continue;
731     }
732     // No tracked nullability yet.
733     if (ArgExprTypeLevelNullability != Nullability::Nullable)
734       continue;
735     State = State->set<NullabilityMap>(
736         Region, NullabilityState(ArgExprTypeLevelNullability, ArgExpr));
737   }
738   if (State != OrigState)
739     C.addTransition(State);
740 }
741 
742 /// Suppress the nullability warnings for some functions.
743 void NullabilityChecker::checkPostCall(const CallEvent &Call,
744                                        CheckerContext &C) const {
745   auto Decl = Call.getDecl();
746   if (!Decl)
747     return;
748   // ObjC Messages handles in a different callback.
749   if (Call.getKind() == CE_ObjCMessage)
750     return;
751   const FunctionType *FuncType = Decl->getFunctionType();
752   if (!FuncType)
753     return;
754   QualType ReturnType = FuncType->getReturnType();
755   if (!ReturnType->isAnyPointerType())
756     return;
757   ProgramStateRef State = C.getState();
758   if (State->get<InvariantViolated>())
759     return;
760 
761   const MemRegion *Region = getTrackRegion(Call.getReturnValue());
762   if (!Region)
763     return;
764 
765   // CG headers are misannotated. Do not warn for symbols that are the results
766   // of CG calls.
767   const SourceManager &SM = C.getSourceManager();
768   StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
769   if (llvm::sys::path::filename(FilePath).startswith("CG")) {
770     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
771     C.addTransition(State);
772     return;
773   }
774 
775   const NullabilityState *TrackedNullability =
776       State->get<NullabilityMap>(Region);
777 
778   if (!TrackedNullability &&
779       getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
780     State = State->set<NullabilityMap>(Region, Nullability::Nullable);
781     C.addTransition(State);
782   }
783 }
784 
785 static Nullability getReceiverNullability(const ObjCMethodCall &M,
786                                           ProgramStateRef State) {
787   if (M.isReceiverSelfOrSuper()) {
788     // For super and super class receivers we assume that the receiver is
789     // nonnull.
790     return Nullability::Nonnull;
791   }
792   // Otherwise look up nullability in the state.
793   SVal Receiver = M.getReceiverSVal();
794   if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
795     // If the receiver is constrained to be nonnull, assume that it is nonnull
796     // regardless of its type.
797     NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
798     if (Nullness == NullConstraint::IsNotNull)
799       return Nullability::Nonnull;
800   }
801   auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
802   if (ValueRegionSVal) {
803     const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
804     assert(SelfRegion);
805 
806     const NullabilityState *TrackedSelfNullability =
807         State->get<NullabilityMap>(SelfRegion);
808     if (TrackedSelfNullability)
809       return TrackedSelfNullability->getValue();
810   }
811   return Nullability::Unspecified;
812 }
813 
814 /// Calculate the nullability of the result of a message expr based on the
815 /// nullability of the receiver, the nullability of the return value, and the
816 /// constraints.
817 void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
818                                               CheckerContext &C) const {
819   auto Decl = M.getDecl();
820   if (!Decl)
821     return;
822   QualType RetType = Decl->getReturnType();
823   if (!RetType->isAnyPointerType())
824     return;
825 
826   ProgramStateRef State = C.getState();
827   if (State->get<InvariantViolated>())
828     return;
829 
830   const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
831   if (!ReturnRegion)
832     return;
833 
834   auto Interface = Decl->getClassInterface();
835   auto Name = Interface ? Interface->getName() : "";
836   // In order to reduce the noise in the diagnostics generated by this checker,
837   // some framework and programming style based heuristics are used. These
838   // heuristics are for Cocoa APIs which have NS prefix.
839   if (Name.startswith("NS")) {
840     // Developers rely on dynamic invariants such as an item should be available
841     // in a collection, or a collection is not empty often. Those invariants can
842     // not be inferred by any static analysis tool. To not to bother the users
843     // with too many false positives, every item retrieval function should be
844     // ignored for collections. The instance methods of dictionaries in Cocoa
845     // are either item retrieval related or not interesting nullability wise.
846     // Using this fact, to keep the code easier to read just ignore the return
847     // value of every instance method of dictionaries.
848     if (M.isInstanceMessage() && Name.contains("Dictionary")) {
849       State =
850           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
851       C.addTransition(State);
852       return;
853     }
854     // For similar reasons ignore some methods of Cocoa arrays.
855     StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
856     if (Name.contains("Array") &&
857         (FirstSelectorSlot == "firstObject" ||
858          FirstSelectorSlot == "lastObject")) {
859       State =
860           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
861       C.addTransition(State);
862       return;
863     }
864 
865     // Encoding related methods of string should not fail when lossless
866     // encodings are used. Using lossless encodings is so frequent that ignoring
867     // this class of methods reduced the emitted diagnostics by about 30% on
868     // some projects (and all of that was false positives).
869     if (Name.contains("String")) {
870       for (auto Param : M.parameters()) {
871         if (Param->getName() == "encoding") {
872           State = State->set<NullabilityMap>(ReturnRegion,
873                                              Nullability::Contradicted);
874           C.addTransition(State);
875           return;
876         }
877       }
878     }
879   }
880 
881   const ObjCMessageExpr *Message = M.getOriginExpr();
882   Nullability SelfNullability = getReceiverNullability(M, State);
883 
884   const NullabilityState *NullabilityOfReturn =
885       State->get<NullabilityMap>(ReturnRegion);
886 
887   if (NullabilityOfReturn) {
888     // When we have a nullability tracked for the return value, the nullability
889     // of the expression will be the most nullable of the receiver and the
890     // return value.
891     Nullability RetValTracked = NullabilityOfReturn->getValue();
892     Nullability ComputedNullab =
893         getMostNullable(RetValTracked, SelfNullability);
894     if (ComputedNullab != RetValTracked &&
895         ComputedNullab != Nullability::Unspecified) {
896       const Stmt *NullabilitySource =
897           ComputedNullab == RetValTracked
898               ? NullabilityOfReturn->getNullabilitySource()
899               : Message->getInstanceReceiver();
900       State = State->set<NullabilityMap>(
901           ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
902       C.addTransition(State);
903     }
904     return;
905   }
906 
907   // No tracked information. Use static type information for return value.
908   Nullability RetNullability = getNullabilityAnnotation(RetType);
909 
910   // Properties might be computed. For this reason the static analyzer creates a
911   // new symbol each time an unknown property  is read. To avoid false pozitives
912   // do not treat unknown properties as nullable, even when they explicitly
913   // marked nullable.
914   if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
915     RetNullability = Nullability::Nonnull;
916 
917   Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
918   if (ComputedNullab == Nullability::Nullable) {
919     const Stmt *NullabilitySource = ComputedNullab == RetNullability
920                                         ? Message
921                                         : Message->getInstanceReceiver();
922     State = State->set<NullabilityMap>(
923         ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
924     C.addTransition(State);
925   }
926 }
927 
928 /// Explicit casts are trusted. If there is a disagreement in the nullability
929 /// annotations in the destination and the source or '0' is casted to nonnull
930 /// track the value as having contraditory nullability. This will allow users to
931 /// suppress warnings.
932 void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
933                                        CheckerContext &C) const {
934   QualType OriginType = CE->getSubExpr()->getType();
935   QualType DestType = CE->getType();
936   if (!OriginType->isAnyPointerType())
937     return;
938   if (!DestType->isAnyPointerType())
939     return;
940 
941   ProgramStateRef State = C.getState();
942   if (State->get<InvariantViolated>())
943     return;
944 
945   Nullability DestNullability = getNullabilityAnnotation(DestType);
946 
947   // No explicit nullability in the destination type, so this cast does not
948   // change the nullability.
949   if (DestNullability == Nullability::Unspecified)
950     return;
951 
952   auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
953   const MemRegion *Region = getTrackRegion(*RegionSVal);
954   if (!Region)
955     return;
956 
957   // When 0 is converted to nonnull mark it as contradicted.
958   if (DestNullability == Nullability::Nonnull) {
959     NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
960     if (Nullness == NullConstraint::IsNull) {
961       State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
962       C.addTransition(State);
963       return;
964     }
965   }
966 
967   const NullabilityState *TrackedNullability =
968       State->get<NullabilityMap>(Region);
969 
970   if (!TrackedNullability) {
971     if (DestNullability != Nullability::Nullable)
972       return;
973     State = State->set<NullabilityMap>(Region,
974                                        NullabilityState(DestNullability, CE));
975     C.addTransition(State);
976     return;
977   }
978 
979   if (TrackedNullability->getValue() != DestNullability &&
980       TrackedNullability->getValue() != Nullability::Contradicted) {
981     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
982     C.addTransition(State);
983   }
984 }
985 
986 /// For a given statement performing a bind, attempt to syntactically
987 /// match the expression resulting in the bound value.
988 static const Expr * matchValueExprForBind(const Stmt *S) {
989   // For `x = e` the value expression is the right-hand side.
990   if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
991     if (BinOp->getOpcode() == BO_Assign)
992       return BinOp->getRHS();
993   }
994 
995   // For `int x = e` the value expression is the initializer.
996   if (auto *DS = dyn_cast<DeclStmt>(S))  {
997     if (DS->isSingleDecl()) {
998       auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
999       if (!VD)
1000         return nullptr;
1001 
1002       if (const Expr *Init = VD->getInit())
1003         return Init;
1004     }
1005   }
1006 
1007   return nullptr;
1008 }
1009 
1010 /// Returns true if \param S is a DeclStmt for a local variable that
1011 /// ObjC automated reference counting initialized with zero.
1012 static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
1013   // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
1014   // prevents false positives when a _Nonnull local variable cannot be
1015   // initialized with an initialization expression:
1016   //    NSString * _Nonnull s; // no-warning
1017   //    @autoreleasepool {
1018   //      s = ...
1019   //    }
1020   //
1021   // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
1022   // uninitialized in Sema's UninitializedValues analysis to warn when a use of
1023   // the zero-initialized definition will unexpectedly yield nil.
1024 
1025   // Locals are only zero-initialized when automated reference counting
1026   // is turned on.
1027   if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
1028     return false;
1029 
1030   auto *DS = dyn_cast<DeclStmt>(S);
1031   if (!DS || !DS->isSingleDecl())
1032     return false;
1033 
1034   auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1035   if (!VD)
1036     return false;
1037 
1038   // Sema only zero-initializes locals with ObjCLifetimes.
1039   if(!VD->getType().getQualifiers().hasObjCLifetime())
1040     return false;
1041 
1042   const Expr *Init = VD->getInit();
1043   assert(Init && "ObjC local under ARC without initializer");
1044 
1045   // Return false if the local is explicitly initialized (e.g., with '= nil').
1046   if (!isa<ImplicitValueInitExpr>(Init))
1047     return false;
1048 
1049   return true;
1050 }
1051 
1052 /// Propagate the nullability information through binds and warn when nullable
1053 /// pointer or null symbol is assigned to a pointer with a nonnull type.
1054 void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
1055                                    CheckerContext &C) const {
1056   const TypedValueRegion *TVR =
1057       dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
1058   if (!TVR)
1059     return;
1060 
1061   QualType LocType = TVR->getValueType();
1062   if (!LocType->isAnyPointerType())
1063     return;
1064 
1065   ProgramStateRef State = C.getState();
1066   if (State->get<InvariantViolated>())
1067     return;
1068 
1069   auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
1070   if (!ValDefOrUnknown)
1071     return;
1072 
1073   NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
1074 
1075   Nullability ValNullability = Nullability::Unspecified;
1076   if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
1077     ValNullability = getNullabilityAnnotation(Sym->getType());
1078 
1079   Nullability LocNullability = getNullabilityAnnotation(LocType);
1080 
1081   // If the type of the RHS expression is nonnull, don't warn. This
1082   // enables explicit suppression with a cast to nonnull.
1083   Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
1084   const Expr *ValueExpr = matchValueExprForBind(S);
1085   if (ValueExpr) {
1086     ValueExprTypeLevelNullability =
1087       getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
1088   }
1089 
1090   bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
1091                                 RhsNullness == NullConstraint::IsNull);
1092   if (Filter.CheckNullPassedToNonnull &&
1093       NullAssignedToNonNull &&
1094       ValNullability != Nullability::Nonnull &&
1095       ValueExprTypeLevelNullability != Nullability::Nonnull &&
1096       !isARCNilInitializedLocal(C, S)) {
1097     static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
1098     ExplodedNode *N = C.generateErrorNode(State, &Tag);
1099     if (!N)
1100       return;
1101 
1102 
1103     const Stmt *ValueStmt = S;
1104     if (ValueExpr)
1105       ValueStmt = ValueExpr;
1106 
1107     SmallString<256> SBuf;
1108     llvm::raw_svector_ostream OS(SBuf);
1109     OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
1110     OS << " assigned to a pointer which is expected to have non-null value";
1111     reportBugIfInvariantHolds(OS.str(),
1112                               ErrorKind::NilAssignedToNonnull, N, nullptr, C,
1113                               ValueStmt);
1114     return;
1115   }
1116 
1117   // If null was returned from a non-null function, mark the nullability
1118   // invariant as violated even if the diagnostic was suppressed.
1119   if (NullAssignedToNonNull) {
1120     State = State->set<InvariantViolated>(true);
1121     C.addTransition(State);
1122     return;
1123   }
1124 
1125   // Intentionally missing case: '0' is bound to a reference. It is handled by
1126   // the DereferenceChecker.
1127 
1128   const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
1129   if (!ValueRegion)
1130     return;
1131 
1132   const NullabilityState *TrackedNullability =
1133       State->get<NullabilityMap>(ValueRegion);
1134 
1135   if (TrackedNullability) {
1136     if (RhsNullness == NullConstraint::IsNotNull ||
1137         TrackedNullability->getValue() != Nullability::Nullable)
1138       return;
1139     if (Filter.CheckNullablePassedToNonnull &&
1140         LocNullability == Nullability::Nonnull) {
1141       static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
1142       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
1143       reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
1144                                 "which is expected to have non-null value",
1145                                 ErrorKind::NullableAssignedToNonnull, N,
1146                                 ValueRegion, C);
1147     }
1148     return;
1149   }
1150 
1151   const auto *BinOp = dyn_cast<BinaryOperator>(S);
1152 
1153   if (ValNullability == Nullability::Nullable) {
1154     // Trust the static information of the value more than the static
1155     // information on the location.
1156     const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
1157     State = State->set<NullabilityMap>(
1158         ValueRegion, NullabilityState(ValNullability, NullabilitySource));
1159     C.addTransition(State);
1160     return;
1161   }
1162 
1163   if (LocNullability == Nullability::Nullable) {
1164     const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
1165     State = State->set<NullabilityMap>(
1166         ValueRegion, NullabilityState(LocNullability, NullabilitySource));
1167     C.addTransition(State);
1168   }
1169 }
1170 
1171 void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
1172                                     const char *NL, const char *Sep) const {
1173 
1174   NullabilityMapTy B = State->get<NullabilityMap>();
1175 
1176   if (State->get<InvariantViolated>())
1177     Out << Sep << NL
1178         << "Nullability invariant was violated, warnings suppressed." << NL;
1179 
1180   if (B.isEmpty())
1181     return;
1182 
1183   if (!State->get<InvariantViolated>())
1184     Out << Sep << NL;
1185 
1186   for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1187     Out << I->first << " : ";
1188     I->second.print(Out);
1189     Out << NL;
1190   }
1191 }
1192 
1193 void ento::registerNullabilityBase(CheckerManager &mgr) {
1194   mgr.registerChecker<NullabilityChecker>();
1195 }
1196 
1197 bool ento::shouldRegisterNullabilityBase(const LangOptions &LO) {
1198   return true;
1199 }
1200 
1201 #define REGISTER_CHECKER(name, trackingRequired)                               \
1202   void ento::register##name##Checker(CheckerManager &mgr) {                    \
1203     NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>();        \
1204     checker->Filter.Check##name = true;                                        \
1205     checker->Filter.CheckName##name = mgr.getCurrentCheckName();               \
1206     checker->NeedTracking = checker->NeedTracking || trackingRequired;         \
1207     checker->NoDiagnoseCallsToSystemHeaders =                                  \
1208         checker->NoDiagnoseCallsToSystemHeaders ||                             \
1209         mgr.getAnalyzerOptions().getCheckerBooleanOption(                      \
1210                       checker, "NoDiagnoseCallsToSystemHeaders", true);        \
1211   }                                                                            \
1212                                                                                \
1213   bool ento::shouldRegister##name##Checker(const LangOptions &LO) {            \
1214     return true;                                                               \
1215   }
1216 
1217 // The checks are likely to be turned on by default and it is possible to do
1218 // them without tracking any nullability related information. As an optimization
1219 // no nullability information will be tracked when only these two checks are
1220 // enables.
1221 REGISTER_CHECKER(NullPassedToNonnull, false)
1222 REGISTER_CHECKER(NullReturnedFromNonnull, false)
1223 
1224 REGISTER_CHECKER(NullableDereferenced, true)
1225 REGISTER_CHECKER(NullablePassedToNonnull, true)
1226 REGISTER_CHECKER(NullableReturnedFromNonnull, true)
1227