xref: /freebsd-src/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This checker tries to find nullability violations. There are several kinds of
100b57cec5SDimitry Andric // possible violations:
110b57cec5SDimitry Andric // * Null pointer is passed to a pointer which has a _Nonnull type.
120b57cec5SDimitry Andric // * Null pointer is returned from a function which has a _Nonnull return type.
130b57cec5SDimitry Andric // * Nullable pointer is passed to a pointer which has a _Nonnull type.
140b57cec5SDimitry Andric // * Nullable pointer is returned from a function which has a _Nonnull return
150b57cec5SDimitry Andric //   type.
160b57cec5SDimitry Andric // * Nullable pointer is dereferenced.
170b57cec5SDimitry Andric //
180b57cec5SDimitry Andric // This checker propagates the nullability information of the pointers and looks
190b57cec5SDimitry Andric // for the patterns that are described above. Explicit casts are trusted and are
200b57cec5SDimitry Andric // considered a way to suppress false positives for this checker. The other way
210b57cec5SDimitry Andric // to suppress warnings would be to add asserts or guarding if statements to the
220b57cec5SDimitry Andric // code. In addition to the nullability propagation this checker also uses some
230b57cec5SDimitry Andric // heuristics to suppress potential false positives.
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
280b57cec5SDimitry Andric 
2906c3fb27SDimitry Andric #include "clang/Analysis/AnyCall.h"
300b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
320b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
330b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
3406c3fb27SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
3506c3fb27SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
360b57cec5SDimitry Andric 
3706c3fb27SDimitry Andric #include "llvm/ADT/STLExtras.h"
380b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
390b57cec5SDimitry Andric #include "llvm/Support/Path.h"
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric using namespace clang;
420b57cec5SDimitry Andric using namespace ento;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric namespace {
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric /// Returns the most nullable nullability. This is used for message expressions
470b57cec5SDimitry Andric /// like [receiver method], where the nullability of this expression is either
480b57cec5SDimitry Andric /// the nullability of the receiver or the nullability of the return type of the
490b57cec5SDimitry Andric /// method, depending on which is more nullable. Contradicted is considered to
500b57cec5SDimitry Andric /// be the most nullable, to avoid false positive results.
510b57cec5SDimitry Andric Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
520b57cec5SDimitry Andric   return static_cast<Nullability>(
530b57cec5SDimitry Andric       std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
540b57cec5SDimitry Andric }
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric const char *getNullabilityString(Nullability Nullab) {
570b57cec5SDimitry Andric   switch (Nullab) {
580b57cec5SDimitry Andric   case Nullability::Contradicted:
590b57cec5SDimitry Andric     return "contradicted";
600b57cec5SDimitry Andric   case Nullability::Nullable:
610b57cec5SDimitry Andric     return "nullable";
620b57cec5SDimitry Andric   case Nullability::Unspecified:
630b57cec5SDimitry Andric     return "unspecified";
640b57cec5SDimitry Andric   case Nullability::Nonnull:
650b57cec5SDimitry Andric     return "nonnull";
660b57cec5SDimitry Andric   }
670b57cec5SDimitry Andric   llvm_unreachable("Unexpected enumeration.");
680b57cec5SDimitry Andric   return "";
690b57cec5SDimitry Andric }
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric // These enums are used as an index to ErrorMessages array.
720b57cec5SDimitry Andric enum class ErrorKind : int {
730b57cec5SDimitry Andric   NilAssignedToNonnull,
740b57cec5SDimitry Andric   NilPassedToNonnull,
750b57cec5SDimitry Andric   NilReturnedToNonnull,
760b57cec5SDimitry Andric   NullableAssignedToNonnull,
770b57cec5SDimitry Andric   NullableReturnedToNonnull,
780b57cec5SDimitry Andric   NullableDereferenced,
790b57cec5SDimitry Andric   NullablePassedToNonnull
800b57cec5SDimitry Andric };
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric class NullabilityChecker
830b57cec5SDimitry Andric     : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
840b57cec5SDimitry Andric                      check::PostCall, check::PostStmt<ExplicitCastExpr>,
85bdd1243dSDimitry Andric                      check::PostObjCMessage, check::DeadSymbols, eval::Assume,
8606c3fb27SDimitry Andric                      check::Location, check::Event<ImplicitNullDerefEvent>,
8706c3fb27SDimitry Andric                      check::BeginFunction> {
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric public:
900b57cec5SDimitry Andric   // If true, the checker will not diagnose nullabilility issues for calls
910b57cec5SDimitry Andric   // to system headers. This option is motivated by the observation that large
920b57cec5SDimitry Andric   // projects may have many nullability warnings. These projects may
930b57cec5SDimitry Andric   // find warnings about nullability annotations that they have explicitly
940b57cec5SDimitry Andric   // added themselves higher priority to fix than warnings on calls to system
950b57cec5SDimitry Andric   // libraries.
9681ad6265SDimitry Andric   bool NoDiagnoseCallsToSystemHeaders = false;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
990b57cec5SDimitry Andric   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
1000b57cec5SDimitry Andric   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
1010b57cec5SDimitry Andric   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
1020b57cec5SDimitry Andric   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
1030b57cec5SDimitry Andric   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
1040b57cec5SDimitry Andric   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
1050b57cec5SDimitry Andric   void checkEvent(ImplicitNullDerefEvent Event) const;
1065ffd83dbSDimitry Andric   void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
1075ffd83dbSDimitry Andric                      CheckerContext &C) const;
10806c3fb27SDimitry Andric   void checkBeginFunction(CheckerContext &Ctx) const;
109bdd1243dSDimitry Andric   ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
110bdd1243dSDimitry Andric                              bool Assumption) const;
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
1130b57cec5SDimitry Andric                   const char *Sep) const override;
1140b57cec5SDimitry Andric 
1155ffd83dbSDimitry Andric   enum CheckKind {
1165ffd83dbSDimitry Andric     CK_NullPassedToNonnull,
1175ffd83dbSDimitry Andric     CK_NullReturnedFromNonnull,
1185ffd83dbSDimitry Andric     CK_NullableDereferenced,
1195ffd83dbSDimitry Andric     CK_NullablePassedToNonnull,
1205ffd83dbSDimitry Andric     CK_NullableReturnedFromNonnull,
1215ffd83dbSDimitry Andric     CK_NumCheckKinds
1220b57cec5SDimitry Andric   };
1230b57cec5SDimitry Andric 
12481ad6265SDimitry Andric   bool ChecksEnabled[CK_NumCheckKinds] = {false};
1255ffd83dbSDimitry Andric   CheckerNameRef CheckNames[CK_NumCheckKinds];
1265ffd83dbSDimitry Andric   mutable std::unique_ptr<BugType> BTs[CK_NumCheckKinds];
1275ffd83dbSDimitry Andric 
1285ffd83dbSDimitry Andric   const std::unique_ptr<BugType> &getBugType(CheckKind Kind) const {
1295ffd83dbSDimitry Andric     if (!BTs[Kind])
1305ffd83dbSDimitry Andric       BTs[Kind].reset(new BugType(CheckNames[Kind], "Nullability",
1315ffd83dbSDimitry Andric                                   categories::MemoryError));
1325ffd83dbSDimitry Andric     return BTs[Kind];
1335ffd83dbSDimitry Andric   }
1345ffd83dbSDimitry Andric 
1350b57cec5SDimitry Andric   // When set to false no nullability information will be tracked in
1360b57cec5SDimitry Andric   // NullabilityMap. It is possible to catch errors like passing a null pointer
1370b57cec5SDimitry Andric   // to a callee that expects nonnull argument without the information that is
138bdd1243dSDimitry Andric   // stored in the NullabilityMap. This is an optimization.
13981ad6265SDimitry Andric   bool NeedTracking = false;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric private:
1420b57cec5SDimitry Andric   class NullabilityBugVisitor : public BugReporterVisitor {
1430b57cec5SDimitry Andric   public:
1440b57cec5SDimitry Andric     NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric     void Profile(llvm::FoldingSetNodeID &ID) const override {
1470b57cec5SDimitry Andric       static int X = 0;
1480b57cec5SDimitry Andric       ID.AddPointer(&X);
1490b57cec5SDimitry Andric       ID.AddPointer(Region);
1500b57cec5SDimitry Andric     }
1510b57cec5SDimitry Andric 
152a7dea167SDimitry Andric     PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1530b57cec5SDimitry Andric                                      BugReporterContext &BRC,
154a7dea167SDimitry Andric                                      PathSensitiveBugReport &BR) override;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   private:
1570b57cec5SDimitry Andric     // The tracked region.
1580b57cec5SDimitry Andric     const MemRegion *Region;
1590b57cec5SDimitry Andric   };
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   /// When any of the nonnull arguments of the analyzed function is null, do not
1620b57cec5SDimitry Andric   /// report anything and turn off the check.
1630b57cec5SDimitry Andric   ///
1640b57cec5SDimitry Andric   /// When \p SuppressPath is set to true, no more bugs will be reported on this
1650b57cec5SDimitry Andric   /// path by this checker.
1665ffd83dbSDimitry Andric   void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
1670b57cec5SDimitry Andric                                  ExplodedNode *N, const MemRegion *Region,
1680b57cec5SDimitry Andric                                  CheckerContext &C,
1690b57cec5SDimitry Andric                                  const Stmt *ValueExpr = nullptr,
1700b57cec5SDimitry Andric                                  bool SuppressPath = false) const;
1710b57cec5SDimitry Andric 
1725ffd83dbSDimitry Andric   void reportBug(StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
1730b57cec5SDimitry Andric                  const MemRegion *Region, BugReporter &BR,
1740b57cec5SDimitry Andric                  const Stmt *ValueExpr = nullptr) const {
1755ffd83dbSDimitry Andric     const std::unique_ptr<BugType> &BT = getBugType(CK);
176a7dea167SDimitry Andric     auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
1770b57cec5SDimitry Andric     if (Region) {
1780b57cec5SDimitry Andric       R->markInteresting(Region);
179fe6060f1SDimitry Andric       R->addVisitor<NullabilityBugVisitor>(Region);
1800b57cec5SDimitry Andric     }
1810b57cec5SDimitry Andric     if (ValueExpr) {
1820b57cec5SDimitry Andric       R->addRange(ValueExpr->getSourceRange());
1830b57cec5SDimitry Andric       if (Error == ErrorKind::NilAssignedToNonnull ||
1840b57cec5SDimitry Andric           Error == ErrorKind::NilPassedToNonnull ||
1850b57cec5SDimitry Andric           Error == ErrorKind::NilReturnedToNonnull)
1860b57cec5SDimitry Andric         if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
1870b57cec5SDimitry Andric           bugreporter::trackExpressionValue(N, Ex, *R);
1880b57cec5SDimitry Andric     }
1890b57cec5SDimitry Andric     BR.emitReport(std::move(R));
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   /// If an SVal wraps a region that should be tracked, it will return a pointer
1930b57cec5SDimitry Andric   /// to the wrapped region. Otherwise it will return a nullptr.
1940b57cec5SDimitry Andric   const SymbolicRegion *getTrackRegion(SVal Val,
1950b57cec5SDimitry Andric                                        bool CheckSuperRegion = false) const;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   /// Returns true if the call is diagnosable in the current analyzer
1980b57cec5SDimitry Andric   /// configuration.
1990b57cec5SDimitry Andric   bool isDiagnosableCall(const CallEvent &Call) const {
2000b57cec5SDimitry Andric     if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
2010b57cec5SDimitry Andric       return false;
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     return true;
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric };
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric class NullabilityState {
2080b57cec5SDimitry Andric public:
2090b57cec5SDimitry Andric   NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
2100b57cec5SDimitry Andric       : Nullab(Nullab), Source(Source) {}
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   const Stmt *getNullabilitySource() const { return Source; }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   Nullability getValue() const { return Nullab; }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   void Profile(llvm::FoldingSetNodeID &ID) const {
2170b57cec5SDimitry Andric     ID.AddInteger(static_cast<char>(Nullab));
2180b57cec5SDimitry Andric     ID.AddPointer(Source);
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   void print(raw_ostream &Out) const {
2220b57cec5SDimitry Andric     Out << getNullabilityString(Nullab) << "\n";
2230b57cec5SDimitry Andric   }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric private:
2260b57cec5SDimitry Andric   Nullability Nullab;
2270b57cec5SDimitry Andric   // Source is the expression which determined the nullability. For example in a
2280b57cec5SDimitry Andric   // message like [nullable nonnull_returning] has nullable nullability, because
2290b57cec5SDimitry Andric   // the receiver is nullable. Here the receiver will be the source of the
2300b57cec5SDimitry Andric   // nullability. This is useful information when the diagnostics are generated.
2310b57cec5SDimitry Andric   const Stmt *Source;
2320b57cec5SDimitry Andric };
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
2350b57cec5SDimitry Andric   return Lhs.getValue() == Rhs.getValue() &&
2360b57cec5SDimitry Andric          Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric 
239bdd1243dSDimitry Andric // For the purpose of tracking historical property accesses, the key for lookup
240bdd1243dSDimitry Andric // is an object pointer (could be an instance or a class) paired with the unique
241bdd1243dSDimitry Andric // identifier for the property being invoked on that object.
242bdd1243dSDimitry Andric using ObjectPropPair = std::pair<const MemRegion *, const IdentifierInfo *>;
243bdd1243dSDimitry Andric 
244bdd1243dSDimitry Andric // Metadata associated with the return value from a recorded property access.
245bdd1243dSDimitry Andric struct ConstrainedPropertyVal {
246bdd1243dSDimitry Andric   // This will reference the conjured return SVal for some call
247bdd1243dSDimitry Andric   // of the form [object property]
248bdd1243dSDimitry Andric   DefinedOrUnknownSVal Value;
249bdd1243dSDimitry Andric 
250bdd1243dSDimitry Andric   // If the SVal has been determined to be nonnull, that is recorded here
251bdd1243dSDimitry Andric   bool isConstrainedNonnull;
252bdd1243dSDimitry Andric 
253bdd1243dSDimitry Andric   ConstrainedPropertyVal(DefinedOrUnknownSVal SV)
254bdd1243dSDimitry Andric       : Value(SV), isConstrainedNonnull(false) {}
255bdd1243dSDimitry Andric 
256bdd1243dSDimitry Andric   void Profile(llvm::FoldingSetNodeID &ID) const {
257bdd1243dSDimitry Andric     Value.Profile(ID);
258bdd1243dSDimitry Andric     ID.AddInteger(isConstrainedNonnull ? 1 : 0);
259bdd1243dSDimitry Andric   }
260bdd1243dSDimitry Andric };
261bdd1243dSDimitry Andric 
262bdd1243dSDimitry Andric bool operator==(const ConstrainedPropertyVal &Lhs,
263bdd1243dSDimitry Andric                 const ConstrainedPropertyVal &Rhs) {
264bdd1243dSDimitry Andric   return Lhs.Value == Rhs.Value &&
265bdd1243dSDimitry Andric          Lhs.isConstrainedNonnull == Rhs.isConstrainedNonnull;
266bdd1243dSDimitry Andric }
267bdd1243dSDimitry Andric 
2680b57cec5SDimitry Andric } // end anonymous namespace
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
2710b57cec5SDimitry Andric                                NullabilityState)
272bdd1243dSDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(PropertyAccessesMap, ObjectPropPair,
273bdd1243dSDimitry Andric                                ConstrainedPropertyVal)
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric // We say "the nullability type invariant is violated" when a location with a
2760b57cec5SDimitry Andric // non-null type contains NULL or a function with a non-null return type returns
2770b57cec5SDimitry Andric // NULL. Violations of the nullability type invariant can be detected either
2780b57cec5SDimitry Andric // directly (for example, when NULL is passed as an argument to a nonnull
2790b57cec5SDimitry Andric // parameter) or indirectly (for example, when, inside a function, the
2800b57cec5SDimitry Andric // programmer defensively checks whether a nonnull parameter contains NULL and
2810b57cec5SDimitry Andric // finds that it does).
2820b57cec5SDimitry Andric //
2830b57cec5SDimitry Andric // As a matter of policy, the nullability checker typically warns on direct
2840b57cec5SDimitry Andric // violations of the nullability invariant (although it uses various
2850b57cec5SDimitry Andric // heuristics to suppress warnings in some cases) but will not warn if the
2860b57cec5SDimitry Andric // invariant has already been violated along the path (either directly or
2870b57cec5SDimitry Andric // indirectly). As a practical matter, this prevents the analyzer from
2880b57cec5SDimitry Andric // (1) warning on defensive code paths where a nullability precondition is
2890b57cec5SDimitry Andric // determined to have been violated, (2) warning additional times after an
2900b57cec5SDimitry Andric // initial direct violation has been discovered, and (3) warning after a direct
2910b57cec5SDimitry Andric // violation that has been implicitly or explicitly suppressed (for
2920b57cec5SDimitry Andric // example, with a cast of NULL to _Nonnull). In essence, once an invariant
2930b57cec5SDimitry Andric // violation is detected on a path, this checker will be essentially turned off
2940b57cec5SDimitry Andric // for the rest of the analysis
2950b57cec5SDimitry Andric //
2960b57cec5SDimitry Andric // The analyzer takes this approach (rather than generating a sink node) to
2970b57cec5SDimitry Andric // ensure coverage of defensive paths, which may be important for backwards
2980b57cec5SDimitry Andric // compatibility in codebases that were developed without nullability in mind.
2990b57cec5SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric enum class NullConstraint { IsNull, IsNotNull, Unknown };
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
3040b57cec5SDimitry Andric                                         ProgramStateRef State) {
3050b57cec5SDimitry Andric   ConditionTruthVal Nullness = State->isNull(Val);
3060b57cec5SDimitry Andric   if (Nullness.isConstrainedFalse())
3070b57cec5SDimitry Andric     return NullConstraint::IsNotNull;
3080b57cec5SDimitry Andric   if (Nullness.isConstrainedTrue())
3090b57cec5SDimitry Andric     return NullConstraint::IsNull;
3100b57cec5SDimitry Andric   return NullConstraint::Unknown;
3110b57cec5SDimitry Andric }
3120b57cec5SDimitry Andric 
31306c3fb27SDimitry Andric static bool isValidPointerType(QualType T) {
31406c3fb27SDimitry Andric   return T->isAnyPointerType() || T->isBlockPointerType();
31506c3fb27SDimitry Andric }
31606c3fb27SDimitry Andric 
3170b57cec5SDimitry Andric const SymbolicRegion *
3180b57cec5SDimitry Andric NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
3190b57cec5SDimitry Andric   if (!NeedTracking)
3200b57cec5SDimitry Andric     return nullptr;
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   auto RegionSVal = Val.getAs<loc::MemRegionVal>();
3230b57cec5SDimitry Andric   if (!RegionSVal)
3240b57cec5SDimitry Andric     return nullptr;
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   const MemRegion *Region = RegionSVal->getRegion();
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric   if (CheckSuperRegion) {
329bdd1243dSDimitry Andric     if (const SubRegion *FieldReg = Region->getAs<FieldRegion>()) {
330bdd1243dSDimitry Andric       if (const auto *ER = dyn_cast<ElementRegion>(FieldReg->getSuperRegion()))
331bdd1243dSDimitry Andric         FieldReg = ER;
3320b57cec5SDimitry Andric       return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
333bdd1243dSDimitry Andric     }
3340b57cec5SDimitry Andric     if (auto ElementReg = Region->getAs<ElementRegion>())
3350b57cec5SDimitry Andric       return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   return dyn_cast<SymbolicRegion>(Region);
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric 
341a7dea167SDimitry Andric PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
342a7dea167SDimitry Andric     const ExplodedNode *N, BugReporterContext &BRC,
343a7dea167SDimitry Andric     PathSensitiveBugReport &BR) {
3440b57cec5SDimitry Andric   ProgramStateRef State = N->getState();
3450b57cec5SDimitry Andric   ProgramStateRef StatePrev = N->getFirstPred()->getState();
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
3480b57cec5SDimitry Andric   const NullabilityState *TrackedNullabPrev =
3490b57cec5SDimitry Andric       StatePrev->get<NullabilityMap>(Region);
3500b57cec5SDimitry Andric   if (!TrackedNullab)
3510b57cec5SDimitry Andric     return nullptr;
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   if (TrackedNullabPrev &&
3540b57cec5SDimitry Andric       TrackedNullabPrev->getValue() == TrackedNullab->getValue())
3550b57cec5SDimitry Andric     return nullptr;
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   // Retrieve the associated statement.
3580b57cec5SDimitry Andric   const Stmt *S = TrackedNullab->getNullabilitySource();
3590b57cec5SDimitry Andric   if (!S || S->getBeginLoc().isInvalid()) {
360a7dea167SDimitry Andric     S = N->getStmtForDiagnostics();
3610b57cec5SDimitry Andric   }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric   if (!S)
3640b57cec5SDimitry Andric     return nullptr;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   std::string InfoText =
3670b57cec5SDimitry Andric       (llvm::Twine("Nullability '") +
3680b57cec5SDimitry Andric        getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
3690b57cec5SDimitry Andric           .str();
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // Generate the extra diagnostic.
3720b57cec5SDimitry Andric   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
3730b57cec5SDimitry Andric                              N->getLocationContext());
374a7dea167SDimitry Andric   return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric /// Returns true when the value stored at the given location has been
3780b57cec5SDimitry Andric /// constrained to null after being passed through an object of nonnnull type.
3790b57cec5SDimitry Andric static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
3800b57cec5SDimitry Andric                                                   SVal LV, QualType T) {
3810b57cec5SDimitry Andric   if (getNullabilityAnnotation(T) != Nullability::Nonnull)
3820b57cec5SDimitry Andric     return false;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   auto RegionVal = LV.getAs<loc::MemRegionVal>();
3850b57cec5SDimitry Andric   if (!RegionVal)
3860b57cec5SDimitry Andric     return false;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   // If the value was constrained to null *after* it was passed through that
3890b57cec5SDimitry Andric   // location, it could not have been a concrete pointer *when* it was passed.
3900b57cec5SDimitry Andric   // In that case we would have handled the situation when the value was
3910b57cec5SDimitry Andric   // bound to that location, by emitting (or not emitting) a report.
3920b57cec5SDimitry Andric   // Therefore we are only interested in symbolic regions that can be either
3930b57cec5SDimitry Andric   // null or non-null depending on the value of their respective symbol.
3940b57cec5SDimitry Andric   auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
3950b57cec5SDimitry Andric   if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
3960b57cec5SDimitry Andric     return false;
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
3990b57cec5SDimitry Andric     return true;
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   return false;
4020b57cec5SDimitry Andric }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric static bool
4050b57cec5SDimitry Andric checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
4060b57cec5SDimitry Andric                                     ProgramStateRef State,
4070b57cec5SDimitry Andric                                     const LocationContext *LocCtxt) {
4080b57cec5SDimitry Andric   for (const auto *ParamDecl : Params) {
4090b57cec5SDimitry Andric     if (ParamDecl->isParameterPack())
4100b57cec5SDimitry Andric       break;
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric     SVal LV = State->getLValue(ParamDecl, LocCtxt);
4130b57cec5SDimitry Andric     if (checkValueAtLValForInvariantViolation(State, LV,
4140b57cec5SDimitry Andric                                               ParamDecl->getType())) {
4150b57cec5SDimitry Andric       return true;
4160b57cec5SDimitry Andric     }
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric   return false;
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric static bool
4220b57cec5SDimitry Andric checkSelfIvarsForInvariantViolation(ProgramStateRef State,
4230b57cec5SDimitry Andric                                     const LocationContext *LocCtxt) {
4240b57cec5SDimitry Andric   auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
4250b57cec5SDimitry Andric   if (!MD || !MD->isInstanceMethod())
4260b57cec5SDimitry Andric     return false;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
4290b57cec5SDimitry Andric   if (!SelfDecl)
4300b57cec5SDimitry Andric     return false;
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   const ObjCObjectPointerType *SelfType =
4350b57cec5SDimitry Andric       dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
4360b57cec5SDimitry Andric   if (!SelfType)
4370b57cec5SDimitry Andric     return false;
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
4400b57cec5SDimitry Andric   if (!ID)
4410b57cec5SDimitry Andric     return false;
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   for (const auto *IvarDecl : ID->ivars()) {
4440b57cec5SDimitry Andric     SVal LV = State->getLValue(IvarDecl, SelfVal);
4450b57cec5SDimitry Andric     if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
4460b57cec5SDimitry Andric       return true;
4470b57cec5SDimitry Andric     }
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric   return false;
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
4530b57cec5SDimitry Andric                                     CheckerContext &C) {
4540b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
4550b57cec5SDimitry Andric     return true;
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   const LocationContext *LocCtxt = C.getLocationContext();
4580b57cec5SDimitry Andric   const Decl *D = LocCtxt->getDecl();
4590b57cec5SDimitry Andric   if (!D)
4600b57cec5SDimitry Andric     return false;
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   ArrayRef<ParmVarDecl*> Params;
4630b57cec5SDimitry Andric   if (const auto *BD = dyn_cast<BlockDecl>(D))
4640b57cec5SDimitry Andric     Params = BD->parameters();
4650b57cec5SDimitry Andric   else if (const auto *FD = dyn_cast<FunctionDecl>(D))
4660b57cec5SDimitry Andric     Params = FD->parameters();
4670b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
4680b57cec5SDimitry Andric     Params = MD->parameters();
4690b57cec5SDimitry Andric   else
4700b57cec5SDimitry Andric     return false;
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
4730b57cec5SDimitry Andric       checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
4740b57cec5SDimitry Andric     if (!N->isSink())
4750b57cec5SDimitry Andric       C.addTransition(State->set<InvariantViolated>(true), N);
4760b57cec5SDimitry Andric     return true;
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric   return false;
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4815ffd83dbSDimitry Andric void NullabilityChecker::reportBugIfInvariantHolds(
4825ffd83dbSDimitry Andric     StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
4835ffd83dbSDimitry Andric     const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
4845ffd83dbSDimitry Andric     bool SuppressPath) const {
4850b57cec5SDimitry Andric   ProgramStateRef OriginalState = N->getState();
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   if (checkInvariantViolation(OriginalState, N, C))
4880b57cec5SDimitry Andric     return;
4890b57cec5SDimitry Andric   if (SuppressPath) {
4900b57cec5SDimitry Andric     OriginalState = OriginalState->set<InvariantViolated>(true);
4910b57cec5SDimitry Andric     N = C.addTransition(OriginalState, N);
4920b57cec5SDimitry Andric   }
4930b57cec5SDimitry Andric 
4945ffd83dbSDimitry Andric   reportBug(Msg, Error, CK, N, Region, C.getBugReporter(), ValueExpr);
4950b57cec5SDimitry Andric }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric /// Cleaning up the program state.
4980b57cec5SDimitry Andric void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
4990b57cec5SDimitry Andric                                           CheckerContext &C) const {
5000b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
5010b57cec5SDimitry Andric   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
50206c3fb27SDimitry Andric   for (const MemRegion *Reg : llvm::make_first_range(Nullabilities)) {
50306c3fb27SDimitry Andric     const auto *Region = Reg->getAs<SymbolicRegion>();
5040b57cec5SDimitry Andric     assert(Region && "Non-symbolic region is tracked.");
5050b57cec5SDimitry Andric     if (SR.isDead(Region->getSymbol())) {
50606c3fb27SDimitry Andric       State = State->remove<NullabilityMap>(Reg);
5070b57cec5SDimitry Andric     }
5080b57cec5SDimitry Andric   }
509bdd1243dSDimitry Andric 
510bdd1243dSDimitry Andric   // When an object goes out of scope, we can free the history associated
511bdd1243dSDimitry Andric   // with any property accesses on that object
512bdd1243dSDimitry Andric   PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
51306c3fb27SDimitry Andric   for (ObjectPropPair PropKey : llvm::make_first_range(PropertyAccesses)) {
51406c3fb27SDimitry Andric     const MemRegion *ReceiverRegion = PropKey.first;
515bdd1243dSDimitry Andric     if (!SR.isLiveRegion(ReceiverRegion)) {
51606c3fb27SDimitry Andric       State = State->remove<PropertyAccessesMap>(PropKey);
517bdd1243dSDimitry Andric     }
518bdd1243dSDimitry Andric   }
519bdd1243dSDimitry Andric 
5200b57cec5SDimitry Andric   // When one of the nonnull arguments are constrained to be null, nullability
5210b57cec5SDimitry Andric   // preconditions are violated. It is not enough to check this only when we
5220b57cec5SDimitry Andric   // actually report an error, because at that time interesting symbols might be
5230b57cec5SDimitry Andric   // reaped.
5240b57cec5SDimitry Andric   if (checkInvariantViolation(State, C.getPredecessor(), C))
5250b57cec5SDimitry Andric     return;
5260b57cec5SDimitry Andric   C.addTransition(State);
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric /// This callback triggers when a pointer is dereferenced and the analyzer does
5300b57cec5SDimitry Andric /// not know anything about the value of that pointer. When that pointer is
5310b57cec5SDimitry Andric /// nullable, this code emits a warning.
5320b57cec5SDimitry Andric void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
5330b57cec5SDimitry Andric   if (Event.SinkNode->getState()->get<InvariantViolated>())
5340b57cec5SDimitry Andric     return;
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric   const MemRegion *Region =
5370b57cec5SDimitry Andric       getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
5380b57cec5SDimitry Andric   if (!Region)
5390b57cec5SDimitry Andric     return;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   ProgramStateRef State = Event.SinkNode->getState();
5420b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
5430b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   if (!TrackedNullability)
5460b57cec5SDimitry Andric     return;
5470b57cec5SDimitry Andric 
5485ffd83dbSDimitry Andric   if (ChecksEnabled[CK_NullableDereferenced] &&
5490b57cec5SDimitry Andric       TrackedNullability->getValue() == Nullability::Nullable) {
5500b57cec5SDimitry Andric     BugReporter &BR = *Event.BR;
5510b57cec5SDimitry Andric     // Do not suppress errors on defensive code paths, because dereferencing
5520b57cec5SDimitry Andric     // a nullable pointer is always an error.
5530b57cec5SDimitry Andric     if (Event.IsDirectDereference)
5540b57cec5SDimitry Andric       reportBug("Nullable pointer is dereferenced",
5555ffd83dbSDimitry Andric                 ErrorKind::NullableDereferenced, CK_NullableDereferenced,
5565ffd83dbSDimitry Andric                 Event.SinkNode, Region, BR);
5570b57cec5SDimitry Andric     else {
5580b57cec5SDimitry Andric       reportBug("Nullable pointer is passed to a callee that requires a "
5595ffd83dbSDimitry Andric                 "non-null",
5605ffd83dbSDimitry Andric                 ErrorKind::NullablePassedToNonnull, CK_NullableDereferenced,
5610b57cec5SDimitry Andric                 Event.SinkNode, Region, BR);
5620b57cec5SDimitry Andric     }
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric 
56606c3fb27SDimitry Andric void NullabilityChecker::checkBeginFunction(CheckerContext &C) const {
56706c3fb27SDimitry Andric   if (!C.inTopFrame())
56806c3fb27SDimitry Andric     return;
56906c3fb27SDimitry Andric 
57006c3fb27SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
57106c3fb27SDimitry Andric   auto AbstractCall = AnyCall::forDecl(LCtx->getDecl());
57206c3fb27SDimitry Andric   if (!AbstractCall || AbstractCall->parameters().empty())
57306c3fb27SDimitry Andric     return;
57406c3fb27SDimitry Andric 
57506c3fb27SDimitry Andric   ProgramStateRef State = C.getState();
57606c3fb27SDimitry Andric   for (const ParmVarDecl *Param : AbstractCall->parameters()) {
57706c3fb27SDimitry Andric     if (!isValidPointerType(Param->getType()))
57806c3fb27SDimitry Andric       continue;
57906c3fb27SDimitry Andric 
58006c3fb27SDimitry Andric     Nullability RequiredNullability =
58106c3fb27SDimitry Andric         getNullabilityAnnotation(Param->getType());
58206c3fb27SDimitry Andric     if (RequiredNullability != Nullability::Nullable)
58306c3fb27SDimitry Andric       continue;
58406c3fb27SDimitry Andric 
58506c3fb27SDimitry Andric     const VarRegion *ParamRegion = State->getRegion(Param, LCtx);
58606c3fb27SDimitry Andric     const MemRegion *ParamPointeeRegion =
58706c3fb27SDimitry Andric         State->getSVal(ParamRegion).getAsRegion();
58806c3fb27SDimitry Andric     if (!ParamPointeeRegion)
58906c3fb27SDimitry Andric       continue;
59006c3fb27SDimitry Andric 
59106c3fb27SDimitry Andric     State = State->set<NullabilityMap>(ParamPointeeRegion,
59206c3fb27SDimitry Andric                                        NullabilityState(RequiredNullability));
59306c3fb27SDimitry Andric   }
59406c3fb27SDimitry Andric   C.addTransition(State);
59506c3fb27SDimitry Andric }
59606c3fb27SDimitry Andric 
5975ffd83dbSDimitry Andric // Whenever we see a load from a typed memory region that's been annotated as
5985ffd83dbSDimitry Andric // 'nonnull', we want to trust the user on that and assume that it is is indeed
5995ffd83dbSDimitry Andric // non-null.
6005ffd83dbSDimitry Andric //
6015ffd83dbSDimitry Andric // We do so even if the value is known to have been assigned to null.
6025ffd83dbSDimitry Andric // The user should be warned on assigning the null value to a non-null pointer
6035ffd83dbSDimitry Andric // as opposed to warning on the later dereference of this pointer.
6045ffd83dbSDimitry Andric //
6055ffd83dbSDimitry Andric // \code
6065ffd83dbSDimitry Andric //   int * _Nonnull var = 0; // we want to warn the user here...
6075ffd83dbSDimitry Andric //   // . . .
6085ffd83dbSDimitry Andric //   *var = 42;              // ...and not here
6095ffd83dbSDimitry Andric // \endcode
6105ffd83dbSDimitry Andric void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
6115ffd83dbSDimitry Andric                                        const Stmt *S,
6125ffd83dbSDimitry Andric                                        CheckerContext &Context) const {
6135ffd83dbSDimitry Andric   // We should care only about loads.
6145ffd83dbSDimitry Andric   // The main idea is to add a constraint whenever we're loading a value from
6155ffd83dbSDimitry Andric   // an annotated pointer type.
6165ffd83dbSDimitry Andric   if (!IsLoad)
6175ffd83dbSDimitry Andric     return;
6185ffd83dbSDimitry Andric 
6195ffd83dbSDimitry Andric   // Annotations that we want to consider make sense only for types.
6205ffd83dbSDimitry Andric   const auto *Region =
6215ffd83dbSDimitry Andric       dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
6225ffd83dbSDimitry Andric   if (!Region)
6235ffd83dbSDimitry Andric     return;
6245ffd83dbSDimitry Andric 
6255ffd83dbSDimitry Andric   ProgramStateRef State = Context.getState();
6265ffd83dbSDimitry Andric 
6275ffd83dbSDimitry Andric   auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
6285ffd83dbSDimitry Andric   if (!StoredVal)
6295ffd83dbSDimitry Andric     return;
6305ffd83dbSDimitry Andric 
6315ffd83dbSDimitry Andric   Nullability NullabilityOfTheLoadedValue =
6325ffd83dbSDimitry Andric       getNullabilityAnnotation(Region->getValueType());
6335ffd83dbSDimitry Andric 
6345ffd83dbSDimitry Andric   if (NullabilityOfTheLoadedValue == Nullability::Nonnull) {
6355ffd83dbSDimitry Andric     // It doesn't matter what we think about this particular pointer, it should
6365ffd83dbSDimitry Andric     // be considered non-null as annotated by the developer.
6375ffd83dbSDimitry Andric     if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
6385ffd83dbSDimitry Andric       Context.addTransition(NewState);
6395ffd83dbSDimitry Andric     }
6405ffd83dbSDimitry Andric   }
6415ffd83dbSDimitry Andric }
6425ffd83dbSDimitry Andric 
6430b57cec5SDimitry Andric /// Find the outermost subexpression of E that is not an implicit cast.
6440b57cec5SDimitry Andric /// This looks through the implicit casts to _Nonnull that ARC adds to
6450b57cec5SDimitry Andric /// return expressions of ObjC types when the return type of the function or
6460b57cec5SDimitry Andric /// method is non-null but the express is not.
6470b57cec5SDimitry Andric static const Expr *lookThroughImplicitCasts(const Expr *E) {
6485ffd83dbSDimitry Andric   return E->IgnoreImpCasts();
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric /// This method check when nullable pointer or null value is returned from a
6520b57cec5SDimitry Andric /// function that has nonnull return type.
6530b57cec5SDimitry Andric void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
6540b57cec5SDimitry Andric                                       CheckerContext &C) const {
6550b57cec5SDimitry Andric   auto RetExpr = S->getRetValue();
6560b57cec5SDimitry Andric   if (!RetExpr)
6570b57cec5SDimitry Andric     return;
6580b57cec5SDimitry Andric 
65906c3fb27SDimitry Andric   if (!isValidPointerType(RetExpr->getType()))
6600b57cec5SDimitry Andric     return;
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
6630b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
6640b57cec5SDimitry Andric     return;
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
6670b57cec5SDimitry Andric   if (!RetSVal)
6680b57cec5SDimitry Andric     return;
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   bool InSuppressedMethodFamily = false;
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   QualType RequiredRetType;
6730b57cec5SDimitry Andric   AnalysisDeclContext *DeclCtxt =
6740b57cec5SDimitry Andric       C.getLocationContext()->getAnalysisDeclContext();
6750b57cec5SDimitry Andric   const Decl *D = DeclCtxt->getDecl();
6760b57cec5SDimitry Andric   if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
6770b57cec5SDimitry Andric     // HACK: This is a big hammer to avoid warning when there are defensive
6780b57cec5SDimitry Andric     // nil checks in -init and -copy methods. We should add more sophisticated
6790b57cec5SDimitry Andric     // logic here to suppress on common defensive idioms but still
6800b57cec5SDimitry Andric     // warn when there is a likely problem.
6810b57cec5SDimitry Andric     ObjCMethodFamily Family = MD->getMethodFamily();
6820b57cec5SDimitry Andric     if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
6830b57cec5SDimitry Andric       InSuppressedMethodFamily = true;
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric     RequiredRetType = MD->getReturnType();
6860b57cec5SDimitry Andric   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6870b57cec5SDimitry Andric     RequiredRetType = FD->getReturnType();
6880b57cec5SDimitry Andric   } else {
6890b57cec5SDimitry Andric     return;
6900b57cec5SDimitry Andric   }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   NullConstraint Nullness = getNullConstraint(*RetSVal, State);
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric   Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   // If the returned value is null but the type of the expression
6970b57cec5SDimitry Andric   // generating it is nonnull then we will suppress the diagnostic.
6980b57cec5SDimitry Andric   // This enables explicit suppression when returning a nil literal in a
6990b57cec5SDimitry Andric   // function with a _Nonnull return type:
7000b57cec5SDimitry Andric   //    return (NSString * _Nonnull)0;
7010b57cec5SDimitry Andric   Nullability RetExprTypeLevelNullability =
7020b57cec5SDimitry Andric         getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
7050b57cec5SDimitry Andric                                   Nullness == NullConstraint::IsNull);
7065ffd83dbSDimitry Andric   if (ChecksEnabled[CK_NullReturnedFromNonnull] && NullReturnedFromNonNull &&
7070b57cec5SDimitry Andric       RetExprTypeLevelNullability != Nullability::Nonnull &&
7085ffd83dbSDimitry Andric       !InSuppressedMethodFamily && C.getLocationContext()->inTopFrame()) {
7090b57cec5SDimitry Andric     static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
7100b57cec5SDimitry Andric     ExplodedNode *N = C.generateErrorNode(State, &Tag);
7110b57cec5SDimitry Andric     if (!N)
7120b57cec5SDimitry Andric       return;
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric     SmallString<256> SBuf;
7150b57cec5SDimitry Andric     llvm::raw_svector_ostream OS(SBuf);
7160b57cec5SDimitry Andric     OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
7170b57cec5SDimitry Andric     OS << " returned from a " << C.getDeclDescription(D) <<
7180b57cec5SDimitry Andric           " that is expected to return a non-null value";
7195ffd83dbSDimitry Andric     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
7205ffd83dbSDimitry Andric                               CK_NullReturnedFromNonnull, N, nullptr, C,
7210b57cec5SDimitry Andric                               RetExpr);
7220b57cec5SDimitry Andric     return;
7230b57cec5SDimitry Andric   }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   // If null was returned from a non-null function, mark the nullability
7260b57cec5SDimitry Andric   // invariant as violated even if the diagnostic was suppressed.
7270b57cec5SDimitry Andric   if (NullReturnedFromNonNull) {
7280b57cec5SDimitry Andric     State = State->set<InvariantViolated>(true);
7290b57cec5SDimitry Andric     C.addTransition(State);
7300b57cec5SDimitry Andric     return;
7310b57cec5SDimitry Andric   }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   const MemRegion *Region = getTrackRegion(*RetSVal);
7340b57cec5SDimitry Andric   if (!Region)
7350b57cec5SDimitry Andric     return;
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
7380b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
7390b57cec5SDimitry Andric   if (TrackedNullability) {
7400b57cec5SDimitry Andric     Nullability TrackedNullabValue = TrackedNullability->getValue();
7415ffd83dbSDimitry Andric     if (ChecksEnabled[CK_NullableReturnedFromNonnull] &&
7420b57cec5SDimitry Andric         Nullness != NullConstraint::IsNotNull &&
7430b57cec5SDimitry Andric         TrackedNullabValue == Nullability::Nullable &&
7440b57cec5SDimitry Andric         RequiredNullability == Nullability::Nonnull) {
7450b57cec5SDimitry Andric       static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
7460b57cec5SDimitry Andric       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric       SmallString<256> SBuf;
7490b57cec5SDimitry Andric       llvm::raw_svector_ostream OS(SBuf);
7500b57cec5SDimitry Andric       OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
7510b57cec5SDimitry Andric             " that is expected to return a non-null value";
7520b57cec5SDimitry Andric 
7535ffd83dbSDimitry Andric       reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
7545ffd83dbSDimitry Andric                                 CK_NullableReturnedFromNonnull, N, Region, C);
7550b57cec5SDimitry Andric     }
7560b57cec5SDimitry Andric     return;
7570b57cec5SDimitry Andric   }
7580b57cec5SDimitry Andric   if (RequiredNullability == Nullability::Nullable) {
7590b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region,
7600b57cec5SDimitry Andric                                        NullabilityState(RequiredNullability,
7610b57cec5SDimitry Andric                                                         S));
7620b57cec5SDimitry Andric     C.addTransition(State);
7630b57cec5SDimitry Andric   }
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric /// This callback warns when a nullable pointer or a null value is passed to a
7670b57cec5SDimitry Andric /// function that expects its argument to be nonnull.
7680b57cec5SDimitry Andric void NullabilityChecker::checkPreCall(const CallEvent &Call,
7690b57cec5SDimitry Andric                                       CheckerContext &C) const {
7700b57cec5SDimitry Andric   if (!Call.getDecl())
7710b57cec5SDimitry Andric     return;
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
7740b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
7750b57cec5SDimitry Andric     return;
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   ProgramStateRef OrigState = State;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   unsigned Idx = 0;
7800b57cec5SDimitry Andric   for (const ParmVarDecl *Param : Call.parameters()) {
7810b57cec5SDimitry Andric     if (Param->isParameterPack())
7820b57cec5SDimitry Andric       break;
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     if (Idx >= Call.getNumArgs())
7850b57cec5SDimitry Andric       break;
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric     const Expr *ArgExpr = Call.getArgExpr(Idx);
7880b57cec5SDimitry Andric     auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
7890b57cec5SDimitry Andric     if (!ArgSVal)
7900b57cec5SDimitry Andric       continue;
7910b57cec5SDimitry Andric 
79206c3fb27SDimitry Andric     if (!isValidPointerType(Param->getType()) &&
7930b57cec5SDimitry Andric         !Param->getType()->isReferenceType())
7940b57cec5SDimitry Andric       continue;
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric     NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric     Nullability RequiredNullability =
7990b57cec5SDimitry Andric         getNullabilityAnnotation(Param->getType());
8000b57cec5SDimitry Andric     Nullability ArgExprTypeLevelNullability =
80106c3fb27SDimitry Andric         getNullabilityAnnotation(lookThroughImplicitCasts(ArgExpr)->getType());
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric     unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
8040b57cec5SDimitry Andric 
8055ffd83dbSDimitry Andric     if (ChecksEnabled[CK_NullPassedToNonnull] &&
8065ffd83dbSDimitry Andric         Nullness == NullConstraint::IsNull &&
8070b57cec5SDimitry Andric         ArgExprTypeLevelNullability != Nullability::Nonnull &&
8080b57cec5SDimitry Andric         RequiredNullability == Nullability::Nonnull &&
8090b57cec5SDimitry Andric         isDiagnosableCall(Call)) {
8100b57cec5SDimitry Andric       ExplodedNode *N = C.generateErrorNode(State);
8110b57cec5SDimitry Andric       if (!N)
8120b57cec5SDimitry Andric         return;
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric       SmallString<256> SBuf;
8150b57cec5SDimitry Andric       llvm::raw_svector_ostream OS(SBuf);
8160b57cec5SDimitry Andric       OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
8170b57cec5SDimitry Andric       OS << " passed to a callee that requires a non-null " << ParamIdx
8180b57cec5SDimitry Andric          << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
8195ffd83dbSDimitry Andric       reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
8205ffd83dbSDimitry Andric                                 CK_NullPassedToNonnull, N, nullptr, C, ArgExpr,
8215ffd83dbSDimitry Andric                                 /*SuppressPath=*/false);
8220b57cec5SDimitry Andric       return;
8230b57cec5SDimitry Andric     }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric     const MemRegion *Region = getTrackRegion(*ArgSVal);
8260b57cec5SDimitry Andric     if (!Region)
8270b57cec5SDimitry Andric       continue;
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric     const NullabilityState *TrackedNullability =
8300b57cec5SDimitry Andric         State->get<NullabilityMap>(Region);
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric     if (TrackedNullability) {
8330b57cec5SDimitry Andric       if (Nullness == NullConstraint::IsNotNull ||
8340b57cec5SDimitry Andric           TrackedNullability->getValue() != Nullability::Nullable)
8350b57cec5SDimitry Andric         continue;
8360b57cec5SDimitry Andric 
8375ffd83dbSDimitry Andric       if (ChecksEnabled[CK_NullablePassedToNonnull] &&
8380b57cec5SDimitry Andric           RequiredNullability == Nullability::Nonnull &&
8390b57cec5SDimitry Andric           isDiagnosableCall(Call)) {
8400b57cec5SDimitry Andric         ExplodedNode *N = C.addTransition(State);
8410b57cec5SDimitry Andric         SmallString<256> SBuf;
8420b57cec5SDimitry Andric         llvm::raw_svector_ostream OS(SBuf);
8430b57cec5SDimitry Andric         OS << "Nullable pointer is passed to a callee that requires a non-null "
8440b57cec5SDimitry Andric            << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
8455ffd83dbSDimitry Andric         reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
8465ffd83dbSDimitry Andric                                   CK_NullablePassedToNonnull, N, Region, C,
8475ffd83dbSDimitry Andric                                   ArgExpr, /*SuppressPath=*/true);
8480b57cec5SDimitry Andric         return;
8490b57cec5SDimitry Andric       }
8505ffd83dbSDimitry Andric       if (ChecksEnabled[CK_NullableDereferenced] &&
8510b57cec5SDimitry Andric           Param->getType()->isReferenceType()) {
8520b57cec5SDimitry Andric         ExplodedNode *N = C.addTransition(State);
8530b57cec5SDimitry Andric         reportBugIfInvariantHolds("Nullable pointer is dereferenced",
8545ffd83dbSDimitry Andric                                   ErrorKind::NullableDereferenced,
8555ffd83dbSDimitry Andric                                   CK_NullableDereferenced, N, Region, C,
8565ffd83dbSDimitry Andric                                   ArgExpr, /*SuppressPath=*/true);
8570b57cec5SDimitry Andric         return;
8580b57cec5SDimitry Andric       }
8590b57cec5SDimitry Andric       continue;
8600b57cec5SDimitry Andric     }
8610b57cec5SDimitry Andric   }
8620b57cec5SDimitry Andric   if (State != OrigState)
8630b57cec5SDimitry Andric     C.addTransition(State);
8640b57cec5SDimitry Andric }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric /// Suppress the nullability warnings for some functions.
8670b57cec5SDimitry Andric void NullabilityChecker::checkPostCall(const CallEvent &Call,
8680b57cec5SDimitry Andric                                        CheckerContext &C) const {
8690b57cec5SDimitry Andric   auto Decl = Call.getDecl();
8700b57cec5SDimitry Andric   if (!Decl)
8710b57cec5SDimitry Andric     return;
8720b57cec5SDimitry Andric   // ObjC Messages handles in a different callback.
8730b57cec5SDimitry Andric   if (Call.getKind() == CE_ObjCMessage)
8740b57cec5SDimitry Andric     return;
8750b57cec5SDimitry Andric   const FunctionType *FuncType = Decl->getFunctionType();
8760b57cec5SDimitry Andric   if (!FuncType)
8770b57cec5SDimitry Andric     return;
8780b57cec5SDimitry Andric   QualType ReturnType = FuncType->getReturnType();
87906c3fb27SDimitry Andric   if (!isValidPointerType(ReturnType))
8800b57cec5SDimitry Andric     return;
8810b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
8820b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
8830b57cec5SDimitry Andric     return;
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric   const MemRegion *Region = getTrackRegion(Call.getReturnValue());
8860b57cec5SDimitry Andric   if (!Region)
8870b57cec5SDimitry Andric     return;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // CG headers are misannotated. Do not warn for symbols that are the results
8900b57cec5SDimitry Andric   // of CG calls.
8910b57cec5SDimitry Andric   const SourceManager &SM = C.getSourceManager();
8920b57cec5SDimitry Andric   StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
8935f757f3fSDimitry Andric   if (llvm::sys::path::filename(FilePath).starts_with("CG")) {
8940b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
8950b57cec5SDimitry Andric     C.addTransition(State);
8960b57cec5SDimitry Andric     return;
8970b57cec5SDimitry Andric   }
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
9000b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
9010b57cec5SDimitry Andric 
9025f757f3fSDimitry Andric   // ObjCMessageExpr gets the actual type through
9035f757f3fSDimitry Andric   // Sema::getMessageSendResultType, instead of using the return type of
9045f757f3fSDimitry Andric   // MethodDecl directly. The final type is generated by considering the
9055f757f3fSDimitry Andric   // nullability of receiver and MethodDecl together. Thus, The type of
9065f757f3fSDimitry Andric   // ObjCMessageExpr is prefer.
9075f757f3fSDimitry Andric   if (const Expr *E = Call.getOriginExpr())
9085f757f3fSDimitry Andric     ReturnType = E->getType();
9095f757f3fSDimitry Andric 
9100b57cec5SDimitry Andric   if (!TrackedNullability &&
9110b57cec5SDimitry Andric       getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
9120b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region, Nullability::Nullable);
9130b57cec5SDimitry Andric     C.addTransition(State);
9140b57cec5SDimitry Andric   }
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric static Nullability getReceiverNullability(const ObjCMethodCall &M,
9180b57cec5SDimitry Andric                                           ProgramStateRef State) {
9190b57cec5SDimitry Andric   if (M.isReceiverSelfOrSuper()) {
9200b57cec5SDimitry Andric     // For super and super class receivers we assume that the receiver is
9210b57cec5SDimitry Andric     // nonnull.
9220b57cec5SDimitry Andric     return Nullability::Nonnull;
9230b57cec5SDimitry Andric   }
9240b57cec5SDimitry Andric   // Otherwise look up nullability in the state.
9250b57cec5SDimitry Andric   SVal Receiver = M.getReceiverSVal();
9260b57cec5SDimitry Andric   if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
9270b57cec5SDimitry Andric     // If the receiver is constrained to be nonnull, assume that it is nonnull
9280b57cec5SDimitry Andric     // regardless of its type.
9290b57cec5SDimitry Andric     NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
9300b57cec5SDimitry Andric     if (Nullness == NullConstraint::IsNotNull)
9310b57cec5SDimitry Andric       return Nullability::Nonnull;
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric   auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
9340b57cec5SDimitry Andric   if (ValueRegionSVal) {
9350b57cec5SDimitry Andric     const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
9360b57cec5SDimitry Andric     assert(SelfRegion);
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric     const NullabilityState *TrackedSelfNullability =
9390b57cec5SDimitry Andric         State->get<NullabilityMap>(SelfRegion);
9400b57cec5SDimitry Andric     if (TrackedSelfNullability)
9410b57cec5SDimitry Andric       return TrackedSelfNullability->getValue();
9420b57cec5SDimitry Andric   }
9430b57cec5SDimitry Andric   return Nullability::Unspecified;
9440b57cec5SDimitry Andric }
9450b57cec5SDimitry Andric 
946bdd1243dSDimitry Andric // The return value of a property access is typically a temporary value which
947bdd1243dSDimitry Andric // will not be tracked in a persistent manner by the analyzer.  We use
948bdd1243dSDimitry Andric // evalAssume() in order to immediately record constraints on those temporaries
949bdd1243dSDimitry Andric // at the time they are imposed (e.g. by a nil-check conditional).
950bdd1243dSDimitry Andric ProgramStateRef NullabilityChecker::evalAssume(ProgramStateRef State, SVal Cond,
951bdd1243dSDimitry Andric                                                bool Assumption) const {
952bdd1243dSDimitry Andric   PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
95306c3fb27SDimitry Andric   for (auto [PropKey, PropVal] : PropertyAccesses) {
95406c3fb27SDimitry Andric     if (!PropVal.isConstrainedNonnull) {
95506c3fb27SDimitry Andric       ConditionTruthVal IsNonNull = State->isNonNull(PropVal.Value);
956bdd1243dSDimitry Andric       if (IsNonNull.isConstrainedTrue()) {
95706c3fb27SDimitry Andric         ConstrainedPropertyVal Replacement = PropVal;
958bdd1243dSDimitry Andric         Replacement.isConstrainedNonnull = true;
95906c3fb27SDimitry Andric         State = State->set<PropertyAccessesMap>(PropKey, Replacement);
960bdd1243dSDimitry Andric       } else if (IsNonNull.isConstrainedFalse()) {
961bdd1243dSDimitry Andric         // Space optimization: no point in tracking constrained-null cases
96206c3fb27SDimitry Andric         State = State->remove<PropertyAccessesMap>(PropKey);
963bdd1243dSDimitry Andric       }
964bdd1243dSDimitry Andric     }
965bdd1243dSDimitry Andric   }
966bdd1243dSDimitry Andric 
967bdd1243dSDimitry Andric   return State;
968bdd1243dSDimitry Andric }
969bdd1243dSDimitry Andric 
9700b57cec5SDimitry Andric /// Calculate the nullability of the result of a message expr based on the
9710b57cec5SDimitry Andric /// nullability of the receiver, the nullability of the return value, and the
9720b57cec5SDimitry Andric /// constraints.
9730b57cec5SDimitry Andric void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
9740b57cec5SDimitry Andric                                               CheckerContext &C) const {
9750b57cec5SDimitry Andric   auto Decl = M.getDecl();
9760b57cec5SDimitry Andric   if (!Decl)
9770b57cec5SDimitry Andric     return;
9780b57cec5SDimitry Andric   QualType RetType = Decl->getReturnType();
97906c3fb27SDimitry Andric   if (!isValidPointerType(RetType))
9800b57cec5SDimitry Andric     return;
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
9830b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
9840b57cec5SDimitry Andric     return;
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
9870b57cec5SDimitry Andric   if (!ReturnRegion)
9880b57cec5SDimitry Andric     return;
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric   auto Interface = Decl->getClassInterface();
9910b57cec5SDimitry Andric   auto Name = Interface ? Interface->getName() : "";
9920b57cec5SDimitry Andric   // In order to reduce the noise in the diagnostics generated by this checker,
9930b57cec5SDimitry Andric   // some framework and programming style based heuristics are used. These
9940b57cec5SDimitry Andric   // heuristics are for Cocoa APIs which have NS prefix.
9955f757f3fSDimitry Andric   if (Name.starts_with("NS")) {
9960b57cec5SDimitry Andric     // Developers rely on dynamic invariants such as an item should be available
9970b57cec5SDimitry Andric     // in a collection, or a collection is not empty often. Those invariants can
9980b57cec5SDimitry Andric     // not be inferred by any static analysis tool. To not to bother the users
9990b57cec5SDimitry Andric     // with too many false positives, every item retrieval function should be
10000b57cec5SDimitry Andric     // ignored for collections. The instance methods of dictionaries in Cocoa
10010b57cec5SDimitry Andric     // are either item retrieval related or not interesting nullability wise.
10020b57cec5SDimitry Andric     // Using this fact, to keep the code easier to read just ignore the return
10030b57cec5SDimitry Andric     // value of every instance method of dictionaries.
10040b57cec5SDimitry Andric     if (M.isInstanceMessage() && Name.contains("Dictionary")) {
10050b57cec5SDimitry Andric       State =
10060b57cec5SDimitry Andric           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
10070b57cec5SDimitry Andric       C.addTransition(State);
10080b57cec5SDimitry Andric       return;
10090b57cec5SDimitry Andric     }
10100b57cec5SDimitry Andric     // For similar reasons ignore some methods of Cocoa arrays.
10110b57cec5SDimitry Andric     StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
10120b57cec5SDimitry Andric     if (Name.contains("Array") &&
10130b57cec5SDimitry Andric         (FirstSelectorSlot == "firstObject" ||
10140b57cec5SDimitry Andric          FirstSelectorSlot == "lastObject")) {
10150b57cec5SDimitry Andric       State =
10160b57cec5SDimitry Andric           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
10170b57cec5SDimitry Andric       C.addTransition(State);
10180b57cec5SDimitry Andric       return;
10190b57cec5SDimitry Andric     }
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric     // Encoding related methods of string should not fail when lossless
10220b57cec5SDimitry Andric     // encodings are used. Using lossless encodings is so frequent that ignoring
10230b57cec5SDimitry Andric     // this class of methods reduced the emitted diagnostics by about 30% on
10240b57cec5SDimitry Andric     // some projects (and all of that was false positives).
10250b57cec5SDimitry Andric     if (Name.contains("String")) {
1026bdd1243dSDimitry Andric       for (auto *Param : M.parameters()) {
10270b57cec5SDimitry Andric         if (Param->getName() == "encoding") {
10280b57cec5SDimitry Andric           State = State->set<NullabilityMap>(ReturnRegion,
10290b57cec5SDimitry Andric                                              Nullability::Contradicted);
10300b57cec5SDimitry Andric           C.addTransition(State);
10310b57cec5SDimitry Andric           return;
10320b57cec5SDimitry Andric         }
10330b57cec5SDimitry Andric       }
10340b57cec5SDimitry Andric     }
10350b57cec5SDimitry Andric   }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric   const ObjCMessageExpr *Message = M.getOriginExpr();
10380b57cec5SDimitry Andric   Nullability SelfNullability = getReceiverNullability(M, State);
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric   const NullabilityState *NullabilityOfReturn =
10410b57cec5SDimitry Andric       State->get<NullabilityMap>(ReturnRegion);
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   if (NullabilityOfReturn) {
10440b57cec5SDimitry Andric     // When we have a nullability tracked for the return value, the nullability
10450b57cec5SDimitry Andric     // of the expression will be the most nullable of the receiver and the
10460b57cec5SDimitry Andric     // return value.
10470b57cec5SDimitry Andric     Nullability RetValTracked = NullabilityOfReturn->getValue();
10480b57cec5SDimitry Andric     Nullability ComputedNullab =
10490b57cec5SDimitry Andric         getMostNullable(RetValTracked, SelfNullability);
10500b57cec5SDimitry Andric     if (ComputedNullab != RetValTracked &&
10510b57cec5SDimitry Andric         ComputedNullab != Nullability::Unspecified) {
10520b57cec5SDimitry Andric       const Stmt *NullabilitySource =
10530b57cec5SDimitry Andric           ComputedNullab == RetValTracked
10540b57cec5SDimitry Andric               ? NullabilityOfReturn->getNullabilitySource()
10550b57cec5SDimitry Andric               : Message->getInstanceReceiver();
10560b57cec5SDimitry Andric       State = State->set<NullabilityMap>(
10570b57cec5SDimitry Andric           ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
10580b57cec5SDimitry Andric       C.addTransition(State);
10590b57cec5SDimitry Andric     }
10600b57cec5SDimitry Andric     return;
10610b57cec5SDimitry Andric   }
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric   // No tracked information. Use static type information for return value.
10645f757f3fSDimitry Andric   Nullability RetNullability = getNullabilityAnnotation(Message->getType());
10650b57cec5SDimitry Andric 
1066bdd1243dSDimitry Andric   // Properties might be computed, which means the property value could
1067bdd1243dSDimitry Andric   // theoretically change between calls even in commonly-observed cases like
1068bdd1243dSDimitry Andric   // this:
1069bdd1243dSDimitry Andric   //
1070bdd1243dSDimitry Andric   //     if (foo.prop) {    // ok, it's nonnull here...
1071bdd1243dSDimitry Andric   //         [bar doStuffWithNonnullVal:foo.prop];     // ...but what about
1072bdd1243dSDimitry Andric   //         here?
1073bdd1243dSDimitry Andric   //     }
1074bdd1243dSDimitry Andric   //
1075bdd1243dSDimitry Andric   // If the property is nullable-annotated, a naive analysis would lead to many
1076bdd1243dSDimitry Andric   // false positives despite the presence of probably-correct nil-checks.  To
1077bdd1243dSDimitry Andric   // reduce the false positive rate, we maintain a history of the most recently
1078bdd1243dSDimitry Andric   // observed property value.  For each property access, if the prior value has
1079bdd1243dSDimitry Andric   // been constrained to be not nil then we will conservatively assume that the
1080bdd1243dSDimitry Andric   // next access can be inferred as nonnull.
1081bdd1243dSDimitry Andric   if (RetNullability != Nullability::Nonnull &&
1082bdd1243dSDimitry Andric       M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined) {
1083bdd1243dSDimitry Andric     bool LookupResolved = false;
1084bdd1243dSDimitry Andric     if (const MemRegion *ReceiverRegion = getTrackRegion(M.getReceiverSVal())) {
1085*0fca6ea1SDimitry Andric       if (const IdentifierInfo *Ident =
1086*0fca6ea1SDimitry Andric               M.getSelector().getIdentifierInfoForSlot(0)) {
1087bdd1243dSDimitry Andric         LookupResolved = true;
1088bdd1243dSDimitry Andric         ObjectPropPair Key = std::make_pair(ReceiverRegion, Ident);
1089bdd1243dSDimitry Andric         const ConstrainedPropertyVal *PrevPropVal =
1090bdd1243dSDimitry Andric             State->get<PropertyAccessesMap>(Key);
1091bdd1243dSDimitry Andric         if (PrevPropVal && PrevPropVal->isConstrainedNonnull) {
10920b57cec5SDimitry Andric           RetNullability = Nullability::Nonnull;
1093bdd1243dSDimitry Andric         } else {
1094bdd1243dSDimitry Andric           // If a previous property access was constrained as nonnull, we hold
1095bdd1243dSDimitry Andric           // on to that constraint (effectively inferring that all subsequent
1096bdd1243dSDimitry Andric           // accesses on that code path can be inferred as nonnull).  If the
1097bdd1243dSDimitry Andric           // previous property access was *not* constrained as nonnull, then
1098bdd1243dSDimitry Andric           // let's throw it away in favor of keeping the SVal associated with
1099bdd1243dSDimitry Andric           // this more recent access.
1100bdd1243dSDimitry Andric           if (auto ReturnSVal =
1101bdd1243dSDimitry Andric                   M.getReturnValue().getAs<DefinedOrUnknownSVal>()) {
1102bdd1243dSDimitry Andric             State = State->set<PropertyAccessesMap>(
1103bdd1243dSDimitry Andric                 Key, ConstrainedPropertyVal(*ReturnSVal));
1104bdd1243dSDimitry Andric           }
1105bdd1243dSDimitry Andric         }
1106bdd1243dSDimitry Andric       }
1107bdd1243dSDimitry Andric     }
1108bdd1243dSDimitry Andric 
1109bdd1243dSDimitry Andric     if (!LookupResolved) {
1110bdd1243dSDimitry Andric       // Fallback: err on the side of suppressing the false positive.
1111bdd1243dSDimitry Andric       RetNullability = Nullability::Nonnull;
1112bdd1243dSDimitry Andric     }
1113bdd1243dSDimitry Andric   }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
11160b57cec5SDimitry Andric   if (ComputedNullab == Nullability::Nullable) {
11170b57cec5SDimitry Andric     const Stmt *NullabilitySource = ComputedNullab == RetNullability
11180b57cec5SDimitry Andric                                         ? Message
11190b57cec5SDimitry Andric                                         : Message->getInstanceReceiver();
11200b57cec5SDimitry Andric     State = State->set<NullabilityMap>(
11210b57cec5SDimitry Andric         ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
11220b57cec5SDimitry Andric     C.addTransition(State);
11230b57cec5SDimitry Andric   }
11240b57cec5SDimitry Andric }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric /// Explicit casts are trusted. If there is a disagreement in the nullability
11270b57cec5SDimitry Andric /// annotations in the destination and the source or '0' is casted to nonnull
11280b57cec5SDimitry Andric /// track the value as having contraditory nullability. This will allow users to
11290b57cec5SDimitry Andric /// suppress warnings.
11300b57cec5SDimitry Andric void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
11310b57cec5SDimitry Andric                                        CheckerContext &C) const {
11320b57cec5SDimitry Andric   QualType OriginType = CE->getSubExpr()->getType();
11330b57cec5SDimitry Andric   QualType DestType = CE->getType();
113406c3fb27SDimitry Andric   if (!isValidPointerType(OriginType))
11350b57cec5SDimitry Andric     return;
113606c3fb27SDimitry Andric   if (!isValidPointerType(DestType))
11370b57cec5SDimitry Andric     return;
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
11400b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
11410b57cec5SDimitry Andric     return;
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric   Nullability DestNullability = getNullabilityAnnotation(DestType);
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric   // No explicit nullability in the destination type, so this cast does not
11460b57cec5SDimitry Andric   // change the nullability.
11470b57cec5SDimitry Andric   if (DestNullability == Nullability::Unspecified)
11480b57cec5SDimitry Andric     return;
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
11510b57cec5SDimitry Andric   const MemRegion *Region = getTrackRegion(*RegionSVal);
11520b57cec5SDimitry Andric   if (!Region)
11530b57cec5SDimitry Andric     return;
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   // When 0 is converted to nonnull mark it as contradicted.
11560b57cec5SDimitry Andric   if (DestNullability == Nullability::Nonnull) {
11570b57cec5SDimitry Andric     NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
11580b57cec5SDimitry Andric     if (Nullness == NullConstraint::IsNull) {
11590b57cec5SDimitry Andric       State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
11600b57cec5SDimitry Andric       C.addTransition(State);
11610b57cec5SDimitry Andric       return;
11620b57cec5SDimitry Andric     }
11630b57cec5SDimitry Andric   }
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
11660b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   if (!TrackedNullability) {
11690b57cec5SDimitry Andric     if (DestNullability != Nullability::Nullable)
11700b57cec5SDimitry Andric       return;
11710b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region,
11720b57cec5SDimitry Andric                                        NullabilityState(DestNullability, CE));
11730b57cec5SDimitry Andric     C.addTransition(State);
11740b57cec5SDimitry Andric     return;
11750b57cec5SDimitry Andric   }
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   if (TrackedNullability->getValue() != DestNullability &&
11780b57cec5SDimitry Andric       TrackedNullability->getValue() != Nullability::Contradicted) {
11790b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
11800b57cec5SDimitry Andric     C.addTransition(State);
11810b57cec5SDimitry Andric   }
11820b57cec5SDimitry Andric }
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric /// For a given statement performing a bind, attempt to syntactically
11850b57cec5SDimitry Andric /// match the expression resulting in the bound value.
11860b57cec5SDimitry Andric static const Expr * matchValueExprForBind(const Stmt *S) {
11870b57cec5SDimitry Andric   // For `x = e` the value expression is the right-hand side.
11880b57cec5SDimitry Andric   if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
11890b57cec5SDimitry Andric     if (BinOp->getOpcode() == BO_Assign)
11900b57cec5SDimitry Andric       return BinOp->getRHS();
11910b57cec5SDimitry Andric   }
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric   // For `int x = e` the value expression is the initializer.
11940b57cec5SDimitry Andric   if (auto *DS = dyn_cast<DeclStmt>(S))  {
11950b57cec5SDimitry Andric     if (DS->isSingleDecl()) {
11960b57cec5SDimitry Andric       auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
11970b57cec5SDimitry Andric       if (!VD)
11980b57cec5SDimitry Andric         return nullptr;
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric       if (const Expr *Init = VD->getInit())
12010b57cec5SDimitry Andric         return Init;
12020b57cec5SDimitry Andric     }
12030b57cec5SDimitry Andric   }
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric   return nullptr;
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric /// Returns true if \param S is a DeclStmt for a local variable that
12090b57cec5SDimitry Andric /// ObjC automated reference counting initialized with zero.
12100b57cec5SDimitry Andric static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
12110b57cec5SDimitry Andric   // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
12120b57cec5SDimitry Andric   // prevents false positives when a _Nonnull local variable cannot be
12130b57cec5SDimitry Andric   // initialized with an initialization expression:
12140b57cec5SDimitry Andric   //    NSString * _Nonnull s; // no-warning
12150b57cec5SDimitry Andric   //    @autoreleasepool {
12160b57cec5SDimitry Andric   //      s = ...
12170b57cec5SDimitry Andric   //    }
12180b57cec5SDimitry Andric   //
12190b57cec5SDimitry Andric   // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
12200b57cec5SDimitry Andric   // uninitialized in Sema's UninitializedValues analysis to warn when a use of
12210b57cec5SDimitry Andric   // the zero-initialized definition will unexpectedly yield nil.
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // Locals are only zero-initialized when automated reference counting
12240b57cec5SDimitry Andric   // is turned on.
12250b57cec5SDimitry Andric   if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
12260b57cec5SDimitry Andric     return false;
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric   auto *DS = dyn_cast<DeclStmt>(S);
12290b57cec5SDimitry Andric   if (!DS || !DS->isSingleDecl())
12300b57cec5SDimitry Andric     return false;
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
12330b57cec5SDimitry Andric   if (!VD)
12340b57cec5SDimitry Andric     return false;
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric   // Sema only zero-initializes locals with ObjCLifetimes.
12370b57cec5SDimitry Andric   if(!VD->getType().getQualifiers().hasObjCLifetime())
12380b57cec5SDimitry Andric     return false;
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric   const Expr *Init = VD->getInit();
12410b57cec5SDimitry Andric   assert(Init && "ObjC local under ARC without initializer");
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   // Return false if the local is explicitly initialized (e.g., with '= nil').
12440b57cec5SDimitry Andric   if (!isa<ImplicitValueInitExpr>(Init))
12450b57cec5SDimitry Andric     return false;
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   return true;
12480b57cec5SDimitry Andric }
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric /// Propagate the nullability information through binds and warn when nullable
12510b57cec5SDimitry Andric /// pointer or null symbol is assigned to a pointer with a nonnull type.
12520b57cec5SDimitry Andric void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
12530b57cec5SDimitry Andric                                    CheckerContext &C) const {
12540b57cec5SDimitry Andric   const TypedValueRegion *TVR =
12550b57cec5SDimitry Andric       dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
12560b57cec5SDimitry Andric   if (!TVR)
12570b57cec5SDimitry Andric     return;
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric   QualType LocType = TVR->getValueType();
126006c3fb27SDimitry Andric   if (!isValidPointerType(LocType))
12610b57cec5SDimitry Andric     return;
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
12640b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
12650b57cec5SDimitry Andric     return;
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
12680b57cec5SDimitry Andric   if (!ValDefOrUnknown)
12690b57cec5SDimitry Andric     return;
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   Nullability ValNullability = Nullability::Unspecified;
12740b57cec5SDimitry Andric   if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
12750b57cec5SDimitry Andric     ValNullability = getNullabilityAnnotation(Sym->getType());
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric   Nullability LocNullability = getNullabilityAnnotation(LocType);
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric   // If the type of the RHS expression is nonnull, don't warn. This
12800b57cec5SDimitry Andric   // enables explicit suppression with a cast to nonnull.
12810b57cec5SDimitry Andric   Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
12820b57cec5SDimitry Andric   const Expr *ValueExpr = matchValueExprForBind(S);
12830b57cec5SDimitry Andric   if (ValueExpr) {
12840b57cec5SDimitry Andric     ValueExprTypeLevelNullability =
12850b57cec5SDimitry Andric       getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
12860b57cec5SDimitry Andric   }
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
12890b57cec5SDimitry Andric                                 RhsNullness == NullConstraint::IsNull);
12905ffd83dbSDimitry Andric   if (ChecksEnabled[CK_NullPassedToNonnull] && NullAssignedToNonNull &&
12910b57cec5SDimitry Andric       ValNullability != Nullability::Nonnull &&
12920b57cec5SDimitry Andric       ValueExprTypeLevelNullability != Nullability::Nonnull &&
12930b57cec5SDimitry Andric       !isARCNilInitializedLocal(C, S)) {
12940b57cec5SDimitry Andric     static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
12950b57cec5SDimitry Andric     ExplodedNode *N = C.generateErrorNode(State, &Tag);
12960b57cec5SDimitry Andric     if (!N)
12970b57cec5SDimitry Andric       return;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric     const Stmt *ValueStmt = S;
13010b57cec5SDimitry Andric     if (ValueExpr)
13020b57cec5SDimitry Andric       ValueStmt = ValueExpr;
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric     SmallString<256> SBuf;
13050b57cec5SDimitry Andric     llvm::raw_svector_ostream OS(SBuf);
13060b57cec5SDimitry Andric     OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
13070b57cec5SDimitry Andric     OS << " assigned to a pointer which is expected to have non-null value";
13085ffd83dbSDimitry Andric     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
13095ffd83dbSDimitry Andric                               CK_NullPassedToNonnull, N, nullptr, C, ValueStmt);
13100b57cec5SDimitry Andric     return;
13110b57cec5SDimitry Andric   }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   // If null was returned from a non-null function, mark the nullability
13140b57cec5SDimitry Andric   // invariant as violated even if the diagnostic was suppressed.
13150b57cec5SDimitry Andric   if (NullAssignedToNonNull) {
13160b57cec5SDimitry Andric     State = State->set<InvariantViolated>(true);
13170b57cec5SDimitry Andric     C.addTransition(State);
13180b57cec5SDimitry Andric     return;
13190b57cec5SDimitry Andric   }
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric   // Intentionally missing case: '0' is bound to a reference. It is handled by
13220b57cec5SDimitry Andric   // the DereferenceChecker.
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric   const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
13250b57cec5SDimitry Andric   if (!ValueRegion)
13260b57cec5SDimitry Andric     return;
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
13290b57cec5SDimitry Andric       State->get<NullabilityMap>(ValueRegion);
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   if (TrackedNullability) {
13320b57cec5SDimitry Andric     if (RhsNullness == NullConstraint::IsNotNull ||
13330b57cec5SDimitry Andric         TrackedNullability->getValue() != Nullability::Nullable)
13340b57cec5SDimitry Andric       return;
13355ffd83dbSDimitry Andric     if (ChecksEnabled[CK_NullablePassedToNonnull] &&
13360b57cec5SDimitry Andric         LocNullability == Nullability::Nonnull) {
13370b57cec5SDimitry Andric       static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
13380b57cec5SDimitry Andric       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
13390b57cec5SDimitry Andric       reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
13400b57cec5SDimitry Andric                                 "which is expected to have non-null value",
13415ffd83dbSDimitry Andric                                 ErrorKind::NullableAssignedToNonnull,
13425ffd83dbSDimitry Andric                                 CK_NullablePassedToNonnull, N, ValueRegion, C);
13430b57cec5SDimitry Andric     }
13440b57cec5SDimitry Andric     return;
13450b57cec5SDimitry Andric   }
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   const auto *BinOp = dyn_cast<BinaryOperator>(S);
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric   if (ValNullability == Nullability::Nullable) {
13500b57cec5SDimitry Andric     // Trust the static information of the value more than the static
13510b57cec5SDimitry Andric     // information on the location.
13520b57cec5SDimitry Andric     const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
13530b57cec5SDimitry Andric     State = State->set<NullabilityMap>(
13540b57cec5SDimitry Andric         ValueRegion, NullabilityState(ValNullability, NullabilitySource));
13550b57cec5SDimitry Andric     C.addTransition(State);
13560b57cec5SDimitry Andric     return;
13570b57cec5SDimitry Andric   }
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric   if (LocNullability == Nullability::Nullable) {
13600b57cec5SDimitry Andric     const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
13610b57cec5SDimitry Andric     State = State->set<NullabilityMap>(
13620b57cec5SDimitry Andric         ValueRegion, NullabilityState(LocNullability, NullabilitySource));
13630b57cec5SDimitry Andric     C.addTransition(State);
13640b57cec5SDimitry Andric   }
13650b57cec5SDimitry Andric }
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
13680b57cec5SDimitry Andric                                     const char *NL, const char *Sep) const {
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   NullabilityMapTy B = State->get<NullabilityMap>();
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
13730b57cec5SDimitry Andric     Out << Sep << NL
13740b57cec5SDimitry Andric         << "Nullability invariant was violated, warnings suppressed." << NL;
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric   if (B.isEmpty())
13770b57cec5SDimitry Andric     return;
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   if (!State->get<InvariantViolated>())
13800b57cec5SDimitry Andric     Out << Sep << NL;
13810b57cec5SDimitry Andric 
138206c3fb27SDimitry Andric   for (auto [Region, State] : B) {
138306c3fb27SDimitry Andric     Out << Region << " : ";
138406c3fb27SDimitry Andric     State.print(Out);
13850b57cec5SDimitry Andric     Out << NL;
13860b57cec5SDimitry Andric   }
13870b57cec5SDimitry Andric }
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric void ento::registerNullabilityBase(CheckerManager &mgr) {
13900b57cec5SDimitry Andric   mgr.registerChecker<NullabilityChecker>();
13910b57cec5SDimitry Andric }
13920b57cec5SDimitry Andric 
13935ffd83dbSDimitry Andric bool ento::shouldRegisterNullabilityBase(const CheckerManager &mgr) {
13940b57cec5SDimitry Andric   return true;
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric #define REGISTER_CHECKER(name, trackingRequired)                               \
13980b57cec5SDimitry Andric   void ento::register##name##Checker(CheckerManager &mgr) {                    \
13990b57cec5SDimitry Andric     NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>();        \
14005ffd83dbSDimitry Andric     checker->ChecksEnabled[NullabilityChecker::CK_##name] = true;              \
14015ffd83dbSDimitry Andric     checker->CheckNames[NullabilityChecker::CK_##name] =                       \
14025ffd83dbSDimitry Andric         mgr.getCurrentCheckerName();                                           \
14030b57cec5SDimitry Andric     checker->NeedTracking = checker->NeedTracking || trackingRequired;         \
14040b57cec5SDimitry Andric     checker->NoDiagnoseCallsToSystemHeaders =                                  \
14050b57cec5SDimitry Andric         checker->NoDiagnoseCallsToSystemHeaders ||                             \
14060b57cec5SDimitry Andric         mgr.getAnalyzerOptions().getCheckerBooleanOption(                      \
14070b57cec5SDimitry Andric             checker, "NoDiagnoseCallsToSystemHeaders", true);                  \
14080b57cec5SDimitry Andric   }                                                                            \
14090b57cec5SDimitry Andric                                                                                \
14105ffd83dbSDimitry Andric   bool ento::shouldRegister##name##Checker(const CheckerManager &mgr) {        \
14110b57cec5SDimitry Andric     return true;                                                               \
14120b57cec5SDimitry Andric   }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric // The checks are likely to be turned on by default and it is possible to do
14150b57cec5SDimitry Andric // them without tracking any nullability related information. As an optimization
14160b57cec5SDimitry Andric // no nullability information will be tracked when only these two checks are
14170b57cec5SDimitry Andric // enables.
14180b57cec5SDimitry Andric REGISTER_CHECKER(NullPassedToNonnull, false)
14190b57cec5SDimitry Andric REGISTER_CHECKER(NullReturnedFromNonnull, false)
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric REGISTER_CHECKER(NullableDereferenced, true)
14220b57cec5SDimitry Andric REGISTER_CHECKER(NullablePassedToNonnull, true)
14230b57cec5SDimitry Andric REGISTER_CHECKER(NullableReturnedFromNonnull, true)
1424