xref: /freebsd/contrib/llvm-project/clang/lib/Analysis/ThreadSafety.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===- ThreadSafety.cpp ---------------------------------------------------===//
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 // A intra-procedural analysis for thread safety (e.g. deadlocks and race
100b57cec5SDimitry Andric // conditions), based off of an annotation system.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
130b57cec5SDimitry Andric // for more information.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafety.h"
180b57cec5SDimitry Andric #include "clang/AST/Attr.h"
190b57cec5SDimitry Andric #include "clang/AST/Decl.h"
200b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
210b57cec5SDimitry Andric #include "clang/AST/DeclGroup.h"
220b57cec5SDimitry Andric #include "clang/AST/Expr.h"
230b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
240b57cec5SDimitry Andric #include "clang/AST/OperationKinds.h"
250b57cec5SDimitry Andric #include "clang/AST/Stmt.h"
260b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
270b57cec5SDimitry Andric #include "clang/AST/Type.h"
280b57cec5SDimitry Andric #include "clang/Analysis/Analyses/PostOrderCFGView.h"
290b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
300b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
310b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
320b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
330b57cec5SDimitry Andric #include "clang/Analysis/AnalysisDeclContext.h"
340b57cec5SDimitry Andric #include "clang/Analysis/CFG.h"
350b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
360b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
370b57cec5SDimitry Andric #include "clang/Basic/OperatorKinds.h"
380b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
390b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h"
400b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
410b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
420b57cec5SDimitry Andric #include "llvm/ADT/ImmutableMap.h"
430b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
440b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
450b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
460b57cec5SDimitry Andric #include "llvm/Support/Allocator.h"
470b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
480b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
490b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
500b57cec5SDimitry Andric #include <algorithm>
510b57cec5SDimitry Andric #include <cassert>
520b57cec5SDimitry Andric #include <functional>
530b57cec5SDimitry Andric #include <iterator>
540b57cec5SDimitry Andric #include <memory>
55*bdd1243dSDimitry Andric #include <optional>
560b57cec5SDimitry Andric #include <string>
570b57cec5SDimitry Andric #include <type_traits>
580b57cec5SDimitry Andric #include <utility>
590b57cec5SDimitry Andric #include <vector>
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric using namespace clang;
620b57cec5SDimitry Andric using namespace threadSafety;
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric // Key method definition
650b57cec5SDimitry Andric ThreadSafetyHandler::~ThreadSafetyHandler() = default;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric /// Issue a warning about an invalid lock expression
680b57cec5SDimitry Andric static void warnInvalidLock(ThreadSafetyHandler &Handler,
690b57cec5SDimitry Andric                             const Expr *MutexExp, const NamedDecl *D,
700b57cec5SDimitry Andric                             const Expr *DeclExp, StringRef Kind) {
710b57cec5SDimitry Andric   SourceLocation Loc;
720b57cec5SDimitry Andric   if (DeclExp)
730b57cec5SDimitry Andric     Loc = DeclExp->getExprLoc();
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric   // FIXME: add a note about the attribute location in MutexExp or D
760b57cec5SDimitry Andric   if (Loc.isValid())
7781ad6265SDimitry Andric     Handler.handleInvalidLockExp(Loc);
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric namespace {
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric /// A set of CapabilityExpr objects, which are compiled from thread safety
830b57cec5SDimitry Andric /// attributes on a function.
840b57cec5SDimitry Andric class CapExprSet : public SmallVector<CapabilityExpr, 4> {
850b57cec5SDimitry Andric public:
860b57cec5SDimitry Andric   /// Push M onto list, but discard duplicates.
870b57cec5SDimitry Andric   void push_back_nodup(const CapabilityExpr &CapE) {
88349cc55cSDimitry Andric     if (llvm::none_of(*this, [=](const CapabilityExpr &CapE2) {
890b57cec5SDimitry Andric           return CapE.equals(CapE2);
90349cc55cSDimitry Andric         }))
910b57cec5SDimitry Andric       push_back(CapE);
920b57cec5SDimitry Andric   }
930b57cec5SDimitry Andric };
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric class FactManager;
960b57cec5SDimitry Andric class FactSet;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric /// This is a helper class that stores a fact that is known at a
990b57cec5SDimitry Andric /// particular point in program execution.  Currently, a fact is a capability,
1000b57cec5SDimitry Andric /// along with additional information, such as where it was acquired, whether
1010b57cec5SDimitry Andric /// it is exclusive or shared, etc.
1020b57cec5SDimitry Andric ///
1030b57cec5SDimitry Andric /// FIXME: this analysis does not currently support re-entrant locking.
1040b57cec5SDimitry Andric class FactEntry : public CapabilityExpr {
105fe6060f1SDimitry Andric public:
106fe6060f1SDimitry Andric   /// Where a fact comes from.
107fe6060f1SDimitry Andric   enum SourceKind {
108fe6060f1SDimitry Andric     Acquired, ///< The fact has been directly acquired.
109fe6060f1SDimitry Andric     Asserted, ///< The fact has been asserted to be held.
110fe6060f1SDimitry Andric     Declared, ///< The fact is assumed to be held by callers.
111fe6060f1SDimitry Andric     Managed,  ///< The fact has been acquired through a scoped capability.
112fe6060f1SDimitry Andric   };
113fe6060f1SDimitry Andric 
1140b57cec5SDimitry Andric private:
1150b57cec5SDimitry Andric   /// Exclusive or shared.
116fe6060f1SDimitry Andric   LockKind LKind : 8;
117fe6060f1SDimitry Andric 
118fe6060f1SDimitry Andric   // How it was acquired.
119fe6060f1SDimitry Andric   SourceKind Source : 8;
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   /// Where it was acquired.
1220b57cec5SDimitry Andric   SourceLocation AcquireLoc;
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric public:
1250b57cec5SDimitry Andric   FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
126fe6060f1SDimitry Andric             SourceKind Src)
127fe6060f1SDimitry Andric       : CapabilityExpr(CE), LKind(LK), Source(Src), AcquireLoc(Loc) {}
1280b57cec5SDimitry Andric   virtual ~FactEntry() = default;
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric   LockKind kind() const { return LKind;      }
1310b57cec5SDimitry Andric   SourceLocation loc() const { return AcquireLoc; }
1320b57cec5SDimitry Andric 
133fe6060f1SDimitry Andric   bool asserted() const { return Source == Asserted; }
134fe6060f1SDimitry Andric   bool declared() const { return Source == Declared; }
135fe6060f1SDimitry Andric   bool managed() const { return Source == Managed; }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   virtual void
1380b57cec5SDimitry Andric   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
1390b57cec5SDimitry Andric                                 SourceLocation JoinLoc, LockErrorKind LEK,
1400b57cec5SDimitry Andric                                 ThreadSafetyHandler &Handler) const = 0;
1410b57cec5SDimitry Andric   virtual void handleLock(FactSet &FSet, FactManager &FactMan,
14281ad6265SDimitry Andric                           const FactEntry &entry,
14381ad6265SDimitry Andric                           ThreadSafetyHandler &Handler) const = 0;
1440b57cec5SDimitry Andric   virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
1450b57cec5SDimitry Andric                             const CapabilityExpr &Cp, SourceLocation UnlockLoc,
14681ad6265SDimitry Andric                             bool FullyRemove,
14781ad6265SDimitry Andric                             ThreadSafetyHandler &Handler) const = 0;
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   // Return true if LKind >= LK, where exclusive > shared
1500b57cec5SDimitry Andric   bool isAtLeast(LockKind LK) const {
1510b57cec5SDimitry Andric     return  (LKind == LK_Exclusive) || (LK == LK_Shared);
1520b57cec5SDimitry Andric   }
1530b57cec5SDimitry Andric };
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric using FactID = unsigned short;
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric /// FactManager manages the memory for all facts that are created during
1580b57cec5SDimitry Andric /// the analysis of a single routine.
1590b57cec5SDimitry Andric class FactManager {
1600b57cec5SDimitry Andric private:
1610b57cec5SDimitry Andric   std::vector<std::unique_ptr<const FactEntry>> Facts;
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric public:
1640b57cec5SDimitry Andric   FactID newFact(std::unique_ptr<FactEntry> Entry) {
1650b57cec5SDimitry Andric     Facts.push_back(std::move(Entry));
1660b57cec5SDimitry Andric     return static_cast<unsigned short>(Facts.size() - 1);
1670b57cec5SDimitry Andric   }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   const FactEntry &operator[](FactID F) const { return *Facts[F]; }
1700b57cec5SDimitry Andric };
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric /// A FactSet is the set of facts that are known to be true at a
1730b57cec5SDimitry Andric /// particular program point.  FactSets must be small, because they are
1740b57cec5SDimitry Andric /// frequently copied, and are thus implemented as a set of indices into a
1750b57cec5SDimitry Andric /// table maintained by a FactManager.  A typical FactSet only holds 1 or 2
1760b57cec5SDimitry Andric /// locks, so we can get away with doing a linear search for lookup.  Note
1770b57cec5SDimitry Andric /// that a hashtable or map is inappropriate in this case, because lookups
1780b57cec5SDimitry Andric /// may involve partial pattern matches, rather than exact matches.
1790b57cec5SDimitry Andric class FactSet {
1800b57cec5SDimitry Andric private:
1810b57cec5SDimitry Andric   using FactVec = SmallVector<FactID, 4>;
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   FactVec FactIDs;
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric public:
1860b57cec5SDimitry Andric   using iterator = FactVec::iterator;
1870b57cec5SDimitry Andric   using const_iterator = FactVec::const_iterator;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   iterator begin() { return FactIDs.begin(); }
1900b57cec5SDimitry Andric   const_iterator begin() const { return FactIDs.begin(); }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   iterator end() { return FactIDs.end(); }
1930b57cec5SDimitry Andric   const_iterator end() const { return FactIDs.end(); }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   bool isEmpty() const { return FactIDs.size() == 0; }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   // Return true if the set contains only negative facts
1980b57cec5SDimitry Andric   bool isEmpty(FactManager &FactMan) const {
1990b57cec5SDimitry Andric     for (const auto FID : *this) {
2000b57cec5SDimitry Andric       if (!FactMan[FID].negative())
2010b57cec5SDimitry Andric         return false;
2020b57cec5SDimitry Andric     }
2030b57cec5SDimitry Andric     return true;
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   void addLockByID(FactID ID) { FactIDs.push_back(ID); }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
2090b57cec5SDimitry Andric     FactID F = FM.newFact(std::move(Entry));
2100b57cec5SDimitry Andric     FactIDs.push_back(F);
2110b57cec5SDimitry Andric     return F;
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
2150b57cec5SDimitry Andric     unsigned n = FactIDs.size();
2160b57cec5SDimitry Andric     if (n == 0)
2170b57cec5SDimitry Andric       return false;
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric     for (unsigned i = 0; i < n-1; ++i) {
2200b57cec5SDimitry Andric       if (FM[FactIDs[i]].matches(CapE)) {
2210b57cec5SDimitry Andric         FactIDs[i] = FactIDs[n-1];
2220b57cec5SDimitry Andric         FactIDs.pop_back();
2230b57cec5SDimitry Andric         return true;
2240b57cec5SDimitry Andric       }
2250b57cec5SDimitry Andric     }
2260b57cec5SDimitry Andric     if (FM[FactIDs[n-1]].matches(CapE)) {
2270b57cec5SDimitry Andric       FactIDs.pop_back();
2280b57cec5SDimitry Andric       return true;
2290b57cec5SDimitry Andric     }
2300b57cec5SDimitry Andric     return false;
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
2340b57cec5SDimitry Andric     return std::find_if(begin(), end(), [&](FactID ID) {
2350b57cec5SDimitry Andric       return FM[ID].matches(CapE);
2360b57cec5SDimitry Andric     });
2370b57cec5SDimitry Andric   }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
2400b57cec5SDimitry Andric     auto I = std::find_if(begin(), end(), [&](FactID ID) {
2410b57cec5SDimitry Andric       return FM[ID].matches(CapE);
2420b57cec5SDimitry Andric     });
2430b57cec5SDimitry Andric     return I != end() ? &FM[*I] : nullptr;
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   const FactEntry *findLockUniv(FactManager &FM,
2470b57cec5SDimitry Andric                                 const CapabilityExpr &CapE) const {
2480b57cec5SDimitry Andric     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2490b57cec5SDimitry Andric       return FM[ID].matchesUniv(CapE);
2500b57cec5SDimitry Andric     });
2510b57cec5SDimitry Andric     return I != end() ? &FM[*I] : nullptr;
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   const FactEntry *findPartialMatch(FactManager &FM,
2550b57cec5SDimitry Andric                                     const CapabilityExpr &CapE) const {
2560b57cec5SDimitry Andric     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2570b57cec5SDimitry Andric       return FM[ID].partiallyMatches(CapE);
2580b57cec5SDimitry Andric     });
2590b57cec5SDimitry Andric     return I != end() ? &FM[*I] : nullptr;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
2630b57cec5SDimitry Andric     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2640b57cec5SDimitry Andric       return FM[ID].valueDecl() == Vd;
2650b57cec5SDimitry Andric     });
2660b57cec5SDimitry Andric     return I != end();
2670b57cec5SDimitry Andric   }
2680b57cec5SDimitry Andric };
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric class ThreadSafetyAnalyzer;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric } // namespace
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric namespace clang {
2750b57cec5SDimitry Andric namespace threadSafety {
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric class BeforeSet {
2780b57cec5SDimitry Andric private:
2790b57cec5SDimitry Andric   using BeforeVect = SmallVector<const ValueDecl *, 4>;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   struct BeforeInfo {
2820b57cec5SDimitry Andric     BeforeVect Vect;
2830b57cec5SDimitry Andric     int Visited = 0;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric     BeforeInfo() = default;
2860b57cec5SDimitry Andric     BeforeInfo(BeforeInfo &&) = default;
2870b57cec5SDimitry Andric   };
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   using BeforeMap =
2900b57cec5SDimitry Andric       llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
2910b57cec5SDimitry Andric   using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric public:
2940b57cec5SDimitry Andric   BeforeSet() = default;
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
2970b57cec5SDimitry Andric                               ThreadSafetyAnalyzer& Analyzer);
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
3000b57cec5SDimitry Andric                                    ThreadSafetyAnalyzer &Analyzer);
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   void checkBeforeAfter(const ValueDecl* Vd,
3030b57cec5SDimitry Andric                         const FactSet& FSet,
3040b57cec5SDimitry Andric                         ThreadSafetyAnalyzer& Analyzer,
3050b57cec5SDimitry Andric                         SourceLocation Loc, StringRef CapKind);
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric private:
3080b57cec5SDimitry Andric   BeforeMap BMap;
3090b57cec5SDimitry Andric   CycleMap CycMap;
3100b57cec5SDimitry Andric };
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric } // namespace threadSafety
3130b57cec5SDimitry Andric } // namespace clang
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric namespace {
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric class LocalVariableMap;
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric /// A side (entry or exit) of a CFG node.
3220b57cec5SDimitry Andric enum CFGBlockSide { CBS_Entry, CBS_Exit };
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric /// CFGBlockInfo is a struct which contains all the information that is
3250b57cec5SDimitry Andric /// maintained for each block in the CFG.  See LocalVariableMap for more
3260b57cec5SDimitry Andric /// information about the contexts.
3270b57cec5SDimitry Andric struct CFGBlockInfo {
3280b57cec5SDimitry Andric   // Lockset held at entry to block
3290b57cec5SDimitry Andric   FactSet EntrySet;
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   // Lockset held at exit from block
3320b57cec5SDimitry Andric   FactSet ExitSet;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   // Context held at entry to block
3350b57cec5SDimitry Andric   LocalVarContext EntryContext;
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   // Context held at exit from block
3380b57cec5SDimitry Andric   LocalVarContext ExitContext;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // Location of first statement in block
3410b57cec5SDimitry Andric   SourceLocation EntryLoc;
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   // Location of last statement in block.
3440b57cec5SDimitry Andric   SourceLocation ExitLoc;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // Used to replay contexts later
3470b57cec5SDimitry Andric   unsigned EntryIndex;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // Is this block reachable?
3500b57cec5SDimitry Andric   bool Reachable = false;
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   const FactSet &getSet(CFGBlockSide Side) const {
3530b57cec5SDimitry Andric     return Side == CBS_Entry ? EntrySet : ExitSet;
3540b57cec5SDimitry Andric   }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   SourceLocation getLocation(CFGBlockSide Side) const {
3570b57cec5SDimitry Andric     return Side == CBS_Entry ? EntryLoc : ExitLoc;
3580b57cec5SDimitry Andric   }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric private:
3610b57cec5SDimitry Andric   CFGBlockInfo(LocalVarContext EmptyCtx)
3620b57cec5SDimitry Andric       : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric public:
3650b57cec5SDimitry Andric   static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
3660b57cec5SDimitry Andric };
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric // A LocalVariableMap maintains a map from local variables to their currently
3690b57cec5SDimitry Andric // valid definitions.  It provides SSA-like functionality when traversing the
3700b57cec5SDimitry Andric // CFG.  Like SSA, each definition or assignment to a variable is assigned a
3710b57cec5SDimitry Andric // unique name (an integer), which acts as the SSA name for that definition.
3720b57cec5SDimitry Andric // The total set of names is shared among all CFG basic blocks.
3730b57cec5SDimitry Andric // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
3740b57cec5SDimitry Andric // with their SSA-names.  Instead, we compute a Context for each point in the
3750b57cec5SDimitry Andric // code, which maps local variables to the appropriate SSA-name.  This map
3760b57cec5SDimitry Andric // changes with each assignment.
3770b57cec5SDimitry Andric //
3780b57cec5SDimitry Andric // The map is computed in a single pass over the CFG.  Subsequent analyses can
3790b57cec5SDimitry Andric // then query the map to find the appropriate Context for a statement, and use
3800b57cec5SDimitry Andric // that Context to look up the definitions of variables.
3810b57cec5SDimitry Andric class LocalVariableMap {
3820b57cec5SDimitry Andric public:
3830b57cec5SDimitry Andric   using Context = LocalVarContext;
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   /// A VarDefinition consists of an expression, representing the value of the
3860b57cec5SDimitry Andric   /// variable, along with the context in which that expression should be
3870b57cec5SDimitry Andric   /// interpreted.  A reference VarDefinition does not itself contain this
3880b57cec5SDimitry Andric   /// information, but instead contains a pointer to a previous VarDefinition.
3890b57cec5SDimitry Andric   struct VarDefinition {
3900b57cec5SDimitry Andric   public:
3910b57cec5SDimitry Andric     friend class LocalVariableMap;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric     // The original declaration for this variable.
3940b57cec5SDimitry Andric     const NamedDecl *Dec;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric     // The expression for this variable, OR
3970b57cec5SDimitry Andric     const Expr *Exp = nullptr;
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric     // Reference to another VarDefinition
4000b57cec5SDimitry Andric     unsigned Ref = 0;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     // The map with which Exp should be interpreted.
4030b57cec5SDimitry Andric     Context Ctx;
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric     bool isReference() { return !Exp; }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   private:
4080b57cec5SDimitry Andric     // Create ordinary variable definition
4090b57cec5SDimitry Andric     VarDefinition(const NamedDecl *D, const Expr *E, Context C)
4100b57cec5SDimitry Andric         : Dec(D), Exp(E), Ctx(C) {}
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric     // Create reference to previous definition
4130b57cec5SDimitry Andric     VarDefinition(const NamedDecl *D, unsigned R, Context C)
4140b57cec5SDimitry Andric         : Dec(D), Ref(R), Ctx(C) {}
4150b57cec5SDimitry Andric   };
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric private:
4180b57cec5SDimitry Andric   Context::Factory ContextFactory;
4190b57cec5SDimitry Andric   std::vector<VarDefinition> VarDefinitions;
4200b57cec5SDimitry Andric   std::vector<std::pair<const Stmt *, Context>> SavedContexts;
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric public:
4230b57cec5SDimitry Andric   LocalVariableMap() {
4240b57cec5SDimitry Andric     // index 0 is a placeholder for undefined variables (aka phi-nodes).
4250b57cec5SDimitry Andric     VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
4260b57cec5SDimitry Andric   }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   /// Look up a definition, within the given context.
4290b57cec5SDimitry Andric   const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
4300b57cec5SDimitry Andric     const unsigned *i = Ctx.lookup(D);
4310b57cec5SDimitry Andric     if (!i)
4320b57cec5SDimitry Andric       return nullptr;
4330b57cec5SDimitry Andric     assert(*i < VarDefinitions.size());
4340b57cec5SDimitry Andric     return &VarDefinitions[*i];
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   /// Look up the definition for D within the given context.  Returns
4380b57cec5SDimitry Andric   /// NULL if the expression is not statically known.  If successful, also
4390b57cec5SDimitry Andric   /// modifies Ctx to hold the context of the return Expr.
4400b57cec5SDimitry Andric   const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
4410b57cec5SDimitry Andric     const unsigned *P = Ctx.lookup(D);
4420b57cec5SDimitry Andric     if (!P)
4430b57cec5SDimitry Andric       return nullptr;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric     unsigned i = *P;
4460b57cec5SDimitry Andric     while (i > 0) {
4470b57cec5SDimitry Andric       if (VarDefinitions[i].Exp) {
4480b57cec5SDimitry Andric         Ctx = VarDefinitions[i].Ctx;
4490b57cec5SDimitry Andric         return VarDefinitions[i].Exp;
4500b57cec5SDimitry Andric       }
4510b57cec5SDimitry Andric       i = VarDefinitions[i].Ref;
4520b57cec5SDimitry Andric     }
4530b57cec5SDimitry Andric     return nullptr;
4540b57cec5SDimitry Andric   }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   /// Return the next context after processing S.  This function is used by
4590b57cec5SDimitry Andric   /// clients of the class to get the appropriate context when traversing the
4600b57cec5SDimitry Andric   /// CFG.  It must be called for every assignment or DeclStmt.
4610b57cec5SDimitry Andric   Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
4620b57cec5SDimitry Andric     if (SavedContexts[CtxIndex+1].first == S) {
4630b57cec5SDimitry Andric       CtxIndex++;
4640b57cec5SDimitry Andric       Context Result = SavedContexts[CtxIndex].second;
4650b57cec5SDimitry Andric       return Result;
4660b57cec5SDimitry Andric     }
4670b57cec5SDimitry Andric     return C;
4680b57cec5SDimitry Andric   }
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   void dumpVarDefinitionName(unsigned i) {
4710b57cec5SDimitry Andric     if (i == 0) {
4720b57cec5SDimitry Andric       llvm::errs() << "Undefined";
4730b57cec5SDimitry Andric       return;
4740b57cec5SDimitry Andric     }
4750b57cec5SDimitry Andric     const NamedDecl *Dec = VarDefinitions[i].Dec;
4760b57cec5SDimitry Andric     if (!Dec) {
4770b57cec5SDimitry Andric       llvm::errs() << "<<NULL>>";
4780b57cec5SDimitry Andric       return;
4790b57cec5SDimitry Andric     }
4800b57cec5SDimitry Andric     Dec->printName(llvm::errs());
4810b57cec5SDimitry Andric     llvm::errs() << "." << i << " " << ((const void*) Dec);
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   /// Dumps an ASCII representation of the variable map to llvm::errs()
4850b57cec5SDimitry Andric   void dump() {
4860b57cec5SDimitry Andric     for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
4870b57cec5SDimitry Andric       const Expr *Exp = VarDefinitions[i].Exp;
4880b57cec5SDimitry Andric       unsigned Ref = VarDefinitions[i].Ref;
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric       dumpVarDefinitionName(i);
4910b57cec5SDimitry Andric       llvm::errs() << " = ";
4920b57cec5SDimitry Andric       if (Exp) Exp->dump();
4930b57cec5SDimitry Andric       else {
4940b57cec5SDimitry Andric         dumpVarDefinitionName(Ref);
4950b57cec5SDimitry Andric         llvm::errs() << "\n";
4960b57cec5SDimitry Andric       }
4970b57cec5SDimitry Andric     }
4980b57cec5SDimitry Andric   }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   /// Dumps an ASCII representation of a Context to llvm::errs()
5010b57cec5SDimitry Andric   void dumpContext(Context C) {
5020b57cec5SDimitry Andric     for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
5030b57cec5SDimitry Andric       const NamedDecl *D = I.getKey();
5040b57cec5SDimitry Andric       D->printName(llvm::errs());
5050b57cec5SDimitry Andric       const unsigned *i = C.lookup(D);
5060b57cec5SDimitry Andric       llvm::errs() << " -> ";
5070b57cec5SDimitry Andric       dumpVarDefinitionName(*i);
5080b57cec5SDimitry Andric       llvm::errs() << "\n";
5090b57cec5SDimitry Andric     }
5100b57cec5SDimitry Andric   }
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   /// Builds the variable map.
5130b57cec5SDimitry Andric   void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
5140b57cec5SDimitry Andric                    std::vector<CFGBlockInfo> &BlockInfo);
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric protected:
5170b57cec5SDimitry Andric   friend class VarMapBuilder;
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // Get the current context index
5200b57cec5SDimitry Andric   unsigned getContextIndex() { return SavedContexts.size()-1; }
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   // Save the current context for later replay
5230b57cec5SDimitry Andric   void saveContext(const Stmt *S, Context C) {
5240b57cec5SDimitry Andric     SavedContexts.push_back(std::make_pair(S, C));
5250b57cec5SDimitry Andric   }
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   // Adds a new definition to the given context, and returns a new context.
5280b57cec5SDimitry Andric   // This method should be called when declaring a new variable.
5290b57cec5SDimitry Andric   Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
5300b57cec5SDimitry Andric     assert(!Ctx.contains(D));
5310b57cec5SDimitry Andric     unsigned newID = VarDefinitions.size();
5320b57cec5SDimitry Andric     Context NewCtx = ContextFactory.add(Ctx, D, newID);
5330b57cec5SDimitry Andric     VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
5340b57cec5SDimitry Andric     return NewCtx;
5350b57cec5SDimitry Andric   }
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   // Add a new reference to an existing definition.
5380b57cec5SDimitry Andric   Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
5390b57cec5SDimitry Andric     unsigned newID = VarDefinitions.size();
5400b57cec5SDimitry Andric     Context NewCtx = ContextFactory.add(Ctx, D, newID);
5410b57cec5SDimitry Andric     VarDefinitions.push_back(VarDefinition(D, i, Ctx));
5420b57cec5SDimitry Andric     return NewCtx;
5430b57cec5SDimitry Andric   }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   // Updates a definition only if that definition is already in the map.
5460b57cec5SDimitry Andric   // This method should be called when assigning to an existing variable.
5470b57cec5SDimitry Andric   Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
5480b57cec5SDimitry Andric     if (Ctx.contains(D)) {
5490b57cec5SDimitry Andric       unsigned newID = VarDefinitions.size();
5500b57cec5SDimitry Andric       Context NewCtx = ContextFactory.remove(Ctx, D);
5510b57cec5SDimitry Andric       NewCtx = ContextFactory.add(NewCtx, D, newID);
5520b57cec5SDimitry Andric       VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
5530b57cec5SDimitry Andric       return NewCtx;
5540b57cec5SDimitry Andric     }
5550b57cec5SDimitry Andric     return Ctx;
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   // Removes a definition from the context, but keeps the variable name
5590b57cec5SDimitry Andric   // as a valid variable.  The index 0 is a placeholder for cleared definitions.
5600b57cec5SDimitry Andric   Context clearDefinition(const NamedDecl *D, Context Ctx) {
5610b57cec5SDimitry Andric     Context NewCtx = Ctx;
5620b57cec5SDimitry Andric     if (NewCtx.contains(D)) {
5630b57cec5SDimitry Andric       NewCtx = ContextFactory.remove(NewCtx, D);
5640b57cec5SDimitry Andric       NewCtx = ContextFactory.add(NewCtx, D, 0);
5650b57cec5SDimitry Andric     }
5660b57cec5SDimitry Andric     return NewCtx;
5670b57cec5SDimitry Andric   }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   // Remove a definition entirely frmo the context.
5700b57cec5SDimitry Andric   Context removeDefinition(const NamedDecl *D, Context Ctx) {
5710b57cec5SDimitry Andric     Context NewCtx = Ctx;
5720b57cec5SDimitry Andric     if (NewCtx.contains(D)) {
5730b57cec5SDimitry Andric       NewCtx = ContextFactory.remove(NewCtx, D);
5740b57cec5SDimitry Andric     }
5750b57cec5SDimitry Andric     return NewCtx;
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   Context intersectContexts(Context C1, Context C2);
5790b57cec5SDimitry Andric   Context createReferenceContext(Context C);
5800b57cec5SDimitry Andric   void intersectBackEdge(Context C1, Context C2);
5810b57cec5SDimitry Andric };
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric } // namespace
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric // This has to be defined after LocalVariableMap.
5860b57cec5SDimitry Andric CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
5870b57cec5SDimitry Andric   return CFGBlockInfo(M.getEmptyContext());
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric namespace {
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric /// Visitor which builds a LocalVariableMap
5930b57cec5SDimitry Andric class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
5940b57cec5SDimitry Andric public:
5950b57cec5SDimitry Andric   LocalVariableMap* VMap;
5960b57cec5SDimitry Andric   LocalVariableMap::Context Ctx;
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric   VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
5990b57cec5SDimitry Andric       : VMap(VM), Ctx(C) {}
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   void VisitDeclStmt(const DeclStmt *S);
6020b57cec5SDimitry Andric   void VisitBinaryOperator(const BinaryOperator *BO);
6030b57cec5SDimitry Andric };
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric } // namespace
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric // Add new local variables to the variable map
6080b57cec5SDimitry Andric void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
6090b57cec5SDimitry Andric   bool modifiedCtx = false;
6100b57cec5SDimitry Andric   const DeclGroupRef DGrp = S->getDeclGroup();
6110b57cec5SDimitry Andric   for (const auto *D : DGrp) {
6120b57cec5SDimitry Andric     if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
6130b57cec5SDimitry Andric       const Expr *E = VD->getInit();
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric       // Add local variables with trivial type to the variable map
6160b57cec5SDimitry Andric       QualType T = VD->getType();
6170b57cec5SDimitry Andric       if (T.isTrivialType(VD->getASTContext())) {
6180b57cec5SDimitry Andric         Ctx = VMap->addDefinition(VD, E, Ctx);
6190b57cec5SDimitry Andric         modifiedCtx = true;
6200b57cec5SDimitry Andric       }
6210b57cec5SDimitry Andric     }
6220b57cec5SDimitry Andric   }
6230b57cec5SDimitry Andric   if (modifiedCtx)
6240b57cec5SDimitry Andric     VMap->saveContext(S, Ctx);
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric // Update local variable definitions in variable map
6280b57cec5SDimitry Andric void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
6290b57cec5SDimitry Andric   if (!BO->isAssignmentOp())
6300b57cec5SDimitry Andric     return;
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   // Update the variable map and current context.
6350b57cec5SDimitry Andric   if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
6360b57cec5SDimitry Andric     const ValueDecl *VDec = DRE->getDecl();
6370b57cec5SDimitry Andric     if (Ctx.lookup(VDec)) {
6380b57cec5SDimitry Andric       if (BO->getOpcode() == BO_Assign)
6390b57cec5SDimitry Andric         Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
6400b57cec5SDimitry Andric       else
6410b57cec5SDimitry Andric         // FIXME -- handle compound assignment operators
6420b57cec5SDimitry Andric         Ctx = VMap->clearDefinition(VDec, Ctx);
6430b57cec5SDimitry Andric       VMap->saveContext(BO, Ctx);
6440b57cec5SDimitry Andric     }
6450b57cec5SDimitry Andric   }
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric // Computes the intersection of two contexts.  The intersection is the
6490b57cec5SDimitry Andric // set of variables which have the same definition in both contexts;
6500b57cec5SDimitry Andric // variables with different definitions are discarded.
6510b57cec5SDimitry Andric LocalVariableMap::Context
6520b57cec5SDimitry Andric LocalVariableMap::intersectContexts(Context C1, Context C2) {
6530b57cec5SDimitry Andric   Context Result = C1;
6540b57cec5SDimitry Andric   for (const auto &P : C1) {
6550b57cec5SDimitry Andric     const NamedDecl *Dec = P.first;
6560b57cec5SDimitry Andric     const unsigned *i2 = C2.lookup(Dec);
6570b57cec5SDimitry Andric     if (!i2)             // variable doesn't exist on second path
6580b57cec5SDimitry Andric       Result = removeDefinition(Dec, Result);
6590b57cec5SDimitry Andric     else if (*i2 != P.second)  // variable exists, but has different definition
6600b57cec5SDimitry Andric       Result = clearDefinition(Dec, Result);
6610b57cec5SDimitry Andric   }
6620b57cec5SDimitry Andric   return Result;
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric // For every variable in C, create a new variable that refers to the
6660b57cec5SDimitry Andric // definition in C.  Return a new context that contains these new variables.
6670b57cec5SDimitry Andric // (We use this for a naive implementation of SSA on loop back-edges.)
6680b57cec5SDimitry Andric LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
6690b57cec5SDimitry Andric   Context Result = getEmptyContext();
6700b57cec5SDimitry Andric   for (const auto &P : C)
6710b57cec5SDimitry Andric     Result = addReference(P.first, P.second, Result);
6720b57cec5SDimitry Andric   return Result;
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric // This routine also takes the intersection of C1 and C2, but it does so by
6760b57cec5SDimitry Andric // altering the VarDefinitions.  C1 must be the result of an earlier call to
6770b57cec5SDimitry Andric // createReferenceContext.
6780b57cec5SDimitry Andric void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
6790b57cec5SDimitry Andric   for (const auto &P : C1) {
6800b57cec5SDimitry Andric     unsigned i1 = P.second;
6810b57cec5SDimitry Andric     VarDefinition *VDef = &VarDefinitions[i1];
6820b57cec5SDimitry Andric     assert(VDef->isReference());
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric     const unsigned *i2 = C2.lookup(P.first);
6850b57cec5SDimitry Andric     if (!i2 || (*i2 != i1))
6860b57cec5SDimitry Andric       VDef->Ref = 0;    // Mark this variable as undefined
6870b57cec5SDimitry Andric   }
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric // Traverse the CFG in topological order, so all predecessors of a block
6910b57cec5SDimitry Andric // (excluding back-edges) are visited before the block itself.  At
6920b57cec5SDimitry Andric // each point in the code, we calculate a Context, which holds the set of
6930b57cec5SDimitry Andric // variable definitions which are visible at that point in execution.
6940b57cec5SDimitry Andric // Visible variables are mapped to their definitions using an array that
6950b57cec5SDimitry Andric // contains all definitions.
6960b57cec5SDimitry Andric //
6970b57cec5SDimitry Andric // At join points in the CFG, the set is computed as the intersection of
6980b57cec5SDimitry Andric // the incoming sets along each edge, E.g.
6990b57cec5SDimitry Andric //
7000b57cec5SDimitry Andric //                       { Context                 | VarDefinitions }
7010b57cec5SDimitry Andric //   int x = 0;          { x -> x1                 | x1 = 0 }
7020b57cec5SDimitry Andric //   int y = 0;          { x -> x1, y -> y1        | y1 = 0, x1 = 0 }
7030b57cec5SDimitry Andric //   if (b) x = 1;       { x -> x2, y -> y1        | x2 = 1, y1 = 0, ... }
7040b57cec5SDimitry Andric //   else   x = 2;       { x -> x3, y -> y1        | x3 = 2, x2 = 1, ... }
7050b57cec5SDimitry Andric //   ...                 { y -> y1  (x is unknown) | x3 = 2, x2 = 1, ... }
7060b57cec5SDimitry Andric //
7070b57cec5SDimitry Andric // This is essentially a simpler and more naive version of the standard SSA
7080b57cec5SDimitry Andric // algorithm.  Those definitions that remain in the intersection are from blocks
7090b57cec5SDimitry Andric // that strictly dominate the current block.  We do not bother to insert proper
7100b57cec5SDimitry Andric // phi nodes, because they are not used in our analysis; instead, wherever
7110b57cec5SDimitry Andric // a phi node would be required, we simply remove that definition from the
7120b57cec5SDimitry Andric // context (E.g. x above).
7130b57cec5SDimitry Andric //
7140b57cec5SDimitry Andric // The initial traversal does not capture back-edges, so those need to be
7150b57cec5SDimitry Andric // handled on a separate pass.  Whenever the first pass encounters an
7160b57cec5SDimitry Andric // incoming back edge, it duplicates the context, creating new definitions
7170b57cec5SDimitry Andric // that refer back to the originals.  (These correspond to places where SSA
7180b57cec5SDimitry Andric // might have to insert a phi node.)  On the second pass, these definitions are
7190b57cec5SDimitry Andric // set to NULL if the variable has changed on the back-edge (i.e. a phi
7200b57cec5SDimitry Andric // node was actually required.)  E.g.
7210b57cec5SDimitry Andric //
7220b57cec5SDimitry Andric //                       { Context           | VarDefinitions }
7230b57cec5SDimitry Andric //   int x = 0, y = 0;   { x -> x1, y -> y1  | y1 = 0, x1 = 0 }
7240b57cec5SDimitry Andric //   while (b)           { x -> x2, y -> y1  | [1st:] x2=x1; [2nd:] x2=NULL; }
7250b57cec5SDimitry Andric //     x = x+1;          { x -> x3, y -> y1  | x3 = x2 + 1, ... }
7260b57cec5SDimitry Andric //   ...                 { y -> y1           | x3 = 2, x2 = 1, ... }
7270b57cec5SDimitry Andric void LocalVariableMap::traverseCFG(CFG *CFGraph,
7280b57cec5SDimitry Andric                                    const PostOrderCFGView *SortedGraph,
7290b57cec5SDimitry Andric                                    std::vector<CFGBlockInfo> &BlockInfo) {
7300b57cec5SDimitry Andric   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   for (const auto *CurrBlock : *SortedGraph) {
7330b57cec5SDimitry Andric     unsigned CurrBlockID = CurrBlock->getBlockID();
7340b57cec5SDimitry Andric     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric     VisitedBlocks.insert(CurrBlock);
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric     // Calculate the entry context for the current block
7390b57cec5SDimitry Andric     bool HasBackEdges = false;
7400b57cec5SDimitry Andric     bool CtxInit = true;
7410b57cec5SDimitry Andric     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
7420b57cec5SDimitry Andric          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
7430b57cec5SDimitry Andric       // if *PI -> CurrBlock is a back edge, so skip it
7440b57cec5SDimitry Andric       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
7450b57cec5SDimitry Andric         HasBackEdges = true;
7460b57cec5SDimitry Andric         continue;
7470b57cec5SDimitry Andric       }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric       unsigned PrevBlockID = (*PI)->getBlockID();
7500b57cec5SDimitry Andric       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric       if (CtxInit) {
7530b57cec5SDimitry Andric         CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
7540b57cec5SDimitry Andric         CtxInit = false;
7550b57cec5SDimitry Andric       }
7560b57cec5SDimitry Andric       else {
7570b57cec5SDimitry Andric         CurrBlockInfo->EntryContext =
7580b57cec5SDimitry Andric           intersectContexts(CurrBlockInfo->EntryContext,
7590b57cec5SDimitry Andric                             PrevBlockInfo->ExitContext);
7600b57cec5SDimitry Andric       }
7610b57cec5SDimitry Andric     }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric     // Duplicate the context if we have back-edges, so we can call
7640b57cec5SDimitry Andric     // intersectBackEdges later.
7650b57cec5SDimitry Andric     if (HasBackEdges)
7660b57cec5SDimitry Andric       CurrBlockInfo->EntryContext =
7670b57cec5SDimitry Andric         createReferenceContext(CurrBlockInfo->EntryContext);
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric     // Create a starting context index for the current block
7700b57cec5SDimitry Andric     saveContext(nullptr, CurrBlockInfo->EntryContext);
7710b57cec5SDimitry Andric     CurrBlockInfo->EntryIndex = getContextIndex();
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric     // Visit all the statements in the basic block.
7740b57cec5SDimitry Andric     VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
7750b57cec5SDimitry Andric     for (const auto &BI : *CurrBlock) {
7760b57cec5SDimitry Andric       switch (BI.getKind()) {
7770b57cec5SDimitry Andric         case CFGElement::Statement: {
7780b57cec5SDimitry Andric           CFGStmt CS = BI.castAs<CFGStmt>();
7790b57cec5SDimitry Andric           VMapBuilder.Visit(CS.getStmt());
7800b57cec5SDimitry Andric           break;
7810b57cec5SDimitry Andric         }
7820b57cec5SDimitry Andric         default:
7830b57cec5SDimitry Andric           break;
7840b57cec5SDimitry Andric       }
7850b57cec5SDimitry Andric     }
7860b57cec5SDimitry Andric     CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric     // Mark variables on back edges as "unknown" if they've been changed.
7890b57cec5SDimitry Andric     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
7900b57cec5SDimitry Andric          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
7910b57cec5SDimitry Andric       // if CurrBlock -> *SI is *not* a back edge
7920b57cec5SDimitry Andric       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
7930b57cec5SDimitry Andric         continue;
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric       CFGBlock *FirstLoopBlock = *SI;
7960b57cec5SDimitry Andric       Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
7970b57cec5SDimitry Andric       Context LoopEnd   = CurrBlockInfo->ExitContext;
7980b57cec5SDimitry Andric       intersectBackEdge(LoopBegin, LoopEnd);
7990b57cec5SDimitry Andric     }
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   // Put an extra entry at the end of the indexed context array
8030b57cec5SDimitry Andric   unsigned exitID = CFGraph->getExit().getBlockID();
8040b57cec5SDimitry Andric   saveContext(nullptr, BlockInfo[exitID].ExitContext);
8050b57cec5SDimitry Andric }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric /// Find the appropriate source locations to use when producing diagnostics for
8080b57cec5SDimitry Andric /// each block in the CFG.
8090b57cec5SDimitry Andric static void findBlockLocations(CFG *CFGraph,
8100b57cec5SDimitry Andric                                const PostOrderCFGView *SortedGraph,
8110b57cec5SDimitry Andric                                std::vector<CFGBlockInfo> &BlockInfo) {
8120b57cec5SDimitry Andric   for (const auto *CurrBlock : *SortedGraph) {
8130b57cec5SDimitry Andric     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric     // Find the source location of the last statement in the block, if the
8160b57cec5SDimitry Andric     // block is not empty.
8170b57cec5SDimitry Andric     if (const Stmt *S = CurrBlock->getTerminatorStmt()) {
8180b57cec5SDimitry Andric       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
8190b57cec5SDimitry Andric     } else {
8200b57cec5SDimitry Andric       for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
8210b57cec5SDimitry Andric            BE = CurrBlock->rend(); BI != BE; ++BI) {
8220b57cec5SDimitry Andric         // FIXME: Handle other CFGElement kinds.
823*bdd1243dSDimitry Andric         if (std::optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
8240b57cec5SDimitry Andric           CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
8250b57cec5SDimitry Andric           break;
8260b57cec5SDimitry Andric         }
8270b57cec5SDimitry Andric       }
8280b57cec5SDimitry Andric     }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric     if (CurrBlockInfo->ExitLoc.isValid()) {
8310b57cec5SDimitry Andric       // This block contains at least one statement. Find the source location
8320b57cec5SDimitry Andric       // of the first statement in the block.
8330b57cec5SDimitry Andric       for (const auto &BI : *CurrBlock) {
8340b57cec5SDimitry Andric         // FIXME: Handle other CFGElement kinds.
835*bdd1243dSDimitry Andric         if (std::optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
8360b57cec5SDimitry Andric           CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
8370b57cec5SDimitry Andric           break;
8380b57cec5SDimitry Andric         }
8390b57cec5SDimitry Andric       }
8400b57cec5SDimitry Andric     } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
8410b57cec5SDimitry Andric                CurrBlock != &CFGraph->getExit()) {
8420b57cec5SDimitry Andric       // The block is empty, and has a single predecessor. Use its exit
8430b57cec5SDimitry Andric       // location.
8440b57cec5SDimitry Andric       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
8450b57cec5SDimitry Andric           BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
846349cc55cSDimitry Andric     } else if (CurrBlock->succ_size() == 1 && *CurrBlock->succ_begin()) {
847349cc55cSDimitry Andric       // The block is empty, and has a single successor. Use its entry
848349cc55cSDimitry Andric       // location.
849349cc55cSDimitry Andric       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
850349cc55cSDimitry Andric           BlockInfo[(*CurrBlock->succ_begin())->getBlockID()].EntryLoc;
8510b57cec5SDimitry Andric     }
8520b57cec5SDimitry Andric   }
8530b57cec5SDimitry Andric }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric namespace {
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric class LockableFactEntry : public FactEntry {
8580b57cec5SDimitry Andric public:
8590b57cec5SDimitry Andric   LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
860fe6060f1SDimitry Andric                     SourceKind Src = Acquired)
861fe6060f1SDimitry Andric       : FactEntry(CE, LK, Loc, Src) {}
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric   void
8640b57cec5SDimitry Andric   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
8650b57cec5SDimitry Andric                                 SourceLocation JoinLoc, LockErrorKind LEK,
8660b57cec5SDimitry Andric                                 ThreadSafetyHandler &Handler) const override {
867fe6060f1SDimitry Andric     if (!asserted() && !negative() && !isUniversal()) {
86881ad6265SDimitry Andric       Handler.handleMutexHeldEndOfScope(getKind(), toString(), loc(), JoinLoc,
8690b57cec5SDimitry Andric                                         LEK);
8700b57cec5SDimitry Andric     }
8710b57cec5SDimitry Andric   }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
87481ad6265SDimitry Andric                   ThreadSafetyHandler &Handler) const override {
87581ad6265SDimitry Andric     Handler.handleDoubleLock(entry.getKind(), entry.toString(), loc(),
87681ad6265SDimitry Andric                              entry.loc());
8770b57cec5SDimitry Andric   }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   void handleUnlock(FactSet &FSet, FactManager &FactMan,
8800b57cec5SDimitry Andric                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
88181ad6265SDimitry Andric                     bool FullyRemove,
88281ad6265SDimitry Andric                     ThreadSafetyHandler &Handler) const override {
8830b57cec5SDimitry Andric     FSet.removeLock(FactMan, Cp);
8840b57cec5SDimitry Andric     if (!Cp.negative()) {
885a7dea167SDimitry Andric       FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
8860b57cec5SDimitry Andric                                 !Cp, LK_Exclusive, UnlockLoc));
8870b57cec5SDimitry Andric     }
8880b57cec5SDimitry Andric   }
8890b57cec5SDimitry Andric };
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric class ScopedLockableFactEntry : public FactEntry {
8920b57cec5SDimitry Andric private:
8930b57cec5SDimitry Andric   enum UnderlyingCapabilityKind {
8940b57cec5SDimitry Andric     UCK_Acquired,          ///< Any kind of acquired capability.
8950b57cec5SDimitry Andric     UCK_ReleasedShared,    ///< Shared capability that was released.
8960b57cec5SDimitry Andric     UCK_ReleasedExclusive, ///< Exclusive capability that was released.
8970b57cec5SDimitry Andric   };
8980b57cec5SDimitry Andric 
89981ad6265SDimitry Andric   struct UnderlyingCapability {
90081ad6265SDimitry Andric     CapabilityExpr Cap;
90181ad6265SDimitry Andric     UnderlyingCapabilityKind Kind;
90281ad6265SDimitry Andric   };
9030b57cec5SDimitry Andric 
90481ad6265SDimitry Andric   SmallVector<UnderlyingCapability, 2> UnderlyingMutexes;
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric public:
9070b57cec5SDimitry Andric   ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc)
908fe6060f1SDimitry Andric       : FactEntry(CE, LK_Exclusive, Loc, Acquired) {}
9090b57cec5SDimitry Andric 
9105ffd83dbSDimitry Andric   void addLock(const CapabilityExpr &M) {
91181ad6265SDimitry Andric     UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_Acquired});
9120b57cec5SDimitry Andric   }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   void addExclusiveUnlock(const CapabilityExpr &M) {
91581ad6265SDimitry Andric     UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedExclusive});
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   void addSharedUnlock(const CapabilityExpr &M) {
91981ad6265SDimitry Andric     UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedShared});
9200b57cec5SDimitry Andric   }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   void
9230b57cec5SDimitry Andric   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
9240b57cec5SDimitry Andric                                 SourceLocation JoinLoc, LockErrorKind LEK,
9250b57cec5SDimitry Andric                                 ThreadSafetyHandler &Handler) const override {
9260b57cec5SDimitry Andric     for (const auto &UnderlyingMutex : UnderlyingMutexes) {
92781ad6265SDimitry Andric       const auto *Entry = FSet.findLock(FactMan, UnderlyingMutex.Cap);
92881ad6265SDimitry Andric       if ((UnderlyingMutex.Kind == UCK_Acquired && Entry) ||
92981ad6265SDimitry Andric           (UnderlyingMutex.Kind != UCK_Acquired && !Entry)) {
9300b57cec5SDimitry Andric         // If this scoped lock manages another mutex, and if the underlying
9310b57cec5SDimitry Andric         // mutex is still/not held, then warn about the underlying mutex.
93281ad6265SDimitry Andric         Handler.handleMutexHeldEndOfScope(UnderlyingMutex.Cap.getKind(),
93381ad6265SDimitry Andric                                           UnderlyingMutex.Cap.toString(), loc(),
93481ad6265SDimitry Andric                                           JoinLoc, LEK);
9350b57cec5SDimitry Andric       }
9360b57cec5SDimitry Andric     }
9370b57cec5SDimitry Andric   }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
94081ad6265SDimitry Andric                   ThreadSafetyHandler &Handler) const override {
9410b57cec5SDimitry Andric     for (const auto &UnderlyingMutex : UnderlyingMutexes) {
94281ad6265SDimitry Andric       if (UnderlyingMutex.Kind == UCK_Acquired)
94381ad6265SDimitry Andric         lock(FSet, FactMan, UnderlyingMutex.Cap, entry.kind(), entry.loc(),
94481ad6265SDimitry Andric              &Handler);
9450b57cec5SDimitry Andric       else
94681ad6265SDimitry Andric         unlock(FSet, FactMan, UnderlyingMutex.Cap, entry.loc(), &Handler);
9470b57cec5SDimitry Andric     }
9480b57cec5SDimitry Andric   }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   void handleUnlock(FactSet &FSet, FactManager &FactMan,
9510b57cec5SDimitry Andric                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
95281ad6265SDimitry Andric                     bool FullyRemove,
95381ad6265SDimitry Andric                     ThreadSafetyHandler &Handler) const override {
9540b57cec5SDimitry Andric     assert(!Cp.negative() && "Managing object cannot be negative.");
9550b57cec5SDimitry Andric     for (const auto &UnderlyingMutex : UnderlyingMutexes) {
9560b57cec5SDimitry Andric       // Remove/lock the underlying mutex if it exists/is still unlocked; warn
9570b57cec5SDimitry Andric       // on double unlocking/locking if we're not destroying the scoped object.
9580b57cec5SDimitry Andric       ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler;
95981ad6265SDimitry Andric       if (UnderlyingMutex.Kind == UCK_Acquired) {
96081ad6265SDimitry Andric         unlock(FSet, FactMan, UnderlyingMutex.Cap, UnlockLoc, TSHandler);
9610b57cec5SDimitry Andric       } else {
96281ad6265SDimitry Andric         LockKind kind = UnderlyingMutex.Kind == UCK_ReleasedShared
9630b57cec5SDimitry Andric                             ? LK_Shared
9640b57cec5SDimitry Andric                             : LK_Exclusive;
96581ad6265SDimitry Andric         lock(FSet, FactMan, UnderlyingMutex.Cap, kind, UnlockLoc, TSHandler);
9660b57cec5SDimitry Andric       }
9670b57cec5SDimitry Andric     }
9680b57cec5SDimitry Andric     if (FullyRemove)
9690b57cec5SDimitry Andric       FSet.removeLock(FactMan, Cp);
9700b57cec5SDimitry Andric   }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric private:
9730b57cec5SDimitry Andric   void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
97481ad6265SDimitry Andric             LockKind kind, SourceLocation loc,
97581ad6265SDimitry Andric             ThreadSafetyHandler *Handler) const {
9760b57cec5SDimitry Andric     if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
9770b57cec5SDimitry Andric       if (Handler)
97881ad6265SDimitry Andric         Handler->handleDoubleLock(Cp.getKind(), Cp.toString(), Fact->loc(),
97981ad6265SDimitry Andric                                   loc);
9800b57cec5SDimitry Andric     } else {
9810b57cec5SDimitry Andric       FSet.removeLock(FactMan, !Cp);
9820b57cec5SDimitry Andric       FSet.addLock(FactMan,
983fe6060f1SDimitry Andric                    std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed));
9840b57cec5SDimitry Andric     }
9850b57cec5SDimitry Andric   }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
98881ad6265SDimitry Andric               SourceLocation loc, ThreadSafetyHandler *Handler) const {
9890b57cec5SDimitry Andric     if (FSet.findLock(FactMan, Cp)) {
9900b57cec5SDimitry Andric       FSet.removeLock(FactMan, Cp);
991a7dea167SDimitry Andric       FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
9920b57cec5SDimitry Andric                                 !Cp, LK_Exclusive, loc));
9930b57cec5SDimitry Andric     } else if (Handler) {
9945ffd83dbSDimitry Andric       SourceLocation PrevLoc;
9955ffd83dbSDimitry Andric       if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
9965ffd83dbSDimitry Andric         PrevLoc = Neg->loc();
99781ad6265SDimitry Andric       Handler->handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), loc, PrevLoc);
9980b57cec5SDimitry Andric     }
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric };
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric /// Class which implements the core thread safety analysis routines.
10030b57cec5SDimitry Andric class ThreadSafetyAnalyzer {
10040b57cec5SDimitry Andric   friend class BuildLockset;
10050b57cec5SDimitry Andric   friend class threadSafety::BeforeSet;
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   llvm::BumpPtrAllocator Bpa;
10080b57cec5SDimitry Andric   threadSafety::til::MemRegionRef Arena;
10090b57cec5SDimitry Andric   threadSafety::SExprBuilder SxBuilder;
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   ThreadSafetyHandler &Handler;
10120b57cec5SDimitry Andric   const CXXMethodDecl *CurrentMethod;
10130b57cec5SDimitry Andric   LocalVariableMap LocalVarMap;
10140b57cec5SDimitry Andric   FactManager FactMan;
10150b57cec5SDimitry Andric   std::vector<CFGBlockInfo> BlockInfo;
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   BeforeSet *GlobalBeforeSet;
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric public:
10200b57cec5SDimitry Andric   ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
10210b57cec5SDimitry Andric       : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   bool inCurrentScope(const CapabilityExpr &CapE);
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
102681ad6265SDimitry Andric                bool ReqAttr = false);
10270b57cec5SDimitry Andric   void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
102881ad6265SDimitry Andric                   SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind);
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   template <typename AttrType>
10310b57cec5SDimitry Andric   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1032*bdd1243dSDimitry Andric                    const NamedDecl *D, til::SExpr *Self = nullptr);
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   template <class AttrType>
10350b57cec5SDimitry Andric   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
10360b57cec5SDimitry Andric                    const NamedDecl *D,
10370b57cec5SDimitry Andric                    const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
10380b57cec5SDimitry Andric                    Expr *BrE, bool Neg);
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric   const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
10410b57cec5SDimitry Andric                                      bool &Negate);
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
10440b57cec5SDimitry Andric                       const CFGBlock* PredBlock,
10450b57cec5SDimitry Andric                       const CFGBlock *CurrBlock);
10460b57cec5SDimitry Andric 
104728a41182SDimitry Andric   bool join(const FactEntry &a, const FactEntry &b, bool CanModify);
10480b57cec5SDimitry Andric 
1049fe6060f1SDimitry Andric   void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet,
1050fe6060f1SDimitry Andric                         SourceLocation JoinLoc, LockErrorKind EntryLEK,
1051fe6060f1SDimitry Andric                         LockErrorKind ExitLEK);
1052fe6060f1SDimitry Andric 
1053fe6060f1SDimitry Andric   void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet,
1054fe6060f1SDimitry Andric                         SourceLocation JoinLoc, LockErrorKind LEK) {
1055fe6060f1SDimitry Andric     intersectAndWarn(EntrySet, ExitSet, JoinLoc, LEK, LEK);
10560b57cec5SDimitry Andric   }
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   void runAnalysis(AnalysisDeclContext &AC);
10590b57cec5SDimitry Andric };
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric } // namespace
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric /// Process acquired_before and acquired_after attributes on Vd.
10640b57cec5SDimitry Andric BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
10650b57cec5SDimitry Andric     ThreadSafetyAnalyzer& Analyzer) {
10660b57cec5SDimitry Andric   // Create a new entry for Vd.
10670b57cec5SDimitry Andric   BeforeInfo *Info = nullptr;
10680b57cec5SDimitry Andric   {
10690b57cec5SDimitry Andric     // Keep InfoPtr in its own scope in case BMap is modified later and the
10700b57cec5SDimitry Andric     // reference becomes invalid.
10710b57cec5SDimitry Andric     std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
10720b57cec5SDimitry Andric     if (!InfoPtr)
10730b57cec5SDimitry Andric       InfoPtr.reset(new BeforeInfo());
10740b57cec5SDimitry Andric     Info = InfoPtr.get();
10750b57cec5SDimitry Andric   }
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric   for (const auto *At : Vd->attrs()) {
10780b57cec5SDimitry Andric     switch (At->getKind()) {
10790b57cec5SDimitry Andric       case attr::AcquiredBefore: {
10800b57cec5SDimitry Andric         const auto *A = cast<AcquiredBeforeAttr>(At);
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric         // Read exprs from the attribute, and add them to BeforeVect.
10830b57cec5SDimitry Andric         for (const auto *Arg : A->args()) {
10840b57cec5SDimitry Andric           CapabilityExpr Cp =
10850b57cec5SDimitry Andric             Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
10860b57cec5SDimitry Andric           if (const ValueDecl *Cpvd = Cp.valueDecl()) {
10870b57cec5SDimitry Andric             Info->Vect.push_back(Cpvd);
10880b57cec5SDimitry Andric             const auto It = BMap.find(Cpvd);
10890b57cec5SDimitry Andric             if (It == BMap.end())
10900b57cec5SDimitry Andric               insertAttrExprs(Cpvd, Analyzer);
10910b57cec5SDimitry Andric           }
10920b57cec5SDimitry Andric         }
10930b57cec5SDimitry Andric         break;
10940b57cec5SDimitry Andric       }
10950b57cec5SDimitry Andric       case attr::AcquiredAfter: {
10960b57cec5SDimitry Andric         const auto *A = cast<AcquiredAfterAttr>(At);
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric         // Read exprs from the attribute, and add them to BeforeVect.
10990b57cec5SDimitry Andric         for (const auto *Arg : A->args()) {
11000b57cec5SDimitry Andric           CapabilityExpr Cp =
11010b57cec5SDimitry Andric             Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
11020b57cec5SDimitry Andric           if (const ValueDecl *ArgVd = Cp.valueDecl()) {
11030b57cec5SDimitry Andric             // Get entry for mutex listed in attribute
11040b57cec5SDimitry Andric             BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
11050b57cec5SDimitry Andric             ArgInfo->Vect.push_back(Vd);
11060b57cec5SDimitry Andric           }
11070b57cec5SDimitry Andric         }
11080b57cec5SDimitry Andric         break;
11090b57cec5SDimitry Andric       }
11100b57cec5SDimitry Andric       default:
11110b57cec5SDimitry Andric         break;
11120b57cec5SDimitry Andric     }
11130b57cec5SDimitry Andric   }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   return Info;
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric BeforeSet::BeforeInfo *
11190b57cec5SDimitry Andric BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
11200b57cec5SDimitry Andric                                 ThreadSafetyAnalyzer &Analyzer) {
11210b57cec5SDimitry Andric   auto It = BMap.find(Vd);
11220b57cec5SDimitry Andric   BeforeInfo *Info = nullptr;
11230b57cec5SDimitry Andric   if (It == BMap.end())
11240b57cec5SDimitry Andric     Info = insertAttrExprs(Vd, Analyzer);
11250b57cec5SDimitry Andric   else
11260b57cec5SDimitry Andric     Info = It->second.get();
11270b57cec5SDimitry Andric   assert(Info && "BMap contained nullptr?");
11280b57cec5SDimitry Andric   return Info;
11290b57cec5SDimitry Andric }
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric /// Return true if any mutexes in FSet are in the acquired_before set of Vd.
11320b57cec5SDimitry Andric void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
11330b57cec5SDimitry Andric                                  const FactSet& FSet,
11340b57cec5SDimitry Andric                                  ThreadSafetyAnalyzer& Analyzer,
11350b57cec5SDimitry Andric                                  SourceLocation Loc, StringRef CapKind) {
11360b57cec5SDimitry Andric   SmallVector<BeforeInfo*, 8> InfoVect;
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   // Do a depth-first traversal of Vd.
11390b57cec5SDimitry Andric   // Return true if there are cycles.
11400b57cec5SDimitry Andric   std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
11410b57cec5SDimitry Andric     if (!Vd)
11420b57cec5SDimitry Andric       return false;
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric     BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     if (Info->Visited == 1)
11470b57cec5SDimitry Andric       return true;
11480b57cec5SDimitry Andric 
11490b57cec5SDimitry Andric     if (Info->Visited == 2)
11500b57cec5SDimitry Andric       return false;
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric     if (Info->Vect.empty())
11530b57cec5SDimitry Andric       return false;
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric     InfoVect.push_back(Info);
11560b57cec5SDimitry Andric     Info->Visited = 1;
11570b57cec5SDimitry Andric     for (const auto *Vdb : Info->Vect) {
11580b57cec5SDimitry Andric       // Exclude mutexes in our immediate before set.
11590b57cec5SDimitry Andric       if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
11600b57cec5SDimitry Andric         StringRef L1 = StartVd->getName();
11610b57cec5SDimitry Andric         StringRef L2 = Vdb->getName();
11620b57cec5SDimitry Andric         Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
11630b57cec5SDimitry Andric       }
11640b57cec5SDimitry Andric       // Transitively search other before sets, and warn on cycles.
11650b57cec5SDimitry Andric       if (traverse(Vdb)) {
11660b57cec5SDimitry Andric         if (CycMap.find(Vd) == CycMap.end()) {
11670b57cec5SDimitry Andric           CycMap.insert(std::make_pair(Vd, true));
11680b57cec5SDimitry Andric           StringRef L1 = Vd->getName();
11690b57cec5SDimitry Andric           Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
11700b57cec5SDimitry Andric         }
11710b57cec5SDimitry Andric       }
11720b57cec5SDimitry Andric     }
11730b57cec5SDimitry Andric     Info->Visited = 2;
11740b57cec5SDimitry Andric     return false;
11750b57cec5SDimitry Andric   };
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   traverse(StartVd);
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   for (auto *Info : InfoVect)
11800b57cec5SDimitry Andric     Info->Visited = 0;
11810b57cec5SDimitry Andric }
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric /// Gets the value decl pointer from DeclRefExprs or MemberExprs.
11840b57cec5SDimitry Andric static const ValueDecl *getValueDecl(const Expr *Exp) {
11850b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
11860b57cec5SDimitry Andric     return getValueDecl(CE->getSubExpr());
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric   if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
11890b57cec5SDimitry Andric     return DR->getDecl();
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(Exp))
11920b57cec5SDimitry Andric     return ME->getMemberDecl();
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   return nullptr;
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric namespace {
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric template <typename Ty>
12000b57cec5SDimitry Andric class has_arg_iterator_range {
12010b57cec5SDimitry Andric   using yes = char[1];
12020b57cec5SDimitry Andric   using no = char[2];
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   template <typename Inner>
12050b57cec5SDimitry Andric   static yes& test(Inner *I, decltype(I->args()) * = nullptr);
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   template <typename>
12080b57cec5SDimitry Andric   static no& test(...);
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric public:
12110b57cec5SDimitry Andric   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
12120b57cec5SDimitry Andric };
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric } // namespace
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1217e8d8bef9SDimitry Andric   const threadSafety::til::SExpr *SExp = CapE.sexpr();
1218e8d8bef9SDimitry Andric   assert(SExp && "Null expressions should be ignored");
1219e8d8bef9SDimitry Andric 
1220e8d8bef9SDimitry Andric   if (const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) {
1221e8d8bef9SDimitry Andric     const ValueDecl *VD = LP->clangDecl();
1222e8d8bef9SDimitry Andric     // Variables defined in a function are always inaccessible.
1223*bdd1243dSDimitry Andric     if (!VD || !VD->isDefinedOutsideFunctionOrMethod())
1224e8d8bef9SDimitry Andric       return false;
1225e8d8bef9SDimitry Andric     // For now we consider static class members to be inaccessible.
1226e8d8bef9SDimitry Andric     if (isa<CXXRecordDecl>(VD->getDeclContext()))
1227e8d8bef9SDimitry Andric       return false;
1228e8d8bef9SDimitry Andric     // Global variables are always in scope.
1229e8d8bef9SDimitry Andric     return true;
1230e8d8bef9SDimitry Andric   }
1231e8d8bef9SDimitry Andric 
1232e8d8bef9SDimitry Andric   // Members are in scope from methods of the same class.
1233e8d8bef9SDimitry Andric   if (const auto *P = dyn_cast<til::Project>(SExp)) {
12340b57cec5SDimitry Andric     if (!CurrentMethod)
12350b57cec5SDimitry Andric       return false;
1236e8d8bef9SDimitry Andric     const ValueDecl *VD = P->clangDecl();
12370b57cec5SDimitry Andric     return VD->getDeclContext() == CurrentMethod->getDeclContext();
12380b57cec5SDimitry Andric   }
1239e8d8bef9SDimitry Andric 
12400b57cec5SDimitry Andric   return false;
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric /// Add a new lock to the lockset, warning if the lock is already there.
12440b57cec5SDimitry Andric /// \param ReqAttr -- true if this is part of an initial Requires attribute.
12450b57cec5SDimitry Andric void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
12460b57cec5SDimitry Andric                                    std::unique_ptr<FactEntry> Entry,
124781ad6265SDimitry Andric                                    bool ReqAttr) {
12480b57cec5SDimitry Andric   if (Entry->shouldIgnore())
12490b57cec5SDimitry Andric     return;
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric   if (!ReqAttr && !Entry->negative()) {
12520b57cec5SDimitry Andric     // look for the negative capability, and remove it from the fact set.
12530b57cec5SDimitry Andric     CapabilityExpr NegC = !*Entry;
12540b57cec5SDimitry Andric     const FactEntry *Nen = FSet.findLock(FactMan, NegC);
12550b57cec5SDimitry Andric     if (Nen) {
12560b57cec5SDimitry Andric       FSet.removeLock(FactMan, NegC);
12570b57cec5SDimitry Andric     }
12580b57cec5SDimitry Andric     else {
12590b57cec5SDimitry Andric       if (inCurrentScope(*Entry) && !Entry->asserted())
126081ad6265SDimitry Andric         Handler.handleNegativeNotHeld(Entry->getKind(), Entry->toString(),
12610b57cec5SDimitry Andric                                       NegC.toString(), Entry->loc());
12620b57cec5SDimitry Andric     }
12630b57cec5SDimitry Andric   }
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   // Check before/after constraints
12660b57cec5SDimitry Andric   if (Handler.issueBetaWarnings() &&
12670b57cec5SDimitry Andric       !Entry->asserted() && !Entry->declared()) {
12680b57cec5SDimitry Andric     GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
126981ad6265SDimitry Andric                                       Entry->loc(), Entry->getKind());
12700b57cec5SDimitry Andric   }
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric   // FIXME: Don't always warn when we have support for reentrant locks.
12730b57cec5SDimitry Andric   if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
12740b57cec5SDimitry Andric     if (!Entry->asserted())
127581ad6265SDimitry Andric       Cp->handleLock(FSet, FactMan, *Entry, Handler);
12760b57cec5SDimitry Andric   } else {
12770b57cec5SDimitry Andric     FSet.addLock(FactMan, std::move(Entry));
12780b57cec5SDimitry Andric   }
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric /// Remove a lock from the lockset, warning if the lock is not there.
12820b57cec5SDimitry Andric /// \param UnlockLoc The source location of the unlock (only used in error msg)
12830b57cec5SDimitry Andric void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
12840b57cec5SDimitry Andric                                       SourceLocation UnlockLoc,
128581ad6265SDimitry Andric                                       bool FullyRemove, LockKind ReceivedKind) {
12860b57cec5SDimitry Andric   if (Cp.shouldIgnore())
12870b57cec5SDimitry Andric     return;
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric   const FactEntry *LDat = FSet.findLock(FactMan, Cp);
12900b57cec5SDimitry Andric   if (!LDat) {
12915ffd83dbSDimitry Andric     SourceLocation PrevLoc;
12925ffd83dbSDimitry Andric     if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
12935ffd83dbSDimitry Andric       PrevLoc = Neg->loc();
129481ad6265SDimitry Andric     Handler.handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), UnlockLoc,
129581ad6265SDimitry Andric                                   PrevLoc);
12960b57cec5SDimitry Andric     return;
12970b57cec5SDimitry Andric   }
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   // Generic lock removal doesn't care about lock kind mismatches, but
13000b57cec5SDimitry Andric   // otherwise diagnose when the lock kinds are mismatched.
13010b57cec5SDimitry Andric   if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
130281ad6265SDimitry Andric     Handler.handleIncorrectUnlockKind(Cp.getKind(), Cp.toString(), LDat->kind(),
13030b57cec5SDimitry Andric                                       ReceivedKind, LDat->loc(), UnlockLoc);
13040b57cec5SDimitry Andric   }
13050b57cec5SDimitry Andric 
130681ad6265SDimitry Andric   LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler);
13070b57cec5SDimitry Andric }
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric /// Extract the list of mutexIDs from the attribute on an expression,
13100b57cec5SDimitry Andric /// and push them onto Mtxs, discarding any duplicates.
13110b57cec5SDimitry Andric template <typename AttrType>
13120b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
13130b57cec5SDimitry Andric                                        const Expr *Exp, const NamedDecl *D,
1314*bdd1243dSDimitry Andric                                        til::SExpr *Self) {
13150b57cec5SDimitry Andric   if (Attr->args_size() == 0) {
13160b57cec5SDimitry Andric     // The mutex held is the "this" object.
1317*bdd1243dSDimitry Andric     CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, Self);
13180b57cec5SDimitry Andric     if (Cp.isInvalid()) {
131981ad6265SDimitry Andric       warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
13200b57cec5SDimitry Andric       return;
13210b57cec5SDimitry Andric     }
13220b57cec5SDimitry Andric     //else
13230b57cec5SDimitry Andric     if (!Cp.shouldIgnore())
13240b57cec5SDimitry Andric       Mtxs.push_back_nodup(Cp);
13250b57cec5SDimitry Andric     return;
13260b57cec5SDimitry Andric   }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric   for (const auto *Arg : Attr->args()) {
1329*bdd1243dSDimitry Andric     CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, Self);
13300b57cec5SDimitry Andric     if (Cp.isInvalid()) {
133181ad6265SDimitry Andric       warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
13320b57cec5SDimitry Andric       continue;
13330b57cec5SDimitry Andric     }
13340b57cec5SDimitry Andric     //else
13350b57cec5SDimitry Andric     if (!Cp.shouldIgnore())
13360b57cec5SDimitry Andric       Mtxs.push_back_nodup(Cp);
13370b57cec5SDimitry Andric   }
13380b57cec5SDimitry Andric }
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric /// Extract the list of mutexIDs from a trylock attribute.  If the
13410b57cec5SDimitry Andric /// trylock applies to the given edge, then push them onto Mtxs, discarding
13420b57cec5SDimitry Andric /// any duplicates.
13430b57cec5SDimitry Andric template <class AttrType>
13440b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
13450b57cec5SDimitry Andric                                        const Expr *Exp, const NamedDecl *D,
13460b57cec5SDimitry Andric                                        const CFGBlock *PredBlock,
13470b57cec5SDimitry Andric                                        const CFGBlock *CurrBlock,
13480b57cec5SDimitry Andric                                        Expr *BrE, bool Neg) {
13490b57cec5SDimitry Andric   // Find out which branch has the lock
13500b57cec5SDimitry Andric   bool branch = false;
13510b57cec5SDimitry Andric   if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
13520b57cec5SDimitry Andric     branch = BLE->getValue();
13530b57cec5SDimitry Andric   else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
13540b57cec5SDimitry Andric     branch = ILE->getValue().getBoolValue();
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric   int branchnum = branch ? 0 : 1;
13570b57cec5SDimitry Andric   if (Neg)
13580b57cec5SDimitry Andric     branchnum = !branchnum;
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric   // If we've taken the trylock branch, then add the lock
13610b57cec5SDimitry Andric   int i = 0;
13620b57cec5SDimitry Andric   for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
13630b57cec5SDimitry Andric        SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
13640b57cec5SDimitry Andric     if (*SI == CurrBlock && i == branchnum)
13650b57cec5SDimitry Andric       getMutexIDs(Mtxs, Attr, Exp, D);
13660b57cec5SDimitry Andric   }
13670b57cec5SDimitry Andric }
13680b57cec5SDimitry Andric 
13690b57cec5SDimitry Andric static bool getStaticBooleanValue(Expr *E, bool &TCond) {
13700b57cec5SDimitry Andric   if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
13710b57cec5SDimitry Andric     TCond = false;
13720b57cec5SDimitry Andric     return true;
13730b57cec5SDimitry Andric   } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
13740b57cec5SDimitry Andric     TCond = BLE->getValue();
13750b57cec5SDimitry Andric     return true;
13760b57cec5SDimitry Andric   } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
13770b57cec5SDimitry Andric     TCond = ILE->getValue().getBoolValue();
13780b57cec5SDimitry Andric     return true;
13790b57cec5SDimitry Andric   } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
13800b57cec5SDimitry Andric     return getStaticBooleanValue(CE->getSubExpr(), TCond);
13810b57cec5SDimitry Andric   return false;
13820b57cec5SDimitry Andric }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric // If Cond can be traced back to a function call, return the call expression.
13850b57cec5SDimitry Andric // The negate variable should be called with false, and will be set to true
13860b57cec5SDimitry Andric // if the function call is negated, e.g. if (!mu.tryLock(...))
13870b57cec5SDimitry Andric const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
13880b57cec5SDimitry Andric                                                          LocalVarContext C,
13890b57cec5SDimitry Andric                                                          bool &Negate) {
13900b57cec5SDimitry Andric   if (!Cond)
13910b57cec5SDimitry Andric     return nullptr;
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
13940b57cec5SDimitry Andric     if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
13950b57cec5SDimitry Andric       return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
13960b57cec5SDimitry Andric     return CallExp;
13970b57cec5SDimitry Andric   }
13980b57cec5SDimitry Andric   else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
13990b57cec5SDimitry Andric     return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
14000b57cec5SDimitry Andric   else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
14010b57cec5SDimitry Andric     return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
14020b57cec5SDimitry Andric   else if (const auto *FE = dyn_cast<FullExpr>(Cond))
14030b57cec5SDimitry Andric     return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
14040b57cec5SDimitry Andric   else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
14050b57cec5SDimitry Andric     const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
14060b57cec5SDimitry Andric     return getTrylockCallExpr(E, C, Negate);
14070b57cec5SDimitry Andric   }
14080b57cec5SDimitry Andric   else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
14090b57cec5SDimitry Andric     if (UOP->getOpcode() == UO_LNot) {
14100b57cec5SDimitry Andric       Negate = !Negate;
14110b57cec5SDimitry Andric       return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
14120b57cec5SDimitry Andric     }
14130b57cec5SDimitry Andric     return nullptr;
14140b57cec5SDimitry Andric   }
14150b57cec5SDimitry Andric   else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
14160b57cec5SDimitry Andric     if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
14170b57cec5SDimitry Andric       if (BOP->getOpcode() == BO_NE)
14180b57cec5SDimitry Andric         Negate = !Negate;
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric       bool TCond = false;
14210b57cec5SDimitry Andric       if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
14220b57cec5SDimitry Andric         if (!TCond) Negate = !Negate;
14230b57cec5SDimitry Andric         return getTrylockCallExpr(BOP->getLHS(), C, Negate);
14240b57cec5SDimitry Andric       }
14250b57cec5SDimitry Andric       TCond = false;
14260b57cec5SDimitry Andric       if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
14270b57cec5SDimitry Andric         if (!TCond) Negate = !Negate;
14280b57cec5SDimitry Andric         return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14290b57cec5SDimitry Andric       }
14300b57cec5SDimitry Andric       return nullptr;
14310b57cec5SDimitry Andric     }
14320b57cec5SDimitry Andric     if (BOP->getOpcode() == BO_LAnd) {
14330b57cec5SDimitry Andric       // LHS must have been evaluated in a different block.
14340b57cec5SDimitry Andric       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14350b57cec5SDimitry Andric     }
14360b57cec5SDimitry Andric     if (BOP->getOpcode() == BO_LOr)
14370b57cec5SDimitry Andric       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14380b57cec5SDimitry Andric     return nullptr;
14390b57cec5SDimitry Andric   } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
14400b57cec5SDimitry Andric     bool TCond, FCond;
14410b57cec5SDimitry Andric     if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
14420b57cec5SDimitry Andric         getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
14430b57cec5SDimitry Andric       if (TCond && !FCond)
14440b57cec5SDimitry Andric         return getTrylockCallExpr(COP->getCond(), C, Negate);
14450b57cec5SDimitry Andric       if (!TCond && FCond) {
14460b57cec5SDimitry Andric         Negate = !Negate;
14470b57cec5SDimitry Andric         return getTrylockCallExpr(COP->getCond(), C, Negate);
14480b57cec5SDimitry Andric       }
14490b57cec5SDimitry Andric     }
14500b57cec5SDimitry Andric   }
14510b57cec5SDimitry Andric   return nullptr;
14520b57cec5SDimitry Andric }
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric /// Find the lockset that holds on the edge between PredBlock
14550b57cec5SDimitry Andric /// and CurrBlock.  The edge set is the exit set of PredBlock (passed
14560b57cec5SDimitry Andric /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
14570b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
14580b57cec5SDimitry Andric                                           const FactSet &ExitSet,
14590b57cec5SDimitry Andric                                           const CFGBlock *PredBlock,
14600b57cec5SDimitry Andric                                           const CFGBlock *CurrBlock) {
14610b57cec5SDimitry Andric   Result = ExitSet;
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   const Stmt *Cond = PredBlock->getTerminatorCondition();
14640b57cec5SDimitry Andric   // We don't acquire try-locks on ?: branches, only when its result is used.
14650b57cec5SDimitry Andric   if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminatorStmt()))
14660b57cec5SDimitry Andric     return;
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric   bool Negate = false;
14690b57cec5SDimitry Andric   const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
14700b57cec5SDimitry Andric   const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
14730b57cec5SDimitry Andric   if (!Exp)
14740b57cec5SDimitry Andric     return;
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric   auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
14770b57cec5SDimitry Andric   if(!FunDecl || !FunDecl->hasAttrs())
14780b57cec5SDimitry Andric     return;
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric   CapExprSet ExclusiveLocksToAdd;
14810b57cec5SDimitry Andric   CapExprSet SharedLocksToAdd;
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   // If the condition is a call to a Trylock function, then grab the attributes
14840b57cec5SDimitry Andric   for (const auto *Attr : FunDecl->attrs()) {
14850b57cec5SDimitry Andric     switch (Attr->getKind()) {
14860b57cec5SDimitry Andric       case attr::TryAcquireCapability: {
14870b57cec5SDimitry Andric         auto *A = cast<TryAcquireCapabilityAttr>(Attr);
14880b57cec5SDimitry Andric         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
14890b57cec5SDimitry Andric                     Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
14900b57cec5SDimitry Andric                     Negate);
14910b57cec5SDimitry Andric         break;
14920b57cec5SDimitry Andric       };
14930b57cec5SDimitry Andric       case attr::ExclusiveTrylockFunction: {
14940b57cec5SDimitry Andric         const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
149581ad6265SDimitry Andric         getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
149681ad6265SDimitry Andric                     A->getSuccessValue(), Negate);
14970b57cec5SDimitry Andric         break;
14980b57cec5SDimitry Andric       }
14990b57cec5SDimitry Andric       case attr::SharedTrylockFunction: {
15000b57cec5SDimitry Andric         const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
150181ad6265SDimitry Andric         getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
150281ad6265SDimitry Andric                     A->getSuccessValue(), Negate);
15030b57cec5SDimitry Andric         break;
15040b57cec5SDimitry Andric       }
15050b57cec5SDimitry Andric       default:
15060b57cec5SDimitry Andric         break;
15070b57cec5SDimitry Andric     }
15080b57cec5SDimitry Andric   }
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric   // Add and remove locks.
15110b57cec5SDimitry Andric   SourceLocation Loc = Exp->getExprLoc();
15120b57cec5SDimitry Andric   for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1513a7dea167SDimitry Andric     addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
151481ad6265SDimitry Andric                                                         LK_Exclusive, Loc));
15150b57cec5SDimitry Andric   for (const auto &SharedLockToAdd : SharedLocksToAdd)
1516a7dea167SDimitry Andric     addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd,
151781ad6265SDimitry Andric                                                         LK_Shared, Loc));
15180b57cec5SDimitry Andric }
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric namespace {
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric /// We use this class to visit different types of expressions in
15230b57cec5SDimitry Andric /// CFGBlocks, and build up the lockset.
15240b57cec5SDimitry Andric /// An expression may cause us to add or remove locks from the lockset, or else
15250b57cec5SDimitry Andric /// output error messages related to missing locks.
15260b57cec5SDimitry Andric /// FIXME: In future, we may be able to not inherit from a visitor.
15270b57cec5SDimitry Andric class BuildLockset : public ConstStmtVisitor<BuildLockset> {
15280b57cec5SDimitry Andric   friend class ThreadSafetyAnalyzer;
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   ThreadSafetyAnalyzer *Analyzer;
15310b57cec5SDimitry Andric   FactSet FSet;
1532*bdd1243dSDimitry Andric   /// Maps constructed objects to `this` placeholder prior to initialization.
1533*bdd1243dSDimitry Andric   llvm::SmallDenseMap<const Expr *, til::LiteralPtr *> ConstructedObjects;
15340b57cec5SDimitry Andric   LocalVariableMap::Context LVarCtx;
15350b57cec5SDimitry Andric   unsigned CtxIndex;
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric   // helper functions
15380b57cec5SDimitry Andric   void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
15390b57cec5SDimitry Andric                           Expr *MutexExp, ProtectedOperationKind POK,
1540*bdd1243dSDimitry Andric                           til::LiteralPtr *Self, SourceLocation Loc);
1541*bdd1243dSDimitry Andric   void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1542*bdd1243dSDimitry Andric                        til::LiteralPtr *Self, SourceLocation Loc);
15430b57cec5SDimitry Andric 
15440b57cec5SDimitry Andric   void checkAccess(const Expr *Exp, AccessKind AK,
15450b57cec5SDimitry Andric                    ProtectedOperationKind POK = POK_VarAccess);
15460b57cec5SDimitry Andric   void checkPtAccess(const Expr *Exp, AccessKind AK,
15470b57cec5SDimitry Andric                      ProtectedOperationKind POK = POK_VarAccess);
15480b57cec5SDimitry Andric 
1549*bdd1243dSDimitry Andric   void handleCall(const Expr *Exp, const NamedDecl *D,
1550*bdd1243dSDimitry Andric                   til::LiteralPtr *Self = nullptr,
1551*bdd1243dSDimitry Andric                   SourceLocation Loc = SourceLocation());
15520b57cec5SDimitry Andric   void examineArguments(const FunctionDecl *FD,
15530b57cec5SDimitry Andric                         CallExpr::const_arg_iterator ArgBegin,
15540b57cec5SDimitry Andric                         CallExpr::const_arg_iterator ArgEnd,
15550b57cec5SDimitry Andric                         bool SkipFirstParam = false);
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric public:
15580b57cec5SDimitry Andric   BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
15590b57cec5SDimitry Andric       : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
15600b57cec5SDimitry Andric         LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   void VisitUnaryOperator(const UnaryOperator *UO);
15630b57cec5SDimitry Andric   void VisitBinaryOperator(const BinaryOperator *BO);
15640b57cec5SDimitry Andric   void VisitCastExpr(const CastExpr *CE);
15650b57cec5SDimitry Andric   void VisitCallExpr(const CallExpr *Exp);
15660b57cec5SDimitry Andric   void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
15670b57cec5SDimitry Andric   void VisitDeclStmt(const DeclStmt *S);
1568*bdd1243dSDimitry Andric   void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Exp);
15690b57cec5SDimitry Andric };
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric } // namespace
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric /// Warn if the LSet does not contain a lock sufficient to protect access
15740b57cec5SDimitry Andric /// of at least the passed in AccessKind.
15750b57cec5SDimitry Andric void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
15760b57cec5SDimitry Andric                                       AccessKind AK, Expr *MutexExp,
15770b57cec5SDimitry Andric                                       ProtectedOperationKind POK,
1578*bdd1243dSDimitry Andric                                       til::LiteralPtr *Self,
157981ad6265SDimitry Andric                                       SourceLocation Loc) {
15800b57cec5SDimitry Andric   LockKind LK = getLockKindFromAccessKind(AK);
15810b57cec5SDimitry Andric 
1582*bdd1243dSDimitry Andric   CapabilityExpr Cp =
1583*bdd1243dSDimitry Andric       Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp, Self);
15840b57cec5SDimitry Andric   if (Cp.isInvalid()) {
158581ad6265SDimitry Andric     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, Cp.getKind());
15860b57cec5SDimitry Andric     return;
15870b57cec5SDimitry Andric   } else if (Cp.shouldIgnore()) {
15880b57cec5SDimitry Andric     return;
15890b57cec5SDimitry Andric   }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   if (Cp.negative()) {
15920b57cec5SDimitry Andric     // Negative capabilities act like locks excluded
15930b57cec5SDimitry Andric     const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
15940b57cec5SDimitry Andric     if (LDat) {
15950b57cec5SDimitry Andric       Analyzer->Handler.handleFunExcludesLock(
159681ad6265SDimitry Andric           Cp.getKind(), D->getNameAsString(), (!Cp).toString(), Loc);
15970b57cec5SDimitry Andric       return;
15980b57cec5SDimitry Andric     }
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric     // If this does not refer to a negative capability in the same class,
16010b57cec5SDimitry Andric     // then stop here.
16020b57cec5SDimitry Andric     if (!Analyzer->inCurrentScope(Cp))
16030b57cec5SDimitry Andric       return;
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric     // Otherwise the negative requirement must be propagated to the caller.
16060b57cec5SDimitry Andric     LDat = FSet.findLock(Analyzer->FactMan, Cp);
16070b57cec5SDimitry Andric     if (!LDat) {
1608e8d8bef9SDimitry Andric       Analyzer->Handler.handleNegativeNotHeld(D, Cp.toString(), Loc);
16090b57cec5SDimitry Andric     }
16100b57cec5SDimitry Andric     return;
16110b57cec5SDimitry Andric   }
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
16140b57cec5SDimitry Andric   bool NoError = true;
16150b57cec5SDimitry Andric   if (!LDat) {
16160b57cec5SDimitry Andric     // No exact match found.  Look for a partial match.
16170b57cec5SDimitry Andric     LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
16180b57cec5SDimitry Andric     if (LDat) {
16190b57cec5SDimitry Andric       // Warn that there's no precise match.
16200b57cec5SDimitry Andric       std::string PartMatchStr = LDat->toString();
16210b57cec5SDimitry Andric       StringRef   PartMatchName(PartMatchStr);
162281ad6265SDimitry Andric       Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
16230b57cec5SDimitry Andric                                            LK, Loc, &PartMatchName);
16240b57cec5SDimitry Andric     } else {
16250b57cec5SDimitry Andric       // Warn that there's no match at all.
162681ad6265SDimitry Andric       Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
16270b57cec5SDimitry Andric                                            LK, Loc);
16280b57cec5SDimitry Andric     }
16290b57cec5SDimitry Andric     NoError = false;
16300b57cec5SDimitry Andric   }
16310b57cec5SDimitry Andric   // Make sure the mutex we found is the right kind.
16320b57cec5SDimitry Andric   if (NoError && LDat && !LDat->isAtLeast(LK)) {
163381ad6265SDimitry Andric     Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
16340b57cec5SDimitry Andric                                          LK, Loc);
16350b57cec5SDimitry Andric   }
16360b57cec5SDimitry Andric }
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric /// Warn if the LSet contains the given lock.
16390b57cec5SDimitry Andric void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1640*bdd1243dSDimitry Andric                                    Expr *MutexExp, til::LiteralPtr *Self,
1641*bdd1243dSDimitry Andric                                    SourceLocation Loc) {
1642*bdd1243dSDimitry Andric   CapabilityExpr Cp =
1643*bdd1243dSDimitry Andric       Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp, Self);
16440b57cec5SDimitry Andric   if (Cp.isInvalid()) {
164581ad6265SDimitry Andric     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, Cp.getKind());
16460b57cec5SDimitry Andric     return;
16470b57cec5SDimitry Andric   } else if (Cp.shouldIgnore()) {
16480b57cec5SDimitry Andric     return;
16490b57cec5SDimitry Andric   }
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
16520b57cec5SDimitry Andric   if (LDat) {
165381ad6265SDimitry Andric     Analyzer->Handler.handleFunExcludesLock(Cp.getKind(), D->getNameAsString(),
1654*bdd1243dSDimitry Andric                                             Cp.toString(), Loc);
16550b57cec5SDimitry Andric   }
16560b57cec5SDimitry Andric }
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric /// Checks guarded_by and pt_guarded_by attributes.
16590b57cec5SDimitry Andric /// Whenever we identify an access (read or write) to a DeclRefExpr that is
16600b57cec5SDimitry Andric /// marked with guarded_by, we must ensure the appropriate mutexes are held.
16610b57cec5SDimitry Andric /// Similarly, we check if the access is to an expression that dereferences
16620b57cec5SDimitry Andric /// a pointer marked with pt_guarded_by.
16630b57cec5SDimitry Andric void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
16640b57cec5SDimitry Andric                                ProtectedOperationKind POK) {
16650b57cec5SDimitry Andric   Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric   SourceLocation Loc = Exp->getExprLoc();
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   // Local variables of reference type cannot be re-assigned;
16700b57cec5SDimitry Andric   // map them to their initializer.
16710b57cec5SDimitry Andric   while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
16720b57cec5SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
16730b57cec5SDimitry Andric     if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
16740b57cec5SDimitry Andric       if (const auto *E = VD->getInit()) {
16750b57cec5SDimitry Andric         // Guard against self-initialization. e.g., int &i = i;
16760b57cec5SDimitry Andric         if (E == Exp)
16770b57cec5SDimitry Andric           break;
16780b57cec5SDimitry Andric         Exp = E;
16790b57cec5SDimitry Andric         continue;
16800b57cec5SDimitry Andric       }
16810b57cec5SDimitry Andric     }
16820b57cec5SDimitry Andric     break;
16830b57cec5SDimitry Andric   }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
16860b57cec5SDimitry Andric     // For dereferences
16870b57cec5SDimitry Andric     if (UO->getOpcode() == UO_Deref)
16880b57cec5SDimitry Andric       checkPtAccess(UO->getSubExpr(), AK, POK);
16890b57cec5SDimitry Andric     return;
16900b57cec5SDimitry Andric   }
16910b57cec5SDimitry Andric 
1692fcaf7f86SDimitry Andric   if (const auto *BO = dyn_cast<BinaryOperator>(Exp)) {
1693fcaf7f86SDimitry Andric     switch (BO->getOpcode()) {
1694fcaf7f86SDimitry Andric     case BO_PtrMemD: // .*
1695fcaf7f86SDimitry Andric       return checkAccess(BO->getLHS(), AK, POK);
1696fcaf7f86SDimitry Andric     case BO_PtrMemI: // ->*
1697fcaf7f86SDimitry Andric       return checkPtAccess(BO->getLHS(), AK, POK);
1698fcaf7f86SDimitry Andric     default:
1699fcaf7f86SDimitry Andric       return;
1700fcaf7f86SDimitry Andric     }
1701fcaf7f86SDimitry Andric   }
1702fcaf7f86SDimitry Andric 
17030b57cec5SDimitry Andric   if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
17040b57cec5SDimitry Andric     checkPtAccess(AE->getLHS(), AK, POK);
17050b57cec5SDimitry Andric     return;
17060b57cec5SDimitry Andric   }
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
17090b57cec5SDimitry Andric     if (ME->isArrow())
17100b57cec5SDimitry Andric       checkPtAccess(ME->getBase(), AK, POK);
17110b57cec5SDimitry Andric     else
17120b57cec5SDimitry Andric       checkAccess(ME->getBase(), AK, POK);
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   const ValueDecl *D = getValueDecl(Exp);
17160b57cec5SDimitry Andric   if (!D || !D->hasAttrs())
17170b57cec5SDimitry Andric     return;
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
172081ad6265SDimitry Andric     Analyzer->Handler.handleNoMutexHeld(D, POK, AK, Loc);
17210b57cec5SDimitry Andric   }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<GuardedByAttr>())
1724*bdd1243dSDimitry Andric     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK, nullptr, Loc);
17250b57cec5SDimitry Andric }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric /// Checks pt_guarded_by and pt_guarded_var attributes.
17280b57cec5SDimitry Andric /// POK is the same  operationKind that was passed to checkAccess.
17290b57cec5SDimitry Andric void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
17300b57cec5SDimitry Andric                                  ProtectedOperationKind POK) {
17310b57cec5SDimitry Andric   while (true) {
17320b57cec5SDimitry Andric     if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
17330b57cec5SDimitry Andric       Exp = PE->getSubExpr();
17340b57cec5SDimitry Andric       continue;
17350b57cec5SDimitry Andric     }
17360b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
17370b57cec5SDimitry Andric       if (CE->getCastKind() == CK_ArrayToPointerDecay) {
17380b57cec5SDimitry Andric         // If it's an actual array, and not a pointer, then it's elements
17390b57cec5SDimitry Andric         // are protected by GUARDED_BY, not PT_GUARDED_BY;
17400b57cec5SDimitry Andric         checkAccess(CE->getSubExpr(), AK, POK);
17410b57cec5SDimitry Andric         return;
17420b57cec5SDimitry Andric       }
17430b57cec5SDimitry Andric       Exp = CE->getSubExpr();
17440b57cec5SDimitry Andric       continue;
17450b57cec5SDimitry Andric     }
17460b57cec5SDimitry Andric     break;
17470b57cec5SDimitry Andric   }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   // Pass by reference warnings are under a different flag.
17500b57cec5SDimitry Andric   ProtectedOperationKind PtPOK = POK_VarDereference;
17510b57cec5SDimitry Andric   if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   const ValueDecl *D = getValueDecl(Exp);
17540b57cec5SDimitry Andric   if (!D || !D->hasAttrs())
17550b57cec5SDimitry Andric     return;
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
175881ad6265SDimitry Andric     Analyzer->Handler.handleNoMutexHeld(D, PtPOK, AK, Exp->getExprLoc());
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric   for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1761*bdd1243dSDimitry Andric     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK, nullptr,
1762*bdd1243dSDimitry Andric                        Exp->getExprLoc());
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric /// Process a function call, method call, constructor call,
17660b57cec5SDimitry Andric /// or destructor call.  This involves looking at the attributes on the
17670b57cec5SDimitry Andric /// corresponding function/method/constructor/destructor, issuing warnings,
17680b57cec5SDimitry Andric /// and updating the locksets accordingly.
17690b57cec5SDimitry Andric ///
17700b57cec5SDimitry Andric /// FIXME: For classes annotated with one of the guarded annotations, we need
17710b57cec5SDimitry Andric /// to treat const method calls as reads and non-const method calls as writes,
17720b57cec5SDimitry Andric /// and check that the appropriate locks are held. Non-const method calls with
17730b57cec5SDimitry Andric /// the same signature as const method calls can be also treated as reads.
17740b57cec5SDimitry Andric ///
1775*bdd1243dSDimitry Andric /// \param Exp   The call expression.
1776*bdd1243dSDimitry Andric /// \param D     The callee declaration.
1777*bdd1243dSDimitry Andric /// \param Self  If \p Exp = nullptr, the implicit this argument.
1778*bdd1243dSDimitry Andric /// \param Loc   If \p Exp = nullptr, the location.
17790b57cec5SDimitry Andric void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1780*bdd1243dSDimitry Andric                               til::LiteralPtr *Self, SourceLocation Loc) {
17810b57cec5SDimitry Andric   CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
17820b57cec5SDimitry Andric   CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
17835ffd83dbSDimitry Andric   CapExprSet ScopedReqsAndExcludes;
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   // Figure out if we're constructing an object of scoped lockable class
1786*bdd1243dSDimitry Andric   CapabilityExpr Scp;
1787*bdd1243dSDimitry Andric   if (Exp) {
1788*bdd1243dSDimitry Andric     assert(!Self);
1789*bdd1243dSDimitry Andric     const auto *TagT = Exp->getType()->getAs<TagType>();
1790*bdd1243dSDimitry Andric     if (TagT && Exp->isPRValue()) {
1791*bdd1243dSDimitry Andric       std::pair<til::LiteralPtr *, StringRef> Placeholder =
1792*bdd1243dSDimitry Andric           Analyzer->SxBuilder.createThisPlaceholder(Exp);
1793*bdd1243dSDimitry Andric       [[maybe_unused]] auto inserted =
1794*bdd1243dSDimitry Andric           ConstructedObjects.insert({Exp, Placeholder.first});
1795*bdd1243dSDimitry Andric       assert(inserted.second && "Are we visiting the same expression again?");
1796*bdd1243dSDimitry Andric       if (isa<CXXConstructExpr>(Exp))
1797*bdd1243dSDimitry Andric         Self = Placeholder.first;
1798*bdd1243dSDimitry Andric       if (TagT->getDecl()->hasAttr<ScopedLockableAttr>())
1799*bdd1243dSDimitry Andric         Scp = CapabilityExpr(Placeholder.first, Placeholder.second, false);
18000b57cec5SDimitry Andric     }
1801*bdd1243dSDimitry Andric 
1802*bdd1243dSDimitry Andric     assert(Loc.isInvalid());
1803*bdd1243dSDimitry Andric     Loc = Exp->getExprLoc();
18040b57cec5SDimitry Andric   }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   for(const Attr *At : D->attrs()) {
18070b57cec5SDimitry Andric     switch (At->getKind()) {
18080b57cec5SDimitry Andric       // When we encounter a lock function, we need to add the lock to our
18090b57cec5SDimitry Andric       // lockset.
18100b57cec5SDimitry Andric       case attr::AcquireCapability: {
18110b57cec5SDimitry Andric         const auto *A = cast<AcquireCapabilityAttr>(At);
18120b57cec5SDimitry Andric         Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
18130b57cec5SDimitry Andric                                             : ExclusiveLocksToAdd,
1814*bdd1243dSDimitry Andric                               A, Exp, D, Self);
18150b57cec5SDimitry Andric         break;
18160b57cec5SDimitry Andric       }
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric       // An assert will add a lock to the lockset, but will not generate
18190b57cec5SDimitry Andric       // a warning if it is already there, and will not generate a warning
18200b57cec5SDimitry Andric       // if it is not removed.
18210b57cec5SDimitry Andric       case attr::AssertExclusiveLock: {
18220b57cec5SDimitry Andric         const auto *A = cast<AssertExclusiveLockAttr>(At);
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric         CapExprSet AssertLocks;
1825*bdd1243dSDimitry Andric         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self);
18260b57cec5SDimitry Andric         for (const auto &AssertLock : AssertLocks)
1827fe6060f1SDimitry Andric           Analyzer->addLock(
182881ad6265SDimitry Andric               FSet, std::make_unique<LockableFactEntry>(
182981ad6265SDimitry Andric                         AssertLock, LK_Exclusive, Loc, FactEntry::Asserted));
18300b57cec5SDimitry Andric         break;
18310b57cec5SDimitry Andric       }
18320b57cec5SDimitry Andric       case attr::AssertSharedLock: {
18330b57cec5SDimitry Andric         const auto *A = cast<AssertSharedLockAttr>(At);
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric         CapExprSet AssertLocks;
1836*bdd1243dSDimitry Andric         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self);
18370b57cec5SDimitry Andric         for (const auto &AssertLock : AssertLocks)
1838fe6060f1SDimitry Andric           Analyzer->addLock(
183981ad6265SDimitry Andric               FSet, std::make_unique<LockableFactEntry>(
184081ad6265SDimitry Andric                         AssertLock, LK_Shared, Loc, FactEntry::Asserted));
18410b57cec5SDimitry Andric         break;
18420b57cec5SDimitry Andric       }
18430b57cec5SDimitry Andric 
18440b57cec5SDimitry Andric       case attr::AssertCapability: {
18450b57cec5SDimitry Andric         const auto *A = cast<AssertCapabilityAttr>(At);
18460b57cec5SDimitry Andric         CapExprSet AssertLocks;
1847*bdd1243dSDimitry Andric         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self);
18480b57cec5SDimitry Andric         for (const auto &AssertLock : AssertLocks)
184981ad6265SDimitry Andric           Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(
18500b57cec5SDimitry Andric                                       AssertLock,
185181ad6265SDimitry Andric                                       A->isShared() ? LK_Shared : LK_Exclusive,
185281ad6265SDimitry Andric                                       Loc, FactEntry::Asserted));
18530b57cec5SDimitry Andric         break;
18540b57cec5SDimitry Andric       }
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric       // When we encounter an unlock function, we need to remove unlocked
18570b57cec5SDimitry Andric       // mutexes from the lockset, and flag a warning if they are not there.
18580b57cec5SDimitry Andric       case attr::ReleaseCapability: {
18590b57cec5SDimitry Andric         const auto *A = cast<ReleaseCapabilityAttr>(At);
18600b57cec5SDimitry Andric         if (A->isGeneric())
1861*bdd1243dSDimitry Andric           Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, Self);
18620b57cec5SDimitry Andric         else if (A->isShared())
1863*bdd1243dSDimitry Andric           Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, Self);
18640b57cec5SDimitry Andric         else
1865*bdd1243dSDimitry Andric           Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, Self);
18660b57cec5SDimitry Andric         break;
18670b57cec5SDimitry Andric       }
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric       case attr::RequiresCapability: {
18700b57cec5SDimitry Andric         const auto *A = cast<RequiresCapabilityAttr>(At);
18710b57cec5SDimitry Andric         for (auto *Arg : A->args()) {
18720b57cec5SDimitry Andric           warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
1873*bdd1243dSDimitry Andric                              POK_FunctionCall, Self, Loc);
18740b57cec5SDimitry Andric           // use for adopting a lock
1875*bdd1243dSDimitry Andric           if (!Scp.shouldIgnore())
1876*bdd1243dSDimitry Andric             Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, Self);
18770b57cec5SDimitry Andric         }
18780b57cec5SDimitry Andric         break;
18790b57cec5SDimitry Andric       }
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric       case attr::LocksExcluded: {
18820b57cec5SDimitry Andric         const auto *A = cast<LocksExcludedAttr>(At);
18835ffd83dbSDimitry Andric         for (auto *Arg : A->args()) {
1884*bdd1243dSDimitry Andric           warnIfMutexHeld(D, Exp, Arg, Self, Loc);
18855ffd83dbSDimitry Andric           // use for deferring a lock
1886*bdd1243dSDimitry Andric           if (!Scp.shouldIgnore())
1887*bdd1243dSDimitry Andric             Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, Self);
18885ffd83dbSDimitry Andric         }
18890b57cec5SDimitry Andric         break;
18900b57cec5SDimitry Andric       }
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric       // Ignore attributes unrelated to thread-safety
18930b57cec5SDimitry Andric       default:
18940b57cec5SDimitry Andric         break;
18950b57cec5SDimitry Andric     }
18960b57cec5SDimitry Andric   }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric   // Remove locks first to allow lock upgrading/downgrading.
18990b57cec5SDimitry Andric   // FIXME -- should only fully remove if the attribute refers to 'this'.
19000b57cec5SDimitry Andric   bool Dtor = isa<CXXDestructorDecl>(D);
19010b57cec5SDimitry Andric   for (const auto &M : ExclusiveLocksToRemove)
190281ad6265SDimitry Andric     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive);
19030b57cec5SDimitry Andric   for (const auto &M : SharedLocksToRemove)
190481ad6265SDimitry Andric     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared);
19050b57cec5SDimitry Andric   for (const auto &M : GenericLocksToRemove)
190681ad6265SDimitry Andric     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic);
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric   // Add locks.
1909fe6060f1SDimitry Andric   FactEntry::SourceKind Source =
1910*bdd1243dSDimitry Andric       !Scp.shouldIgnore() ? FactEntry::Managed : FactEntry::Acquired;
19110b57cec5SDimitry Andric   for (const auto &M : ExclusiveLocksToAdd)
191281ad6265SDimitry Andric     Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(M, LK_Exclusive,
191381ad6265SDimitry Andric                                                                 Loc, Source));
19140b57cec5SDimitry Andric   for (const auto &M : SharedLocksToAdd)
1915fe6060f1SDimitry Andric     Analyzer->addLock(
191681ad6265SDimitry Andric         FSet, std::make_unique<LockableFactEntry>(M, LK_Shared, Loc, Source));
19170b57cec5SDimitry Andric 
1918*bdd1243dSDimitry Andric   if (!Scp.shouldIgnore()) {
19190b57cec5SDimitry Andric     // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1920*bdd1243dSDimitry Andric     auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, Loc);
19210b57cec5SDimitry Andric     for (const auto &M : ExclusiveLocksToAdd)
19225ffd83dbSDimitry Andric       ScopedEntry->addLock(M);
19230b57cec5SDimitry Andric     for (const auto &M : SharedLocksToAdd)
19245ffd83dbSDimitry Andric       ScopedEntry->addLock(M);
19255ffd83dbSDimitry Andric     for (const auto &M : ScopedReqsAndExcludes)
19265ffd83dbSDimitry Andric       ScopedEntry->addLock(M);
19270b57cec5SDimitry Andric     for (const auto &M : ExclusiveLocksToRemove)
19280b57cec5SDimitry Andric       ScopedEntry->addExclusiveUnlock(M);
19290b57cec5SDimitry Andric     for (const auto &M : SharedLocksToRemove)
19300b57cec5SDimitry Andric       ScopedEntry->addSharedUnlock(M);
193181ad6265SDimitry Andric     Analyzer->addLock(FSet, std::move(ScopedEntry));
19320b57cec5SDimitry Andric   }
19330b57cec5SDimitry Andric }
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric /// For unary operations which read and write a variable, we need to
19360b57cec5SDimitry Andric /// check whether we hold any required mutexes. Reads are checked in
19370b57cec5SDimitry Andric /// VisitCastExpr.
19380b57cec5SDimitry Andric void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
19390b57cec5SDimitry Andric   switch (UO->getOpcode()) {
19400b57cec5SDimitry Andric     case UO_PostDec:
19410b57cec5SDimitry Andric     case UO_PostInc:
19420b57cec5SDimitry Andric     case UO_PreDec:
19430b57cec5SDimitry Andric     case UO_PreInc:
19440b57cec5SDimitry Andric       checkAccess(UO->getSubExpr(), AK_Written);
19450b57cec5SDimitry Andric       break;
19460b57cec5SDimitry Andric     default:
19470b57cec5SDimitry Andric       break;
19480b57cec5SDimitry Andric   }
19490b57cec5SDimitry Andric }
19500b57cec5SDimitry Andric 
19510b57cec5SDimitry Andric /// For binary operations which assign to a variable (writes), we need to check
19520b57cec5SDimitry Andric /// whether we hold any required mutexes.
19530b57cec5SDimitry Andric /// FIXME: Deal with non-primitive types.
19540b57cec5SDimitry Andric void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
19550b57cec5SDimitry Andric   if (!BO->isAssignmentOp())
19560b57cec5SDimitry Andric     return;
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric   // adjust the context
19590b57cec5SDimitry Andric   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric   checkAccess(BO->getLHS(), AK_Written);
19620b57cec5SDimitry Andric }
19630b57cec5SDimitry Andric 
19640b57cec5SDimitry Andric /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
19650b57cec5SDimitry Andric /// need to ensure we hold any required mutexes.
19660b57cec5SDimitry Andric /// FIXME: Deal with non-primitive types.
19670b57cec5SDimitry Andric void BuildLockset::VisitCastExpr(const CastExpr *CE) {
19680b57cec5SDimitry Andric   if (CE->getCastKind() != CK_LValueToRValue)
19690b57cec5SDimitry Andric     return;
19700b57cec5SDimitry Andric   checkAccess(CE->getSubExpr(), AK_Read);
19710b57cec5SDimitry Andric }
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric void BuildLockset::examineArguments(const FunctionDecl *FD,
19740b57cec5SDimitry Andric                                     CallExpr::const_arg_iterator ArgBegin,
19750b57cec5SDimitry Andric                                     CallExpr::const_arg_iterator ArgEnd,
19760b57cec5SDimitry Andric                                     bool SkipFirstParam) {
19770b57cec5SDimitry Andric   // Currently we can't do anything if we don't know the function declaration.
19780b57cec5SDimitry Andric   if (!FD)
19790b57cec5SDimitry Andric     return;
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric   // NO_THREAD_SAFETY_ANALYSIS does double duty here.  Normally it
19820b57cec5SDimitry Andric   // only turns off checking within the body of a function, but we also
19830b57cec5SDimitry Andric   // use it to turn off checking in arguments to the function.  This
19840b57cec5SDimitry Andric   // could result in some false negatives, but the alternative is to
19850b57cec5SDimitry Andric   // create yet another attribute.
19860b57cec5SDimitry Andric   if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
19870b57cec5SDimitry Andric     return;
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric   const ArrayRef<ParmVarDecl *> Params = FD->parameters();
19900b57cec5SDimitry Andric   auto Param = Params.begin();
19910b57cec5SDimitry Andric   if (SkipFirstParam)
19920b57cec5SDimitry Andric     ++Param;
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric   // There can be default arguments, so we stop when one iterator is at end().
19950b57cec5SDimitry Andric   for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd;
19960b57cec5SDimitry Andric        ++Param, ++Arg) {
19970b57cec5SDimitry Andric     QualType Qt = (*Param)->getType();
19980b57cec5SDimitry Andric     if (Qt->isReferenceType())
19990b57cec5SDimitry Andric       checkAccess(*Arg, AK_Read, POK_PassByRef);
20000b57cec5SDimitry Andric   }
20010b57cec5SDimitry Andric }
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
20040b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
20050b57cec5SDimitry Andric     const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
20060b57cec5SDimitry Andric     // ME can be null when calling a method pointer
20070b57cec5SDimitry Andric     const CXXMethodDecl *MD = CE->getMethodDecl();
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric     if (ME && MD) {
20100b57cec5SDimitry Andric       if (ME->isArrow()) {
2011fe6060f1SDimitry Andric         // Should perhaps be AK_Written if !MD->isConst().
20120b57cec5SDimitry Andric         checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
20130b57cec5SDimitry Andric       } else {
2014fe6060f1SDimitry Andric         // Should perhaps be AK_Written if !MD->isConst().
20150b57cec5SDimitry Andric         checkAccess(CE->getImplicitObjectArgument(), AK_Read);
20160b57cec5SDimitry Andric       }
20170b57cec5SDimitry Andric     }
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric     examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
20200b57cec5SDimitry Andric   } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
202181ad6265SDimitry Andric     OverloadedOperatorKind OEop = OE->getOperator();
20220b57cec5SDimitry Andric     switch (OEop) {
202381ad6265SDimitry Andric       case OO_Equal:
202481ad6265SDimitry Andric       case OO_PlusEqual:
202581ad6265SDimitry Andric       case OO_MinusEqual:
202681ad6265SDimitry Andric       case OO_StarEqual:
202781ad6265SDimitry Andric       case OO_SlashEqual:
202881ad6265SDimitry Andric       case OO_PercentEqual:
202981ad6265SDimitry Andric       case OO_CaretEqual:
203081ad6265SDimitry Andric       case OO_AmpEqual:
203181ad6265SDimitry Andric       case OO_PipeEqual:
203281ad6265SDimitry Andric       case OO_LessLessEqual:
203381ad6265SDimitry Andric       case OO_GreaterGreaterEqual:
203481ad6265SDimitry Andric         checkAccess(OE->getArg(1), AK_Read);
2035*bdd1243dSDimitry Andric         [[fallthrough]];
203681ad6265SDimitry Andric       case OO_PlusPlus:
203781ad6265SDimitry Andric       case OO_MinusMinus:
203881ad6265SDimitry Andric         checkAccess(OE->getArg(0), AK_Written);
20390b57cec5SDimitry Andric         break;
20400b57cec5SDimitry Andric       case OO_Star:
204181ad6265SDimitry Andric       case OO_ArrowStar:
20420b57cec5SDimitry Andric       case OO_Arrow:
20430b57cec5SDimitry Andric       case OO_Subscript:
20440b57cec5SDimitry Andric         if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
20450b57cec5SDimitry Andric           // Grrr.  operator* can be multiplication...
20460b57cec5SDimitry Andric           checkPtAccess(OE->getArg(0), AK_Read);
20470b57cec5SDimitry Andric         }
2048*bdd1243dSDimitry Andric         [[fallthrough]];
20490b57cec5SDimitry Andric       default: {
20500b57cec5SDimitry Andric         // TODO: get rid of this, and rely on pass-by-ref instead.
20510b57cec5SDimitry Andric         const Expr *Obj = OE->getArg(0);
20520b57cec5SDimitry Andric         checkAccess(Obj, AK_Read);
20530b57cec5SDimitry Andric         // Check the remaining arguments. For method operators, the first
20540b57cec5SDimitry Andric         // argument is the implicit self argument, and doesn't appear in the
20550b57cec5SDimitry Andric         // FunctionDecl, but for non-methods it does.
20560b57cec5SDimitry Andric         const FunctionDecl *FD = OE->getDirectCallee();
20570b57cec5SDimitry Andric         examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
20580b57cec5SDimitry Andric                          /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
20590b57cec5SDimitry Andric         break;
20600b57cec5SDimitry Andric       }
20610b57cec5SDimitry Andric     }
20620b57cec5SDimitry Andric   } else {
20630b57cec5SDimitry Andric     examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
20640b57cec5SDimitry Andric   }
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
20670b57cec5SDimitry Andric   if(!D || !D->hasAttrs())
20680b57cec5SDimitry Andric     return;
20690b57cec5SDimitry Andric   handleCall(Exp, D);
20700b57cec5SDimitry Andric }
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
20730b57cec5SDimitry Andric   const CXXConstructorDecl *D = Exp->getConstructor();
20740b57cec5SDimitry Andric   if (D && D->isCopyConstructor()) {
20750b57cec5SDimitry Andric     const Expr* Source = Exp->getArg(0);
20760b57cec5SDimitry Andric     checkAccess(Source, AK_Read);
20770b57cec5SDimitry Andric   } else {
20780b57cec5SDimitry Andric     examineArguments(D, Exp->arg_begin(), Exp->arg_end());
20790b57cec5SDimitry Andric   }
2080*bdd1243dSDimitry Andric   if (D && D->hasAttrs())
2081*bdd1243dSDimitry Andric     handleCall(Exp, D);
20820b57cec5SDimitry Andric }
20830b57cec5SDimitry Andric 
2084*bdd1243dSDimitry Andric static const Expr *UnpackConstruction(const Expr *E) {
2085*bdd1243dSDimitry Andric   if (auto *CE = dyn_cast<CastExpr>(E))
2086*bdd1243dSDimitry Andric     if (CE->getCastKind() == CK_NoOp)
2087*bdd1243dSDimitry Andric       E = CE->getSubExpr()->IgnoreParens();
2088*bdd1243dSDimitry Andric   if (auto *CE = dyn_cast<CastExpr>(E))
2089*bdd1243dSDimitry Andric     if (CE->getCastKind() == CK_ConstructorConversion ||
2090*bdd1243dSDimitry Andric         CE->getCastKind() == CK_UserDefinedConversion)
2091*bdd1243dSDimitry Andric       E = CE->getSubExpr();
2092*bdd1243dSDimitry Andric   if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2093*bdd1243dSDimitry Andric     E = BTE->getSubExpr();
2094*bdd1243dSDimitry Andric   return E;
20950b57cec5SDimitry Andric }
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
20980b57cec5SDimitry Andric   // adjust the context
20990b57cec5SDimitry Andric   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric   for (auto *D : S->getDeclGroup()) {
21020b57cec5SDimitry Andric     if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2103*bdd1243dSDimitry Andric       const Expr *E = VD->getInit();
21040b57cec5SDimitry Andric       if (!E)
21050b57cec5SDimitry Andric         continue;
21060b57cec5SDimitry Andric       E = E->IgnoreParens();
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric       // handle constructors that involve temporaries
21090b57cec5SDimitry Andric       if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
21105ffd83dbSDimitry Andric         E = EWC->getSubExpr()->IgnoreParens();
2111*bdd1243dSDimitry Andric       E = UnpackConstruction(E);
21120b57cec5SDimitry Andric 
2113*bdd1243dSDimitry Andric       if (auto Object = ConstructedObjects.find(E);
2114*bdd1243dSDimitry Andric           Object != ConstructedObjects.end()) {
2115*bdd1243dSDimitry Andric         Object->second->setClangDecl(VD);
2116*bdd1243dSDimitry Andric         ConstructedObjects.erase(Object);
21170b57cec5SDimitry Andric       }
21180b57cec5SDimitry Andric     }
21190b57cec5SDimitry Andric   }
21200b57cec5SDimitry Andric }
21210b57cec5SDimitry Andric 
2122*bdd1243dSDimitry Andric void BuildLockset::VisitMaterializeTemporaryExpr(
2123*bdd1243dSDimitry Andric     const MaterializeTemporaryExpr *Exp) {
2124*bdd1243dSDimitry Andric   if (const ValueDecl *ExtD = Exp->getExtendingDecl()) {
2125*bdd1243dSDimitry Andric     if (auto Object =
2126*bdd1243dSDimitry Andric             ConstructedObjects.find(UnpackConstruction(Exp->getSubExpr()));
2127*bdd1243dSDimitry Andric         Object != ConstructedObjects.end()) {
2128*bdd1243dSDimitry Andric       Object->second->setClangDecl(ExtD);
2129*bdd1243dSDimitry Andric       ConstructedObjects.erase(Object);
2130*bdd1243dSDimitry Andric     }
2131*bdd1243dSDimitry Andric   }
2132*bdd1243dSDimitry Andric }
2133*bdd1243dSDimitry Andric 
213428a41182SDimitry Andric /// Given two facts merging on a join point, possibly warn and decide whether to
213528a41182SDimitry Andric /// keep or replace.
2136fe6060f1SDimitry Andric ///
213728a41182SDimitry Andric /// \param CanModify Whether we can replace \p A by \p B.
213828a41182SDimitry Andric /// \return  false if we should keep \p A, true if we should take \p B.
213928a41182SDimitry Andric bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B,
214028a41182SDimitry Andric                                 bool CanModify) {
2141fe6060f1SDimitry Andric   if (A.kind() != B.kind()) {
2142fe6060f1SDimitry Andric     // For managed capabilities, the destructor should unlock in the right mode
2143fe6060f1SDimitry Andric     // anyway. For asserted capabilities no unlocking is needed.
2144fe6060f1SDimitry Andric     if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) {
214528a41182SDimitry Andric       // The shared capability subsumes the exclusive capability, if possible.
214628a41182SDimitry Andric       bool ShouldTakeB = B.kind() == LK_Shared;
214728a41182SDimitry Andric       if (CanModify || !ShouldTakeB)
214828a41182SDimitry Andric         return ShouldTakeB;
214928a41182SDimitry Andric     }
215081ad6265SDimitry Andric     Handler.handleExclusiveAndShared(B.getKind(), B.toString(), B.loc(),
215181ad6265SDimitry Andric                                      A.loc());
2152fe6060f1SDimitry Andric     // Take the exclusive capability to reduce further warnings.
215328a41182SDimitry Andric     return CanModify && B.kind() == LK_Exclusive;
2154fe6060f1SDimitry Andric   } else {
2155fe6060f1SDimitry Andric     // The non-asserted capability is the one we want to track.
215628a41182SDimitry Andric     return CanModify && A.asserted() && !B.asserted();
2157fe6060f1SDimitry Andric   }
2158fe6060f1SDimitry Andric }
2159fe6060f1SDimitry Andric 
21600b57cec5SDimitry Andric /// Compute the intersection of two locksets and issue warnings for any
21610b57cec5SDimitry Andric /// locks in the symmetric difference.
21620b57cec5SDimitry Andric ///
21630b57cec5SDimitry Andric /// This function is used at a merge point in the CFG when comparing the lockset
21640b57cec5SDimitry Andric /// of each branch being merged. For example, given the following sequence:
21650b57cec5SDimitry Andric /// A; if () then B; else C; D; we need to check that the lockset after B and C
21660b57cec5SDimitry Andric /// are the same. In the event of a difference, we use the intersection of these
21670b57cec5SDimitry Andric /// two locksets at the start of D.
21680b57cec5SDimitry Andric ///
2169fe6060f1SDimitry Andric /// \param EntrySet A lockset for entry into a (possibly new) block.
2170fe6060f1SDimitry Andric /// \param ExitSet The lockset on exiting a preceding block.
21710b57cec5SDimitry Andric /// \param JoinLoc The location of the join point for error reporting
2172fe6060f1SDimitry Andric /// \param EntryLEK The warning if a mutex is missing from \p EntrySet.
2173fe6060f1SDimitry Andric /// \param ExitLEK The warning if a mutex is missing from \p ExitSet.
2174fe6060f1SDimitry Andric void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &EntrySet,
2175fe6060f1SDimitry Andric                                             const FactSet &ExitSet,
21760b57cec5SDimitry Andric                                             SourceLocation JoinLoc,
2177fe6060f1SDimitry Andric                                             LockErrorKind EntryLEK,
2178fe6060f1SDimitry Andric                                             LockErrorKind ExitLEK) {
2179fe6060f1SDimitry Andric   FactSet EntrySetOrig = EntrySet;
21800b57cec5SDimitry Andric 
2181fe6060f1SDimitry Andric   // Find locks in ExitSet that conflict or are not in EntrySet, and warn.
2182fe6060f1SDimitry Andric   for (const auto &Fact : ExitSet) {
2183fe6060f1SDimitry Andric     const FactEntry &ExitFact = FactMan[Fact];
21840b57cec5SDimitry Andric 
2185fe6060f1SDimitry Andric     FactSet::iterator EntryIt = EntrySet.findLockIter(FactMan, ExitFact);
2186fe6060f1SDimitry Andric     if (EntryIt != EntrySet.end()) {
218728a41182SDimitry Andric       if (join(FactMan[*EntryIt], ExitFact,
218828a41182SDimitry Andric                EntryLEK != LEK_LockedSomeLoopIterations))
2189fe6060f1SDimitry Andric         *EntryIt = Fact;
2190fe6060f1SDimitry Andric     } else if (!ExitFact.managed()) {
2191fe6060f1SDimitry Andric       ExitFact.handleRemovalFromIntersection(ExitSet, FactMan, JoinLoc,
2192fe6060f1SDimitry Andric                                              EntryLEK, Handler);
21930b57cec5SDimitry Andric     }
21940b57cec5SDimitry Andric   }
21950b57cec5SDimitry Andric 
2196fe6060f1SDimitry Andric   // Find locks in EntrySet that are not in ExitSet, and remove them.
2197fe6060f1SDimitry Andric   for (const auto &Fact : EntrySetOrig) {
2198fe6060f1SDimitry Andric     const FactEntry *EntryFact = &FactMan[Fact];
2199fe6060f1SDimitry Andric     const FactEntry *ExitFact = ExitSet.findLock(FactMan, *EntryFact);
22000b57cec5SDimitry Andric 
2201fe6060f1SDimitry Andric     if (!ExitFact) {
2202fe6060f1SDimitry Andric       if (!EntryFact->managed() || ExitLEK == LEK_LockedSomeLoopIterations)
2203fe6060f1SDimitry Andric         EntryFact->handleRemovalFromIntersection(EntrySetOrig, FactMan, JoinLoc,
2204fe6060f1SDimitry Andric                                                  ExitLEK, Handler);
2205fe6060f1SDimitry Andric       if (ExitLEK == LEK_LockedSomePredecessors)
2206fe6060f1SDimitry Andric         EntrySet.removeLock(FactMan, *EntryFact);
22070b57cec5SDimitry Andric     }
22080b57cec5SDimitry Andric   }
22090b57cec5SDimitry Andric }
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric // Return true if block B never continues to its successors.
22120b57cec5SDimitry Andric static bool neverReturns(const CFGBlock *B) {
22130b57cec5SDimitry Andric   if (B->hasNoReturnElement())
22140b57cec5SDimitry Andric     return true;
22150b57cec5SDimitry Andric   if (B->empty())
22160b57cec5SDimitry Andric     return false;
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric   CFGElement Last = B->back();
2219*bdd1243dSDimitry Andric   if (std::optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
22200b57cec5SDimitry Andric     if (isa<CXXThrowExpr>(S->getStmt()))
22210b57cec5SDimitry Andric       return true;
22220b57cec5SDimitry Andric   }
22230b57cec5SDimitry Andric   return false;
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric /// Check a function's CFG for thread-safety violations.
22270b57cec5SDimitry Andric ///
22280b57cec5SDimitry Andric /// We traverse the blocks in the CFG, compute the set of mutexes that are held
22290b57cec5SDimitry Andric /// at the end of each block, and issue warnings for thread safety violations.
22300b57cec5SDimitry Andric /// Each block in the CFG is traversed exactly once.
22310b57cec5SDimitry Andric void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
22320b57cec5SDimitry Andric   // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
22330b57cec5SDimitry Andric   // For now, we just use the walker to set things up.
22340b57cec5SDimitry Andric   threadSafety::CFGWalker walker;
22350b57cec5SDimitry Andric   if (!walker.init(AC))
22360b57cec5SDimitry Andric     return;
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric   // AC.dumpCFG(true);
22390b57cec5SDimitry Andric   // threadSafety::printSCFG(walker);
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric   CFG *CFGraph = walker.getGraph();
22420b57cec5SDimitry Andric   const NamedDecl *D = walker.getDecl();
22430b57cec5SDimitry Andric   const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
22440b57cec5SDimitry Andric   CurrentMethod = dyn_cast<CXXMethodDecl>(D);
22450b57cec5SDimitry Andric 
22460b57cec5SDimitry Andric   if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
22470b57cec5SDimitry Andric     return;
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   // FIXME: Do something a bit more intelligent inside constructor and
22500b57cec5SDimitry Andric   // destructor code.  Constructors and destructors must assume unique access
22510b57cec5SDimitry Andric   // to 'this', so checks on member variable access is disabled, but we should
22520b57cec5SDimitry Andric   // still enable checks on other objects.
22530b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D))
22540b57cec5SDimitry Andric     return;  // Don't check inside constructors.
22550b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(D))
22560b57cec5SDimitry Andric     return;  // Don't check inside destructors.
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric   Handler.enterFunction(CurrentFunction);
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric   BlockInfo.resize(CFGraph->getNumBlockIDs(),
22610b57cec5SDimitry Andric     CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   // We need to explore the CFG via a "topological" ordering.
22640b57cec5SDimitry Andric   // That way, we will be guaranteed to have information about required
22650b57cec5SDimitry Andric   // predecessor locksets when exploring a new block.
22660b57cec5SDimitry Andric   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
22670b57cec5SDimitry Andric   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   // Mark entry block as reachable
22700b57cec5SDimitry Andric   BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric   // Compute SSA names for local variables
22730b57cec5SDimitry Andric   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric   // Fill in source locations for all CFGBlocks.
22760b57cec5SDimitry Andric   findBlockLocations(CFGraph, SortedGraph, BlockInfo);
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric   CapExprSet ExclusiveLocksAcquired;
22790b57cec5SDimitry Andric   CapExprSet SharedLocksAcquired;
22800b57cec5SDimitry Andric   CapExprSet LocksReleased;
22810b57cec5SDimitry Andric 
22820b57cec5SDimitry Andric   // Add locks from exclusive_locks_required and shared_locks_required
22830b57cec5SDimitry Andric   // to initial lockset. Also turn off checking for lock and unlock functions.
22840b57cec5SDimitry Andric   // FIXME: is there a more intelligent way to check lock/unlock functions?
22850b57cec5SDimitry Andric   if (!SortedGraph->empty() && D->hasAttrs()) {
22860b57cec5SDimitry Andric     const CFGBlock *FirstBlock = *SortedGraph->begin();
22870b57cec5SDimitry Andric     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric     CapExprSet ExclusiveLocksToAdd;
22900b57cec5SDimitry Andric     CapExprSet SharedLocksToAdd;
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric     SourceLocation Loc = D->getLocation();
22930b57cec5SDimitry Andric     for (const auto *Attr : D->attrs()) {
22940b57cec5SDimitry Andric       Loc = Attr->getLocation();
22950b57cec5SDimitry Andric       if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
22960b57cec5SDimitry Andric         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
22970b57cec5SDimitry Andric                     nullptr, D);
22980b57cec5SDimitry Andric       } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
22990b57cec5SDimitry Andric         // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
23000b57cec5SDimitry Andric         // We must ignore such methods.
23010b57cec5SDimitry Andric         if (A->args_size() == 0)
23020b57cec5SDimitry Andric           return;
23030b57cec5SDimitry Andric         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
23040b57cec5SDimitry Andric                     nullptr, D);
23050b57cec5SDimitry Andric         getMutexIDs(LocksReleased, A, nullptr, D);
23060b57cec5SDimitry Andric       } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
23070b57cec5SDimitry Andric         if (A->args_size() == 0)
23080b57cec5SDimitry Andric           return;
23090b57cec5SDimitry Andric         getMutexIDs(A->isShared() ? SharedLocksAcquired
23100b57cec5SDimitry Andric                                   : ExclusiveLocksAcquired,
23110b57cec5SDimitry Andric                     A, nullptr, D);
23120b57cec5SDimitry Andric       } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
23130b57cec5SDimitry Andric         // Don't try to check trylock functions for now.
23140b57cec5SDimitry Andric         return;
23150b57cec5SDimitry Andric       } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
23160b57cec5SDimitry Andric         // Don't try to check trylock functions for now.
23170b57cec5SDimitry Andric         return;
23180b57cec5SDimitry Andric       } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
23190b57cec5SDimitry Andric         // Don't try to check trylock functions for now.
23200b57cec5SDimitry Andric         return;
23210b57cec5SDimitry Andric       }
23220b57cec5SDimitry Andric     }
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric     // FIXME -- Loc can be wrong here.
23250b57cec5SDimitry Andric     for (const auto &Mu : ExclusiveLocksToAdd) {
2326fe6060f1SDimitry Andric       auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc,
2327fe6060f1SDimitry Andric                                                        FactEntry::Declared);
232881ad6265SDimitry Andric       addLock(InitialLockset, std::move(Entry), true);
23290b57cec5SDimitry Andric     }
23300b57cec5SDimitry Andric     for (const auto &Mu : SharedLocksToAdd) {
2331fe6060f1SDimitry Andric       auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc,
2332fe6060f1SDimitry Andric                                                        FactEntry::Declared);
233381ad6265SDimitry Andric       addLock(InitialLockset, std::move(Entry), true);
23340b57cec5SDimitry Andric     }
23350b57cec5SDimitry Andric   }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   for (const auto *CurrBlock : *SortedGraph) {
23380b57cec5SDimitry Andric     unsigned CurrBlockID = CurrBlock->getBlockID();
23390b57cec5SDimitry Andric     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric     // Use the default initial lockset in case there are no predecessors.
23420b57cec5SDimitry Andric     VisitedBlocks.insert(CurrBlock);
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric     // Iterate through the predecessor blocks and warn if the lockset for all
23450b57cec5SDimitry Andric     // predecessors is not the same. We take the entry lockset of the current
23460b57cec5SDimitry Andric     // block to be the intersection of all previous locksets.
23470b57cec5SDimitry Andric     // FIXME: By keeping the intersection, we may output more errors in future
23480b57cec5SDimitry Andric     // for a lock which is not in the intersection, but was in the union. We
23490b57cec5SDimitry Andric     // may want to also keep the union in future. As an example, let's say
23500b57cec5SDimitry Andric     // the intersection contains Mutex L, and the union contains L and M.
23510b57cec5SDimitry Andric     // Later we unlock M. At this point, we would output an error because we
23520b57cec5SDimitry Andric     // never locked M; although the real error is probably that we forgot to
23530b57cec5SDimitry Andric     // lock M on all code paths. Conversely, let's say that later we lock M.
23540b57cec5SDimitry Andric     // In this case, we should compare against the intersection instead of the
23550b57cec5SDimitry Andric     // union because the real error is probably that we forgot to unlock M on
23560b57cec5SDimitry Andric     // all code paths.
23570b57cec5SDimitry Andric     bool LocksetInitialized = false;
23580b57cec5SDimitry Andric     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
23590b57cec5SDimitry Andric          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
23600b57cec5SDimitry Andric       // if *PI -> CurrBlock is a back edge
23610b57cec5SDimitry Andric       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
23620b57cec5SDimitry Andric         continue;
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric       unsigned PrevBlockID = (*PI)->getBlockID();
23650b57cec5SDimitry Andric       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric       // Ignore edges from blocks that can't return.
23680b57cec5SDimitry Andric       if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
23690b57cec5SDimitry Andric         continue;
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric       // Okay, we can reach this block from the entry.
23720b57cec5SDimitry Andric       CurrBlockInfo->Reachable = true;
23730b57cec5SDimitry Andric 
23740b57cec5SDimitry Andric       FactSet PrevLockset;
23750b57cec5SDimitry Andric       getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric       if (!LocksetInitialized) {
23780b57cec5SDimitry Andric         CurrBlockInfo->EntrySet = PrevLockset;
23790b57cec5SDimitry Andric         LocksetInitialized = true;
23800b57cec5SDimitry Andric       } else {
2381349cc55cSDimitry Andric         // Surprisingly 'continue' doesn't always produce back edges, because
2382349cc55cSDimitry Andric         // the CFG has empty "transition" blocks where they meet with the end
2383349cc55cSDimitry Andric         // of the regular loop body. We still want to diagnose them as loop.
2384349cc55cSDimitry Andric         intersectAndWarn(
2385349cc55cSDimitry Andric             CurrBlockInfo->EntrySet, PrevLockset, CurrBlockInfo->EntryLoc,
2386349cc55cSDimitry Andric             isa_and_nonnull<ContinueStmt>((*PI)->getTerminatorStmt())
2387349cc55cSDimitry Andric                 ? LEK_LockedSomeLoopIterations
2388349cc55cSDimitry Andric                 : LEK_LockedSomePredecessors);
23890b57cec5SDimitry Andric       }
23900b57cec5SDimitry Andric     }
23910b57cec5SDimitry Andric 
23920b57cec5SDimitry Andric     // Skip rest of block if it's not reachable.
23930b57cec5SDimitry Andric     if (!CurrBlockInfo->Reachable)
23940b57cec5SDimitry Andric       continue;
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric     BuildLockset LocksetBuilder(this, *CurrBlockInfo);
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric     // Visit all the statements in the basic block.
23990b57cec5SDimitry Andric     for (const auto &BI : *CurrBlock) {
24000b57cec5SDimitry Andric       switch (BI.getKind()) {
24010b57cec5SDimitry Andric         case CFGElement::Statement: {
24020b57cec5SDimitry Andric           CFGStmt CS = BI.castAs<CFGStmt>();
24030b57cec5SDimitry Andric           LocksetBuilder.Visit(CS.getStmt());
24040b57cec5SDimitry Andric           break;
24050b57cec5SDimitry Andric         }
2406*bdd1243dSDimitry Andric         // Ignore BaseDtor and MemberDtor for now.
24070b57cec5SDimitry Andric         case CFGElement::AutomaticObjectDtor: {
24080b57cec5SDimitry Andric           CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
24090b57cec5SDimitry Andric           const auto *DD = AD.getDestructorDecl(AC.getASTContext());
24100b57cec5SDimitry Andric           if (!DD->hasAttrs())
24110b57cec5SDimitry Andric             break;
24120b57cec5SDimitry Andric 
2413*bdd1243dSDimitry Andric           LocksetBuilder.handleCall(nullptr, DD,
2414*bdd1243dSDimitry Andric                                     SxBuilder.createVariable(AD.getVarDecl()),
24150b57cec5SDimitry Andric                                     AD.getTriggerStmt()->getEndLoc());
2416*bdd1243dSDimitry Andric           break;
2417*bdd1243dSDimitry Andric         }
2418*bdd1243dSDimitry Andric         case CFGElement::TemporaryDtor: {
2419*bdd1243dSDimitry Andric           auto TD = BI.castAs<CFGTemporaryDtor>();
2420*bdd1243dSDimitry Andric 
2421*bdd1243dSDimitry Andric           // Clean up constructed object even if there are no attributes to
2422*bdd1243dSDimitry Andric           // keep the number of objects in limbo as small as possible.
2423*bdd1243dSDimitry Andric           if (auto Object = LocksetBuilder.ConstructedObjects.find(
2424*bdd1243dSDimitry Andric                   TD.getBindTemporaryExpr()->getSubExpr());
2425*bdd1243dSDimitry Andric               Object != LocksetBuilder.ConstructedObjects.end()) {
2426*bdd1243dSDimitry Andric             const auto *DD = TD.getDestructorDecl(AC.getASTContext());
2427*bdd1243dSDimitry Andric             if (DD->hasAttrs())
2428*bdd1243dSDimitry Andric               // TODO: the location here isn't quite correct.
2429*bdd1243dSDimitry Andric               LocksetBuilder.handleCall(nullptr, DD, Object->second,
2430*bdd1243dSDimitry Andric                                         TD.getBindTemporaryExpr()->getEndLoc());
2431*bdd1243dSDimitry Andric             LocksetBuilder.ConstructedObjects.erase(Object);
2432*bdd1243dSDimitry Andric           }
24330b57cec5SDimitry Andric           break;
24340b57cec5SDimitry Andric         }
24350b57cec5SDimitry Andric         default:
24360b57cec5SDimitry Andric           break;
24370b57cec5SDimitry Andric       }
24380b57cec5SDimitry Andric     }
24390b57cec5SDimitry Andric     CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric     // For every back edge from CurrBlock (the end of the loop) to another block
24420b57cec5SDimitry Andric     // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
24430b57cec5SDimitry Andric     // the one held at the beginning of FirstLoopBlock. We can look up the
24440b57cec5SDimitry Andric     // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
24450b57cec5SDimitry Andric     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
24460b57cec5SDimitry Andric          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
24470b57cec5SDimitry Andric       // if CurrBlock -> *SI is *not* a back edge
24480b57cec5SDimitry Andric       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
24490b57cec5SDimitry Andric         continue;
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric       CFGBlock *FirstLoopBlock = *SI;
24520b57cec5SDimitry Andric       CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
24530b57cec5SDimitry Andric       CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2454fe6060f1SDimitry Andric       intersectAndWarn(PreLoop->EntrySet, LoopEnd->ExitSet, PreLoop->EntryLoc,
2455fe6060f1SDimitry Andric                        LEK_LockedSomeLoopIterations);
24560b57cec5SDimitry Andric     }
24570b57cec5SDimitry Andric   }
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric   CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
24600b57cec5SDimitry Andric   CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   // Skip the final check if the exit block is unreachable.
24630b57cec5SDimitry Andric   if (!Final->Reachable)
24640b57cec5SDimitry Andric     return;
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   // By default, we expect all locks held on entry to be held on exit.
24670b57cec5SDimitry Andric   FactSet ExpectedExitSet = Initial->EntrySet;
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric   // Adjust the expected exit set by adding or removing locks, as declared
24700b57cec5SDimitry Andric   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
24710b57cec5SDimitry Andric   // issue the appropriate warning.
24720b57cec5SDimitry Andric   // FIXME: the location here is not quite right.
24730b57cec5SDimitry Andric   for (const auto &Lock : ExclusiveLocksAcquired)
2474a7dea167SDimitry Andric     ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
24750b57cec5SDimitry Andric                                          Lock, LK_Exclusive, D->getLocation()));
24760b57cec5SDimitry Andric   for (const auto &Lock : SharedLocksAcquired)
2477a7dea167SDimitry Andric     ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
24780b57cec5SDimitry Andric                                          Lock, LK_Shared, D->getLocation()));
24790b57cec5SDimitry Andric   for (const auto &Lock : LocksReleased)
24800b57cec5SDimitry Andric     ExpectedExitSet.removeLock(FactMan, Lock);
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric   // FIXME: Should we call this function for all blocks which exit the function?
2483fe6060f1SDimitry Andric   intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
2484fe6060f1SDimitry Andric                    LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction);
24850b57cec5SDimitry Andric 
24860b57cec5SDimitry Andric   Handler.leaveFunction(CurrentFunction);
24870b57cec5SDimitry Andric }
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric /// Check a function's CFG for thread-safety violations.
24900b57cec5SDimitry Andric ///
24910b57cec5SDimitry Andric /// We traverse the blocks in the CFG, compute the set of mutexes that are held
24920b57cec5SDimitry Andric /// at the end of each block, and issue warnings for thread safety violations.
24930b57cec5SDimitry Andric /// Each block in the CFG is traversed exactly once.
24940b57cec5SDimitry Andric void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
24950b57cec5SDimitry Andric                                            ThreadSafetyHandler &Handler,
24960b57cec5SDimitry Andric                                            BeforeSet **BSet) {
24970b57cec5SDimitry Andric   if (!*BSet)
24980b57cec5SDimitry Andric     *BSet = new BeforeSet;
24990b57cec5SDimitry Andric   ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
25000b57cec5SDimitry Andric   Analyzer.runAnalysis(AC);
25010b57cec5SDimitry Andric }
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric /// Helper function that returns a LockKind required for the given level
25060b57cec5SDimitry Andric /// of access.
25070b57cec5SDimitry Andric LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
25080b57cec5SDimitry Andric   switch (AK) {
25090b57cec5SDimitry Andric     case AK_Read :
25100b57cec5SDimitry Andric       return LK_Shared;
25110b57cec5SDimitry Andric     case AK_Written :
25120b57cec5SDimitry Andric       return LK_Exclusive;
25130b57cec5SDimitry Andric   }
25140b57cec5SDimitry Andric   llvm_unreachable("Unknown AccessKind");
25150b57cec5SDimitry Andric }
2516