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/Optional.h" 440b57cec5SDimitry Andric #include "llvm/ADT/PointerIntPair.h" 450b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 460b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 470b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 480b57cec5SDimitry Andric #include "llvm/Support/Allocator.h" 490b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 500b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 510b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 520b57cec5SDimitry Andric #include <algorithm> 530b57cec5SDimitry Andric #include <cassert> 540b57cec5SDimitry Andric #include <functional> 550b57cec5SDimitry Andric #include <iterator> 560b57cec5SDimitry Andric #include <memory> 570b57cec5SDimitry Andric #include <string> 580b57cec5SDimitry Andric #include <type_traits> 590b57cec5SDimitry Andric #include <utility> 600b57cec5SDimitry Andric #include <vector> 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric using namespace clang; 630b57cec5SDimitry Andric using namespace threadSafety; 640b57cec5SDimitry Andric 650b57cec5SDimitry Andric // Key method definition 660b57cec5SDimitry Andric ThreadSafetyHandler::~ThreadSafetyHandler() = default; 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric /// Issue a warning about an invalid lock expression 690b57cec5SDimitry Andric static void warnInvalidLock(ThreadSafetyHandler &Handler, 700b57cec5SDimitry Andric const Expr *MutexExp, const NamedDecl *D, 710b57cec5SDimitry Andric const Expr *DeclExp, StringRef Kind) { 720b57cec5SDimitry Andric SourceLocation Loc; 730b57cec5SDimitry Andric if (DeclExp) 740b57cec5SDimitry Andric Loc = DeclExp->getExprLoc(); 750b57cec5SDimitry Andric 760b57cec5SDimitry Andric // FIXME: add a note about the attribute location in MutexExp or D 770b57cec5SDimitry Andric if (Loc.isValid()) 780b57cec5SDimitry Andric Handler.handleInvalidLockExp(Kind, Loc); 790b57cec5SDimitry Andric } 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric namespace { 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric /// A set of CapabilityExpr objects, which are compiled from thread safety 840b57cec5SDimitry Andric /// attributes on a function. 850b57cec5SDimitry Andric class CapExprSet : public SmallVector<CapabilityExpr, 4> { 860b57cec5SDimitry Andric public: 870b57cec5SDimitry Andric /// Push M onto list, but discard duplicates. 880b57cec5SDimitry Andric void push_back_nodup(const CapabilityExpr &CapE) { 890b57cec5SDimitry Andric iterator It = std::find_if(begin(), end(), 900b57cec5SDimitry Andric [=](const CapabilityExpr &CapE2) { 910b57cec5SDimitry Andric return CapE.equals(CapE2); 920b57cec5SDimitry Andric }); 930b57cec5SDimitry Andric if (It == end()) 940b57cec5SDimitry Andric push_back(CapE); 950b57cec5SDimitry Andric } 960b57cec5SDimitry Andric }; 970b57cec5SDimitry Andric 980b57cec5SDimitry Andric class FactManager; 990b57cec5SDimitry Andric class FactSet; 1000b57cec5SDimitry Andric 1010b57cec5SDimitry Andric /// This is a helper class that stores a fact that is known at a 1020b57cec5SDimitry Andric /// particular point in program execution. Currently, a fact is a capability, 1030b57cec5SDimitry Andric /// along with additional information, such as where it was acquired, whether 1040b57cec5SDimitry Andric /// it is exclusive or shared, etc. 1050b57cec5SDimitry Andric /// 1060b57cec5SDimitry Andric /// FIXME: this analysis does not currently support re-entrant locking. 1070b57cec5SDimitry Andric class FactEntry : public CapabilityExpr { 108fe6060f1SDimitry Andric public: 109fe6060f1SDimitry Andric /// Where a fact comes from. 110fe6060f1SDimitry Andric enum SourceKind { 111fe6060f1SDimitry Andric Acquired, ///< The fact has been directly acquired. 112fe6060f1SDimitry Andric Asserted, ///< The fact has been asserted to be held. 113fe6060f1SDimitry Andric Declared, ///< The fact is assumed to be held by callers. 114fe6060f1SDimitry Andric Managed, ///< The fact has been acquired through a scoped capability. 115fe6060f1SDimitry Andric }; 116fe6060f1SDimitry Andric 1170b57cec5SDimitry Andric private: 1180b57cec5SDimitry Andric /// Exclusive or shared. 119fe6060f1SDimitry Andric LockKind LKind : 8; 120fe6060f1SDimitry Andric 121fe6060f1SDimitry Andric // How it was acquired. 122fe6060f1SDimitry Andric SourceKind Source : 8; 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric /// Where it was acquired. 1250b57cec5SDimitry Andric SourceLocation AcquireLoc; 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric public: 1280b57cec5SDimitry Andric FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc, 129fe6060f1SDimitry Andric SourceKind Src) 130fe6060f1SDimitry Andric : CapabilityExpr(CE), LKind(LK), Source(Src), AcquireLoc(Loc) {} 1310b57cec5SDimitry Andric virtual ~FactEntry() = default; 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric LockKind kind() const { return LKind; } 1340b57cec5SDimitry Andric SourceLocation loc() const { return AcquireLoc; } 1350b57cec5SDimitry Andric 136fe6060f1SDimitry Andric bool asserted() const { return Source == Asserted; } 137fe6060f1SDimitry Andric bool declared() const { return Source == Declared; } 138fe6060f1SDimitry Andric bool managed() const { return Source == Managed; } 1390b57cec5SDimitry Andric 1400b57cec5SDimitry Andric virtual void 1410b57cec5SDimitry Andric handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 1420b57cec5SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK, 1430b57cec5SDimitry Andric ThreadSafetyHandler &Handler) const = 0; 1440b57cec5SDimitry Andric virtual void handleLock(FactSet &FSet, FactManager &FactMan, 1450b57cec5SDimitry Andric const FactEntry &entry, ThreadSafetyHandler &Handler, 1460b57cec5SDimitry Andric StringRef DiagKind) const = 0; 1470b57cec5SDimitry Andric virtual void handleUnlock(FactSet &FSet, FactManager &FactMan, 1480b57cec5SDimitry Andric const CapabilityExpr &Cp, SourceLocation UnlockLoc, 1490b57cec5SDimitry Andric bool FullyRemove, ThreadSafetyHandler &Handler, 1500b57cec5SDimitry Andric StringRef DiagKind) const = 0; 1510b57cec5SDimitry Andric 1520b57cec5SDimitry Andric // Return true if LKind >= LK, where exclusive > shared 1530b57cec5SDimitry Andric bool isAtLeast(LockKind LK) const { 1540b57cec5SDimitry Andric return (LKind == LK_Exclusive) || (LK == LK_Shared); 1550b57cec5SDimitry Andric } 1560b57cec5SDimitry Andric }; 1570b57cec5SDimitry Andric 1580b57cec5SDimitry Andric using FactID = unsigned short; 1590b57cec5SDimitry Andric 1600b57cec5SDimitry Andric /// FactManager manages the memory for all facts that are created during 1610b57cec5SDimitry Andric /// the analysis of a single routine. 1620b57cec5SDimitry Andric class FactManager { 1630b57cec5SDimitry Andric private: 1640b57cec5SDimitry Andric std::vector<std::unique_ptr<const FactEntry>> Facts; 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric public: 1670b57cec5SDimitry Andric FactID newFact(std::unique_ptr<FactEntry> Entry) { 1680b57cec5SDimitry Andric Facts.push_back(std::move(Entry)); 1690b57cec5SDimitry Andric return static_cast<unsigned short>(Facts.size() - 1); 1700b57cec5SDimitry Andric } 1710b57cec5SDimitry Andric 1720b57cec5SDimitry Andric const FactEntry &operator[](FactID F) const { return *Facts[F]; } 1730b57cec5SDimitry Andric }; 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric /// A FactSet is the set of facts that are known to be true at a 1760b57cec5SDimitry Andric /// particular program point. FactSets must be small, because they are 1770b57cec5SDimitry Andric /// frequently copied, and are thus implemented as a set of indices into a 1780b57cec5SDimitry Andric /// table maintained by a FactManager. A typical FactSet only holds 1 or 2 1790b57cec5SDimitry Andric /// locks, so we can get away with doing a linear search for lookup. Note 1800b57cec5SDimitry Andric /// that a hashtable or map is inappropriate in this case, because lookups 1810b57cec5SDimitry Andric /// may involve partial pattern matches, rather than exact matches. 1820b57cec5SDimitry Andric class FactSet { 1830b57cec5SDimitry Andric private: 1840b57cec5SDimitry Andric using FactVec = SmallVector<FactID, 4>; 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric FactVec FactIDs; 1870b57cec5SDimitry Andric 1880b57cec5SDimitry Andric public: 1890b57cec5SDimitry Andric using iterator = FactVec::iterator; 1900b57cec5SDimitry Andric using const_iterator = FactVec::const_iterator; 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric iterator begin() { return FactIDs.begin(); } 1930b57cec5SDimitry Andric const_iterator begin() const { return FactIDs.begin(); } 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric iterator end() { return FactIDs.end(); } 1960b57cec5SDimitry Andric const_iterator end() const { return FactIDs.end(); } 1970b57cec5SDimitry Andric 1980b57cec5SDimitry Andric bool isEmpty() const { return FactIDs.size() == 0; } 1990b57cec5SDimitry Andric 2000b57cec5SDimitry Andric // Return true if the set contains only negative facts 2010b57cec5SDimitry Andric bool isEmpty(FactManager &FactMan) const { 2020b57cec5SDimitry Andric for (const auto FID : *this) { 2030b57cec5SDimitry Andric if (!FactMan[FID].negative()) 2040b57cec5SDimitry Andric return false; 2050b57cec5SDimitry Andric } 2060b57cec5SDimitry Andric return true; 2070b57cec5SDimitry Andric } 2080b57cec5SDimitry Andric 2090b57cec5SDimitry Andric void addLockByID(FactID ID) { FactIDs.push_back(ID); } 2100b57cec5SDimitry Andric 2110b57cec5SDimitry Andric FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) { 2120b57cec5SDimitry Andric FactID F = FM.newFact(std::move(Entry)); 2130b57cec5SDimitry Andric FactIDs.push_back(F); 2140b57cec5SDimitry Andric return F; 2150b57cec5SDimitry Andric } 2160b57cec5SDimitry Andric 2170b57cec5SDimitry Andric bool removeLock(FactManager& FM, const CapabilityExpr &CapE) { 2180b57cec5SDimitry Andric unsigned n = FactIDs.size(); 2190b57cec5SDimitry Andric if (n == 0) 2200b57cec5SDimitry Andric return false; 2210b57cec5SDimitry Andric 2220b57cec5SDimitry Andric for (unsigned i = 0; i < n-1; ++i) { 2230b57cec5SDimitry Andric if (FM[FactIDs[i]].matches(CapE)) { 2240b57cec5SDimitry Andric FactIDs[i] = FactIDs[n-1]; 2250b57cec5SDimitry Andric FactIDs.pop_back(); 2260b57cec5SDimitry Andric return true; 2270b57cec5SDimitry Andric } 2280b57cec5SDimitry Andric } 2290b57cec5SDimitry Andric if (FM[FactIDs[n-1]].matches(CapE)) { 2300b57cec5SDimitry Andric FactIDs.pop_back(); 2310b57cec5SDimitry Andric return true; 2320b57cec5SDimitry Andric } 2330b57cec5SDimitry Andric return false; 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) { 2370b57cec5SDimitry Andric return std::find_if(begin(), end(), [&](FactID ID) { 2380b57cec5SDimitry Andric return FM[ID].matches(CapE); 2390b57cec5SDimitry Andric }); 2400b57cec5SDimitry Andric } 2410b57cec5SDimitry Andric 2420b57cec5SDimitry Andric const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const { 2430b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) { 2440b57cec5SDimitry Andric return FM[ID].matches(CapE); 2450b57cec5SDimitry Andric }); 2460b57cec5SDimitry Andric return I != end() ? &FM[*I] : nullptr; 2470b57cec5SDimitry Andric } 2480b57cec5SDimitry Andric 2490b57cec5SDimitry Andric const FactEntry *findLockUniv(FactManager &FM, 2500b57cec5SDimitry Andric const CapabilityExpr &CapE) const { 2510b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 2520b57cec5SDimitry Andric return FM[ID].matchesUniv(CapE); 2530b57cec5SDimitry Andric }); 2540b57cec5SDimitry Andric return I != end() ? &FM[*I] : nullptr; 2550b57cec5SDimitry Andric } 2560b57cec5SDimitry Andric 2570b57cec5SDimitry Andric const FactEntry *findPartialMatch(FactManager &FM, 2580b57cec5SDimitry Andric const CapabilityExpr &CapE) const { 2590b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 2600b57cec5SDimitry Andric return FM[ID].partiallyMatches(CapE); 2610b57cec5SDimitry Andric }); 2620b57cec5SDimitry Andric return I != end() ? &FM[*I] : nullptr; 2630b57cec5SDimitry Andric } 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const { 2660b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 2670b57cec5SDimitry Andric return FM[ID].valueDecl() == Vd; 2680b57cec5SDimitry Andric }); 2690b57cec5SDimitry Andric return I != end(); 2700b57cec5SDimitry Andric } 2710b57cec5SDimitry Andric }; 2720b57cec5SDimitry Andric 2730b57cec5SDimitry Andric class ThreadSafetyAnalyzer; 2740b57cec5SDimitry Andric 2750b57cec5SDimitry Andric } // namespace 2760b57cec5SDimitry Andric 2770b57cec5SDimitry Andric namespace clang { 2780b57cec5SDimitry Andric namespace threadSafety { 2790b57cec5SDimitry Andric 2800b57cec5SDimitry Andric class BeforeSet { 2810b57cec5SDimitry Andric private: 2820b57cec5SDimitry Andric using BeforeVect = SmallVector<const ValueDecl *, 4>; 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric struct BeforeInfo { 2850b57cec5SDimitry Andric BeforeVect Vect; 2860b57cec5SDimitry Andric int Visited = 0; 2870b57cec5SDimitry Andric 2880b57cec5SDimitry Andric BeforeInfo() = default; 2890b57cec5SDimitry Andric BeforeInfo(BeforeInfo &&) = default; 2900b57cec5SDimitry Andric }; 2910b57cec5SDimitry Andric 2920b57cec5SDimitry Andric using BeforeMap = 2930b57cec5SDimitry Andric llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>; 2940b57cec5SDimitry Andric using CycleMap = llvm::DenseMap<const ValueDecl *, bool>; 2950b57cec5SDimitry Andric 2960b57cec5SDimitry Andric public: 2970b57cec5SDimitry Andric BeforeSet() = default; 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric BeforeInfo* insertAttrExprs(const ValueDecl* Vd, 3000b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer); 3010b57cec5SDimitry Andric 3020b57cec5SDimitry Andric BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd, 3030b57cec5SDimitry Andric ThreadSafetyAnalyzer &Analyzer); 3040b57cec5SDimitry Andric 3050b57cec5SDimitry Andric void checkBeforeAfter(const ValueDecl* Vd, 3060b57cec5SDimitry Andric const FactSet& FSet, 3070b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer, 3080b57cec5SDimitry Andric SourceLocation Loc, StringRef CapKind); 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric private: 3110b57cec5SDimitry Andric BeforeMap BMap; 3120b57cec5SDimitry Andric CycleMap CycMap; 3130b57cec5SDimitry Andric }; 3140b57cec5SDimitry Andric 3150b57cec5SDimitry Andric } // namespace threadSafety 3160b57cec5SDimitry Andric } // namespace clang 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric namespace { 3190b57cec5SDimitry Andric 3200b57cec5SDimitry Andric class LocalVariableMap; 3210b57cec5SDimitry Andric 3220b57cec5SDimitry Andric using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>; 3230b57cec5SDimitry Andric 3240b57cec5SDimitry Andric /// A side (entry or exit) of a CFG node. 3250b57cec5SDimitry Andric enum CFGBlockSide { CBS_Entry, CBS_Exit }; 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric /// CFGBlockInfo is a struct which contains all the information that is 3280b57cec5SDimitry Andric /// maintained for each block in the CFG. See LocalVariableMap for more 3290b57cec5SDimitry Andric /// information about the contexts. 3300b57cec5SDimitry Andric struct CFGBlockInfo { 3310b57cec5SDimitry Andric // Lockset held at entry to block 3320b57cec5SDimitry Andric FactSet EntrySet; 3330b57cec5SDimitry Andric 3340b57cec5SDimitry Andric // Lockset held at exit from block 3350b57cec5SDimitry Andric FactSet ExitSet; 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric // Context held at entry to block 3380b57cec5SDimitry Andric LocalVarContext EntryContext; 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric // Context held at exit from block 3410b57cec5SDimitry Andric LocalVarContext ExitContext; 3420b57cec5SDimitry Andric 3430b57cec5SDimitry Andric // Location of first statement in block 3440b57cec5SDimitry Andric SourceLocation EntryLoc; 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric // Location of last statement in block. 3470b57cec5SDimitry Andric SourceLocation ExitLoc; 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric // Used to replay contexts later 3500b57cec5SDimitry Andric unsigned EntryIndex; 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric // Is this block reachable? 3530b57cec5SDimitry Andric bool Reachable = false; 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric const FactSet &getSet(CFGBlockSide Side) const { 3560b57cec5SDimitry Andric return Side == CBS_Entry ? EntrySet : ExitSet; 3570b57cec5SDimitry Andric } 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric SourceLocation getLocation(CFGBlockSide Side) const { 3600b57cec5SDimitry Andric return Side == CBS_Entry ? EntryLoc : ExitLoc; 3610b57cec5SDimitry Andric } 3620b57cec5SDimitry Andric 3630b57cec5SDimitry Andric private: 3640b57cec5SDimitry Andric CFGBlockInfo(LocalVarContext EmptyCtx) 3650b57cec5SDimitry Andric : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {} 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric public: 3680b57cec5SDimitry Andric static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M); 3690b57cec5SDimitry Andric }; 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric // A LocalVariableMap maintains a map from local variables to their currently 3720b57cec5SDimitry Andric // valid definitions. It provides SSA-like functionality when traversing the 3730b57cec5SDimitry Andric // CFG. Like SSA, each definition or assignment to a variable is assigned a 3740b57cec5SDimitry Andric // unique name (an integer), which acts as the SSA name for that definition. 3750b57cec5SDimitry Andric // The total set of names is shared among all CFG basic blocks. 3760b57cec5SDimitry Andric // Unlike SSA, we do not rewrite expressions to replace local variables declrefs 3770b57cec5SDimitry Andric // with their SSA-names. Instead, we compute a Context for each point in the 3780b57cec5SDimitry Andric // code, which maps local variables to the appropriate SSA-name. This map 3790b57cec5SDimitry Andric // changes with each assignment. 3800b57cec5SDimitry Andric // 3810b57cec5SDimitry Andric // The map is computed in a single pass over the CFG. Subsequent analyses can 3820b57cec5SDimitry Andric // then query the map to find the appropriate Context for a statement, and use 3830b57cec5SDimitry Andric // that Context to look up the definitions of variables. 3840b57cec5SDimitry Andric class LocalVariableMap { 3850b57cec5SDimitry Andric public: 3860b57cec5SDimitry Andric using Context = LocalVarContext; 3870b57cec5SDimitry Andric 3880b57cec5SDimitry Andric /// A VarDefinition consists of an expression, representing the value of the 3890b57cec5SDimitry Andric /// variable, along with the context in which that expression should be 3900b57cec5SDimitry Andric /// interpreted. A reference VarDefinition does not itself contain this 3910b57cec5SDimitry Andric /// information, but instead contains a pointer to a previous VarDefinition. 3920b57cec5SDimitry Andric struct VarDefinition { 3930b57cec5SDimitry Andric public: 3940b57cec5SDimitry Andric friend class LocalVariableMap; 3950b57cec5SDimitry Andric 3960b57cec5SDimitry Andric // The original declaration for this variable. 3970b57cec5SDimitry Andric const NamedDecl *Dec; 3980b57cec5SDimitry Andric 3990b57cec5SDimitry Andric // The expression for this variable, OR 4000b57cec5SDimitry Andric const Expr *Exp = nullptr; 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric // Reference to another VarDefinition 4030b57cec5SDimitry Andric unsigned Ref = 0; 4040b57cec5SDimitry Andric 4050b57cec5SDimitry Andric // The map with which Exp should be interpreted. 4060b57cec5SDimitry Andric Context Ctx; 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric bool isReference() { return !Exp; } 4090b57cec5SDimitry Andric 4100b57cec5SDimitry Andric private: 4110b57cec5SDimitry Andric // Create ordinary variable definition 4120b57cec5SDimitry Andric VarDefinition(const NamedDecl *D, const Expr *E, Context C) 4130b57cec5SDimitry Andric : Dec(D), Exp(E), Ctx(C) {} 4140b57cec5SDimitry Andric 4150b57cec5SDimitry Andric // Create reference to previous definition 4160b57cec5SDimitry Andric VarDefinition(const NamedDecl *D, unsigned R, Context C) 4170b57cec5SDimitry Andric : Dec(D), Ref(R), Ctx(C) {} 4180b57cec5SDimitry Andric }; 4190b57cec5SDimitry Andric 4200b57cec5SDimitry Andric private: 4210b57cec5SDimitry Andric Context::Factory ContextFactory; 4220b57cec5SDimitry Andric std::vector<VarDefinition> VarDefinitions; 4230b57cec5SDimitry Andric std::vector<unsigned> CtxIndices; 4240b57cec5SDimitry Andric std::vector<std::pair<const Stmt *, Context>> SavedContexts; 4250b57cec5SDimitry Andric 4260b57cec5SDimitry Andric public: 4270b57cec5SDimitry Andric LocalVariableMap() { 4280b57cec5SDimitry Andric // index 0 is a placeholder for undefined variables (aka phi-nodes). 4290b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext())); 4300b57cec5SDimitry Andric } 4310b57cec5SDimitry Andric 4320b57cec5SDimitry Andric /// Look up a definition, within the given context. 4330b57cec5SDimitry Andric const VarDefinition* lookup(const NamedDecl *D, Context Ctx) { 4340b57cec5SDimitry Andric const unsigned *i = Ctx.lookup(D); 4350b57cec5SDimitry Andric if (!i) 4360b57cec5SDimitry Andric return nullptr; 4370b57cec5SDimitry Andric assert(*i < VarDefinitions.size()); 4380b57cec5SDimitry Andric return &VarDefinitions[*i]; 4390b57cec5SDimitry Andric } 4400b57cec5SDimitry Andric 4410b57cec5SDimitry Andric /// Look up the definition for D within the given context. Returns 4420b57cec5SDimitry Andric /// NULL if the expression is not statically known. If successful, also 4430b57cec5SDimitry Andric /// modifies Ctx to hold the context of the return Expr. 4440b57cec5SDimitry Andric const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) { 4450b57cec5SDimitry Andric const unsigned *P = Ctx.lookup(D); 4460b57cec5SDimitry Andric if (!P) 4470b57cec5SDimitry Andric return nullptr; 4480b57cec5SDimitry Andric 4490b57cec5SDimitry Andric unsigned i = *P; 4500b57cec5SDimitry Andric while (i > 0) { 4510b57cec5SDimitry Andric if (VarDefinitions[i].Exp) { 4520b57cec5SDimitry Andric Ctx = VarDefinitions[i].Ctx; 4530b57cec5SDimitry Andric return VarDefinitions[i].Exp; 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric i = VarDefinitions[i].Ref; 4560b57cec5SDimitry Andric } 4570b57cec5SDimitry Andric return nullptr; 4580b57cec5SDimitry Andric } 4590b57cec5SDimitry Andric 4600b57cec5SDimitry Andric Context getEmptyContext() { return ContextFactory.getEmptyMap(); } 4610b57cec5SDimitry Andric 4620b57cec5SDimitry Andric /// Return the next context after processing S. This function is used by 4630b57cec5SDimitry Andric /// clients of the class to get the appropriate context when traversing the 4640b57cec5SDimitry Andric /// CFG. It must be called for every assignment or DeclStmt. 4650b57cec5SDimitry Andric Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) { 4660b57cec5SDimitry Andric if (SavedContexts[CtxIndex+1].first == S) { 4670b57cec5SDimitry Andric CtxIndex++; 4680b57cec5SDimitry Andric Context Result = SavedContexts[CtxIndex].second; 4690b57cec5SDimitry Andric return Result; 4700b57cec5SDimitry Andric } 4710b57cec5SDimitry Andric return C; 4720b57cec5SDimitry Andric } 4730b57cec5SDimitry Andric 4740b57cec5SDimitry Andric void dumpVarDefinitionName(unsigned i) { 4750b57cec5SDimitry Andric if (i == 0) { 4760b57cec5SDimitry Andric llvm::errs() << "Undefined"; 4770b57cec5SDimitry Andric return; 4780b57cec5SDimitry Andric } 4790b57cec5SDimitry Andric const NamedDecl *Dec = VarDefinitions[i].Dec; 4800b57cec5SDimitry Andric if (!Dec) { 4810b57cec5SDimitry Andric llvm::errs() << "<<NULL>>"; 4820b57cec5SDimitry Andric return; 4830b57cec5SDimitry Andric } 4840b57cec5SDimitry Andric Dec->printName(llvm::errs()); 4850b57cec5SDimitry Andric llvm::errs() << "." << i << " " << ((const void*) Dec); 4860b57cec5SDimitry Andric } 4870b57cec5SDimitry Andric 4880b57cec5SDimitry Andric /// Dumps an ASCII representation of the variable map to llvm::errs() 4890b57cec5SDimitry Andric void dump() { 4900b57cec5SDimitry Andric for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) { 4910b57cec5SDimitry Andric const Expr *Exp = VarDefinitions[i].Exp; 4920b57cec5SDimitry Andric unsigned Ref = VarDefinitions[i].Ref; 4930b57cec5SDimitry Andric 4940b57cec5SDimitry Andric dumpVarDefinitionName(i); 4950b57cec5SDimitry Andric llvm::errs() << " = "; 4960b57cec5SDimitry Andric if (Exp) Exp->dump(); 4970b57cec5SDimitry Andric else { 4980b57cec5SDimitry Andric dumpVarDefinitionName(Ref); 4990b57cec5SDimitry Andric llvm::errs() << "\n"; 5000b57cec5SDimitry Andric } 5010b57cec5SDimitry Andric } 5020b57cec5SDimitry Andric } 5030b57cec5SDimitry Andric 5040b57cec5SDimitry Andric /// Dumps an ASCII representation of a Context to llvm::errs() 5050b57cec5SDimitry Andric void dumpContext(Context C) { 5060b57cec5SDimitry Andric for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) { 5070b57cec5SDimitry Andric const NamedDecl *D = I.getKey(); 5080b57cec5SDimitry Andric D->printName(llvm::errs()); 5090b57cec5SDimitry Andric const unsigned *i = C.lookup(D); 5100b57cec5SDimitry Andric llvm::errs() << " -> "; 5110b57cec5SDimitry Andric dumpVarDefinitionName(*i); 5120b57cec5SDimitry Andric llvm::errs() << "\n"; 5130b57cec5SDimitry Andric } 5140b57cec5SDimitry Andric } 5150b57cec5SDimitry Andric 5160b57cec5SDimitry Andric /// Builds the variable map. 5170b57cec5SDimitry Andric void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph, 5180b57cec5SDimitry Andric std::vector<CFGBlockInfo> &BlockInfo); 5190b57cec5SDimitry Andric 5200b57cec5SDimitry Andric protected: 5210b57cec5SDimitry Andric friend class VarMapBuilder; 5220b57cec5SDimitry Andric 5230b57cec5SDimitry Andric // Get the current context index 5240b57cec5SDimitry Andric unsigned getContextIndex() { return SavedContexts.size()-1; } 5250b57cec5SDimitry Andric 5260b57cec5SDimitry Andric // Save the current context for later replay 5270b57cec5SDimitry Andric void saveContext(const Stmt *S, Context C) { 5280b57cec5SDimitry Andric SavedContexts.push_back(std::make_pair(S, C)); 5290b57cec5SDimitry Andric } 5300b57cec5SDimitry Andric 5310b57cec5SDimitry Andric // Adds a new definition to the given context, and returns a new context. 5320b57cec5SDimitry Andric // This method should be called when declaring a new variable. 5330b57cec5SDimitry Andric Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) { 5340b57cec5SDimitry Andric assert(!Ctx.contains(D)); 5350b57cec5SDimitry Andric unsigned newID = VarDefinitions.size(); 5360b57cec5SDimitry Andric Context NewCtx = ContextFactory.add(Ctx, D, newID); 5370b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 5380b57cec5SDimitry Andric return NewCtx; 5390b57cec5SDimitry Andric } 5400b57cec5SDimitry Andric 5410b57cec5SDimitry Andric // Add a new reference to an existing definition. 5420b57cec5SDimitry Andric Context addReference(const NamedDecl *D, unsigned i, Context Ctx) { 5430b57cec5SDimitry Andric unsigned newID = VarDefinitions.size(); 5440b57cec5SDimitry Andric Context NewCtx = ContextFactory.add(Ctx, D, newID); 5450b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(D, i, Ctx)); 5460b57cec5SDimitry Andric return NewCtx; 5470b57cec5SDimitry Andric } 5480b57cec5SDimitry Andric 5490b57cec5SDimitry Andric // Updates a definition only if that definition is already in the map. 5500b57cec5SDimitry Andric // This method should be called when assigning to an existing variable. 5510b57cec5SDimitry Andric Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) { 5520b57cec5SDimitry Andric if (Ctx.contains(D)) { 5530b57cec5SDimitry Andric unsigned newID = VarDefinitions.size(); 5540b57cec5SDimitry Andric Context NewCtx = ContextFactory.remove(Ctx, D); 5550b57cec5SDimitry Andric NewCtx = ContextFactory.add(NewCtx, D, newID); 5560b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 5570b57cec5SDimitry Andric return NewCtx; 5580b57cec5SDimitry Andric } 5590b57cec5SDimitry Andric return Ctx; 5600b57cec5SDimitry Andric } 5610b57cec5SDimitry Andric 5620b57cec5SDimitry Andric // Removes a definition from the context, but keeps the variable name 5630b57cec5SDimitry Andric // as a valid variable. The index 0 is a placeholder for cleared definitions. 5640b57cec5SDimitry Andric Context clearDefinition(const NamedDecl *D, Context Ctx) { 5650b57cec5SDimitry Andric Context NewCtx = Ctx; 5660b57cec5SDimitry Andric if (NewCtx.contains(D)) { 5670b57cec5SDimitry Andric NewCtx = ContextFactory.remove(NewCtx, D); 5680b57cec5SDimitry Andric NewCtx = ContextFactory.add(NewCtx, D, 0); 5690b57cec5SDimitry Andric } 5700b57cec5SDimitry Andric return NewCtx; 5710b57cec5SDimitry Andric } 5720b57cec5SDimitry Andric 5730b57cec5SDimitry Andric // Remove a definition entirely frmo the context. 5740b57cec5SDimitry Andric Context removeDefinition(const NamedDecl *D, Context Ctx) { 5750b57cec5SDimitry Andric Context NewCtx = Ctx; 5760b57cec5SDimitry Andric if (NewCtx.contains(D)) { 5770b57cec5SDimitry Andric NewCtx = ContextFactory.remove(NewCtx, D); 5780b57cec5SDimitry Andric } 5790b57cec5SDimitry Andric return NewCtx; 5800b57cec5SDimitry Andric } 5810b57cec5SDimitry Andric 5820b57cec5SDimitry Andric Context intersectContexts(Context C1, Context C2); 5830b57cec5SDimitry Andric Context createReferenceContext(Context C); 5840b57cec5SDimitry Andric void intersectBackEdge(Context C1, Context C2); 5850b57cec5SDimitry Andric }; 5860b57cec5SDimitry Andric 5870b57cec5SDimitry Andric } // namespace 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric // This has to be defined after LocalVariableMap. 5900b57cec5SDimitry Andric CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) { 5910b57cec5SDimitry Andric return CFGBlockInfo(M.getEmptyContext()); 5920b57cec5SDimitry Andric } 5930b57cec5SDimitry Andric 5940b57cec5SDimitry Andric namespace { 5950b57cec5SDimitry Andric 5960b57cec5SDimitry Andric /// Visitor which builds a LocalVariableMap 5970b57cec5SDimitry Andric class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> { 5980b57cec5SDimitry Andric public: 5990b57cec5SDimitry Andric LocalVariableMap* VMap; 6000b57cec5SDimitry Andric LocalVariableMap::Context Ctx; 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C) 6030b57cec5SDimitry Andric : VMap(VM), Ctx(C) {} 6040b57cec5SDimitry Andric 6050b57cec5SDimitry Andric void VisitDeclStmt(const DeclStmt *S); 6060b57cec5SDimitry Andric void VisitBinaryOperator(const BinaryOperator *BO); 6070b57cec5SDimitry Andric }; 6080b57cec5SDimitry Andric 6090b57cec5SDimitry Andric } // namespace 6100b57cec5SDimitry Andric 6110b57cec5SDimitry Andric // Add new local variables to the variable map 6120b57cec5SDimitry Andric void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) { 6130b57cec5SDimitry Andric bool modifiedCtx = false; 6140b57cec5SDimitry Andric const DeclGroupRef DGrp = S->getDeclGroup(); 6150b57cec5SDimitry Andric for (const auto *D : DGrp) { 6160b57cec5SDimitry Andric if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) { 6170b57cec5SDimitry Andric const Expr *E = VD->getInit(); 6180b57cec5SDimitry Andric 6190b57cec5SDimitry Andric // Add local variables with trivial type to the variable map 6200b57cec5SDimitry Andric QualType T = VD->getType(); 6210b57cec5SDimitry Andric if (T.isTrivialType(VD->getASTContext())) { 6220b57cec5SDimitry Andric Ctx = VMap->addDefinition(VD, E, Ctx); 6230b57cec5SDimitry Andric modifiedCtx = true; 6240b57cec5SDimitry Andric } 6250b57cec5SDimitry Andric } 6260b57cec5SDimitry Andric } 6270b57cec5SDimitry Andric if (modifiedCtx) 6280b57cec5SDimitry Andric VMap->saveContext(S, Ctx); 6290b57cec5SDimitry Andric } 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric // Update local variable definitions in variable map 6320b57cec5SDimitry Andric void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) { 6330b57cec5SDimitry Andric if (!BO->isAssignmentOp()) 6340b57cec5SDimitry Andric return; 6350b57cec5SDimitry Andric 6360b57cec5SDimitry Andric Expr *LHSExp = BO->getLHS()->IgnoreParenCasts(); 6370b57cec5SDimitry Andric 6380b57cec5SDimitry Andric // Update the variable map and current context. 6390b57cec5SDimitry Andric if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) { 6400b57cec5SDimitry Andric const ValueDecl *VDec = DRE->getDecl(); 6410b57cec5SDimitry Andric if (Ctx.lookup(VDec)) { 6420b57cec5SDimitry Andric if (BO->getOpcode() == BO_Assign) 6430b57cec5SDimitry Andric Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx); 6440b57cec5SDimitry Andric else 6450b57cec5SDimitry Andric // FIXME -- handle compound assignment operators 6460b57cec5SDimitry Andric Ctx = VMap->clearDefinition(VDec, Ctx); 6470b57cec5SDimitry Andric VMap->saveContext(BO, Ctx); 6480b57cec5SDimitry Andric } 6490b57cec5SDimitry Andric } 6500b57cec5SDimitry Andric } 6510b57cec5SDimitry Andric 6520b57cec5SDimitry Andric // Computes the intersection of two contexts. The intersection is the 6530b57cec5SDimitry Andric // set of variables which have the same definition in both contexts; 6540b57cec5SDimitry Andric // variables with different definitions are discarded. 6550b57cec5SDimitry Andric LocalVariableMap::Context 6560b57cec5SDimitry Andric LocalVariableMap::intersectContexts(Context C1, Context C2) { 6570b57cec5SDimitry Andric Context Result = C1; 6580b57cec5SDimitry Andric for (const auto &P : C1) { 6590b57cec5SDimitry Andric const NamedDecl *Dec = P.first; 6600b57cec5SDimitry Andric const unsigned *i2 = C2.lookup(Dec); 6610b57cec5SDimitry Andric if (!i2) // variable doesn't exist on second path 6620b57cec5SDimitry Andric Result = removeDefinition(Dec, Result); 6630b57cec5SDimitry Andric else if (*i2 != P.second) // variable exists, but has different definition 6640b57cec5SDimitry Andric Result = clearDefinition(Dec, Result); 6650b57cec5SDimitry Andric } 6660b57cec5SDimitry Andric return Result; 6670b57cec5SDimitry Andric } 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric // For every variable in C, create a new variable that refers to the 6700b57cec5SDimitry Andric // definition in C. Return a new context that contains these new variables. 6710b57cec5SDimitry Andric // (We use this for a naive implementation of SSA on loop back-edges.) 6720b57cec5SDimitry Andric LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) { 6730b57cec5SDimitry Andric Context Result = getEmptyContext(); 6740b57cec5SDimitry Andric for (const auto &P : C) 6750b57cec5SDimitry Andric Result = addReference(P.first, P.second, Result); 6760b57cec5SDimitry Andric return Result; 6770b57cec5SDimitry Andric } 6780b57cec5SDimitry Andric 6790b57cec5SDimitry Andric // This routine also takes the intersection of C1 and C2, but it does so by 6800b57cec5SDimitry Andric // altering the VarDefinitions. C1 must be the result of an earlier call to 6810b57cec5SDimitry Andric // createReferenceContext. 6820b57cec5SDimitry Andric void LocalVariableMap::intersectBackEdge(Context C1, Context C2) { 6830b57cec5SDimitry Andric for (const auto &P : C1) { 6840b57cec5SDimitry Andric unsigned i1 = P.second; 6850b57cec5SDimitry Andric VarDefinition *VDef = &VarDefinitions[i1]; 6860b57cec5SDimitry Andric assert(VDef->isReference()); 6870b57cec5SDimitry Andric 6880b57cec5SDimitry Andric const unsigned *i2 = C2.lookup(P.first); 6890b57cec5SDimitry Andric if (!i2 || (*i2 != i1)) 6900b57cec5SDimitry Andric VDef->Ref = 0; // Mark this variable as undefined 6910b57cec5SDimitry Andric } 6920b57cec5SDimitry Andric } 6930b57cec5SDimitry Andric 6940b57cec5SDimitry Andric // Traverse the CFG in topological order, so all predecessors of a block 6950b57cec5SDimitry Andric // (excluding back-edges) are visited before the block itself. At 6960b57cec5SDimitry Andric // each point in the code, we calculate a Context, which holds the set of 6970b57cec5SDimitry Andric // variable definitions which are visible at that point in execution. 6980b57cec5SDimitry Andric // Visible variables are mapped to their definitions using an array that 6990b57cec5SDimitry Andric // contains all definitions. 7000b57cec5SDimitry Andric // 7010b57cec5SDimitry Andric // At join points in the CFG, the set is computed as the intersection of 7020b57cec5SDimitry Andric // the incoming sets along each edge, E.g. 7030b57cec5SDimitry Andric // 7040b57cec5SDimitry Andric // { Context | VarDefinitions } 7050b57cec5SDimitry Andric // int x = 0; { x -> x1 | x1 = 0 } 7060b57cec5SDimitry Andric // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 7070b57cec5SDimitry Andric // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... } 7080b57cec5SDimitry Andric // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... } 7090b57cec5SDimitry Andric // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... } 7100b57cec5SDimitry Andric // 7110b57cec5SDimitry Andric // This is essentially a simpler and more naive version of the standard SSA 7120b57cec5SDimitry Andric // algorithm. Those definitions that remain in the intersection are from blocks 7130b57cec5SDimitry Andric // that strictly dominate the current block. We do not bother to insert proper 7140b57cec5SDimitry Andric // phi nodes, because they are not used in our analysis; instead, wherever 7150b57cec5SDimitry Andric // a phi node would be required, we simply remove that definition from the 7160b57cec5SDimitry Andric // context (E.g. x above). 7170b57cec5SDimitry Andric // 7180b57cec5SDimitry Andric // The initial traversal does not capture back-edges, so those need to be 7190b57cec5SDimitry Andric // handled on a separate pass. Whenever the first pass encounters an 7200b57cec5SDimitry Andric // incoming back edge, it duplicates the context, creating new definitions 7210b57cec5SDimitry Andric // that refer back to the originals. (These correspond to places where SSA 7220b57cec5SDimitry Andric // might have to insert a phi node.) On the second pass, these definitions are 7230b57cec5SDimitry Andric // set to NULL if the variable has changed on the back-edge (i.e. a phi 7240b57cec5SDimitry Andric // node was actually required.) E.g. 7250b57cec5SDimitry Andric // 7260b57cec5SDimitry Andric // { Context | VarDefinitions } 7270b57cec5SDimitry Andric // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 7280b57cec5SDimitry Andric // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; } 7290b57cec5SDimitry Andric // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... } 7300b57cec5SDimitry Andric // ... { y -> y1 | x3 = 2, x2 = 1, ... } 7310b57cec5SDimitry Andric void LocalVariableMap::traverseCFG(CFG *CFGraph, 7320b57cec5SDimitry Andric const PostOrderCFGView *SortedGraph, 7330b57cec5SDimitry Andric std::vector<CFGBlockInfo> &BlockInfo) { 7340b57cec5SDimitry Andric PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 7350b57cec5SDimitry Andric 7360b57cec5SDimitry Andric CtxIndices.resize(CFGraph->getNumBlockIDs()); 7370b57cec5SDimitry Andric 7380b57cec5SDimitry Andric for (const auto *CurrBlock : *SortedGraph) { 7390b57cec5SDimitry Andric unsigned CurrBlockID = CurrBlock->getBlockID(); 7400b57cec5SDimitry Andric CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 7410b57cec5SDimitry Andric 7420b57cec5SDimitry Andric VisitedBlocks.insert(CurrBlock); 7430b57cec5SDimitry Andric 7440b57cec5SDimitry Andric // Calculate the entry context for the current block 7450b57cec5SDimitry Andric bool HasBackEdges = false; 7460b57cec5SDimitry Andric bool CtxInit = true; 7470b57cec5SDimitry Andric for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 7480b57cec5SDimitry Andric PE = CurrBlock->pred_end(); PI != PE; ++PI) { 7490b57cec5SDimitry Andric // if *PI -> CurrBlock is a back edge, so skip it 7500b57cec5SDimitry Andric if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) { 7510b57cec5SDimitry Andric HasBackEdges = true; 7520b57cec5SDimitry Andric continue; 7530b57cec5SDimitry Andric } 7540b57cec5SDimitry Andric 7550b57cec5SDimitry Andric unsigned PrevBlockID = (*PI)->getBlockID(); 7560b57cec5SDimitry Andric CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 7570b57cec5SDimitry Andric 7580b57cec5SDimitry Andric if (CtxInit) { 7590b57cec5SDimitry Andric CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext; 7600b57cec5SDimitry Andric CtxInit = false; 7610b57cec5SDimitry Andric } 7620b57cec5SDimitry Andric else { 7630b57cec5SDimitry Andric CurrBlockInfo->EntryContext = 7640b57cec5SDimitry Andric intersectContexts(CurrBlockInfo->EntryContext, 7650b57cec5SDimitry Andric PrevBlockInfo->ExitContext); 7660b57cec5SDimitry Andric } 7670b57cec5SDimitry Andric } 7680b57cec5SDimitry Andric 7690b57cec5SDimitry Andric // Duplicate the context if we have back-edges, so we can call 7700b57cec5SDimitry Andric // intersectBackEdges later. 7710b57cec5SDimitry Andric if (HasBackEdges) 7720b57cec5SDimitry Andric CurrBlockInfo->EntryContext = 7730b57cec5SDimitry Andric createReferenceContext(CurrBlockInfo->EntryContext); 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric // Create a starting context index for the current block 7760b57cec5SDimitry Andric saveContext(nullptr, CurrBlockInfo->EntryContext); 7770b57cec5SDimitry Andric CurrBlockInfo->EntryIndex = getContextIndex(); 7780b57cec5SDimitry Andric 7790b57cec5SDimitry Andric // Visit all the statements in the basic block. 7800b57cec5SDimitry Andric VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext); 7810b57cec5SDimitry Andric for (const auto &BI : *CurrBlock) { 7820b57cec5SDimitry Andric switch (BI.getKind()) { 7830b57cec5SDimitry Andric case CFGElement::Statement: { 7840b57cec5SDimitry Andric CFGStmt CS = BI.castAs<CFGStmt>(); 7850b57cec5SDimitry Andric VMapBuilder.Visit(CS.getStmt()); 7860b57cec5SDimitry Andric break; 7870b57cec5SDimitry Andric } 7880b57cec5SDimitry Andric default: 7890b57cec5SDimitry Andric break; 7900b57cec5SDimitry Andric } 7910b57cec5SDimitry Andric } 7920b57cec5SDimitry Andric CurrBlockInfo->ExitContext = VMapBuilder.Ctx; 7930b57cec5SDimitry Andric 7940b57cec5SDimitry Andric // Mark variables on back edges as "unknown" if they've been changed. 7950b57cec5SDimitry Andric for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 7960b57cec5SDimitry Andric SE = CurrBlock->succ_end(); SI != SE; ++SI) { 7970b57cec5SDimitry Andric // if CurrBlock -> *SI is *not* a back edge 7980b57cec5SDimitry Andric if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI)) 7990b57cec5SDimitry Andric continue; 8000b57cec5SDimitry Andric 8010b57cec5SDimitry Andric CFGBlock *FirstLoopBlock = *SI; 8020b57cec5SDimitry Andric Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext; 8030b57cec5SDimitry Andric Context LoopEnd = CurrBlockInfo->ExitContext; 8040b57cec5SDimitry Andric intersectBackEdge(LoopBegin, LoopEnd); 8050b57cec5SDimitry Andric } 8060b57cec5SDimitry Andric } 8070b57cec5SDimitry Andric 8080b57cec5SDimitry Andric // Put an extra entry at the end of the indexed context array 8090b57cec5SDimitry Andric unsigned exitID = CFGraph->getExit().getBlockID(); 8100b57cec5SDimitry Andric saveContext(nullptr, BlockInfo[exitID].ExitContext); 8110b57cec5SDimitry Andric } 8120b57cec5SDimitry Andric 8130b57cec5SDimitry Andric /// Find the appropriate source locations to use when producing diagnostics for 8140b57cec5SDimitry Andric /// each block in the CFG. 8150b57cec5SDimitry Andric static void findBlockLocations(CFG *CFGraph, 8160b57cec5SDimitry Andric const PostOrderCFGView *SortedGraph, 8170b57cec5SDimitry Andric std::vector<CFGBlockInfo> &BlockInfo) { 8180b57cec5SDimitry Andric for (const auto *CurrBlock : *SortedGraph) { 8190b57cec5SDimitry Andric CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()]; 8200b57cec5SDimitry Andric 8210b57cec5SDimitry Andric // Find the source location of the last statement in the block, if the 8220b57cec5SDimitry Andric // block is not empty. 8230b57cec5SDimitry Andric if (const Stmt *S = CurrBlock->getTerminatorStmt()) { 8240b57cec5SDimitry Andric CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc(); 8250b57cec5SDimitry Andric } else { 8260b57cec5SDimitry Andric for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(), 8270b57cec5SDimitry Andric BE = CurrBlock->rend(); BI != BE; ++BI) { 8280b57cec5SDimitry Andric // FIXME: Handle other CFGElement kinds. 8290b57cec5SDimitry Andric if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { 8300b57cec5SDimitry Andric CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc(); 8310b57cec5SDimitry Andric break; 8320b57cec5SDimitry Andric } 8330b57cec5SDimitry Andric } 8340b57cec5SDimitry Andric } 8350b57cec5SDimitry Andric 8360b57cec5SDimitry Andric if (CurrBlockInfo->ExitLoc.isValid()) { 8370b57cec5SDimitry Andric // This block contains at least one statement. Find the source location 8380b57cec5SDimitry Andric // of the first statement in the block. 8390b57cec5SDimitry Andric for (const auto &BI : *CurrBlock) { 8400b57cec5SDimitry Andric // FIXME: Handle other CFGElement kinds. 8410b57cec5SDimitry Andric if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) { 8420b57cec5SDimitry Andric CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc(); 8430b57cec5SDimitry Andric break; 8440b57cec5SDimitry Andric } 8450b57cec5SDimitry Andric } 8460b57cec5SDimitry Andric } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() && 8470b57cec5SDimitry Andric CurrBlock != &CFGraph->getExit()) { 8480b57cec5SDimitry Andric // The block is empty, and has a single predecessor. Use its exit 8490b57cec5SDimitry Andric // location. 8500b57cec5SDimitry Andric CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = 8510b57cec5SDimitry Andric BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc; 8520b57cec5SDimitry Andric } 8530b57cec5SDimitry Andric } 8540b57cec5SDimitry Andric } 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric namespace { 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric class LockableFactEntry : public FactEntry { 8590b57cec5SDimitry Andric public: 8600b57cec5SDimitry Andric LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc, 861fe6060f1SDimitry Andric SourceKind Src = Acquired) 862fe6060f1SDimitry Andric : FactEntry(CE, LK, Loc, Src) {} 8630b57cec5SDimitry Andric 8640b57cec5SDimitry Andric void 8650b57cec5SDimitry Andric handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 8660b57cec5SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK, 8670b57cec5SDimitry Andric ThreadSafetyHandler &Handler) const override { 868fe6060f1SDimitry Andric if (!asserted() && !negative() && !isUniversal()) { 8690b57cec5SDimitry Andric Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc, 8700b57cec5SDimitry Andric LEK); 8710b57cec5SDimitry Andric } 8720b57cec5SDimitry Andric } 8730b57cec5SDimitry Andric 8740b57cec5SDimitry Andric void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry, 8750b57cec5SDimitry Andric ThreadSafetyHandler &Handler, 8760b57cec5SDimitry Andric StringRef DiagKind) const override { 8770b57cec5SDimitry Andric Handler.handleDoubleLock(DiagKind, entry.toString(), loc(), entry.loc()); 8780b57cec5SDimitry Andric } 8790b57cec5SDimitry Andric 8800b57cec5SDimitry Andric void handleUnlock(FactSet &FSet, FactManager &FactMan, 8810b57cec5SDimitry Andric const CapabilityExpr &Cp, SourceLocation UnlockLoc, 8820b57cec5SDimitry Andric bool FullyRemove, ThreadSafetyHandler &Handler, 8830b57cec5SDimitry Andric StringRef DiagKind) const override { 8840b57cec5SDimitry Andric FSet.removeLock(FactMan, Cp); 8850b57cec5SDimitry Andric if (!Cp.negative()) { 886a7dea167SDimitry Andric FSet.addLock(FactMan, std::make_unique<LockableFactEntry>( 8870b57cec5SDimitry Andric !Cp, LK_Exclusive, UnlockLoc)); 8880b57cec5SDimitry Andric } 8890b57cec5SDimitry Andric } 8900b57cec5SDimitry Andric }; 8910b57cec5SDimitry Andric 8920b57cec5SDimitry Andric class ScopedLockableFactEntry : public FactEntry { 8930b57cec5SDimitry Andric private: 8940b57cec5SDimitry Andric enum UnderlyingCapabilityKind { 8950b57cec5SDimitry Andric UCK_Acquired, ///< Any kind of acquired capability. 8960b57cec5SDimitry Andric UCK_ReleasedShared, ///< Shared capability that was released. 8970b57cec5SDimitry Andric UCK_ReleasedExclusive, ///< Exclusive capability that was released. 8980b57cec5SDimitry Andric }; 8990b57cec5SDimitry Andric 9000b57cec5SDimitry Andric using UnderlyingCapability = 9010b57cec5SDimitry Andric llvm::PointerIntPair<const til::SExpr *, 2, UnderlyingCapabilityKind>; 9020b57cec5SDimitry Andric 9030b57cec5SDimitry Andric SmallVector<UnderlyingCapability, 4> UnderlyingMutexes; 9040b57cec5SDimitry Andric 9050b57cec5SDimitry Andric public: 9060b57cec5SDimitry Andric ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc) 907fe6060f1SDimitry Andric : FactEntry(CE, LK_Exclusive, Loc, Acquired) {} 9080b57cec5SDimitry Andric 9095ffd83dbSDimitry Andric void addLock(const CapabilityExpr &M) { 9100b57cec5SDimitry Andric UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired); 9110b57cec5SDimitry Andric } 9120b57cec5SDimitry Andric 9130b57cec5SDimitry Andric void addExclusiveUnlock(const CapabilityExpr &M) { 9140b57cec5SDimitry Andric UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedExclusive); 9150b57cec5SDimitry Andric } 9160b57cec5SDimitry Andric 9170b57cec5SDimitry Andric void addSharedUnlock(const CapabilityExpr &M) { 9180b57cec5SDimitry Andric UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedShared); 9190b57cec5SDimitry Andric } 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric void 9220b57cec5SDimitry Andric handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 9230b57cec5SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK, 9240b57cec5SDimitry Andric ThreadSafetyHandler &Handler) const override { 9250b57cec5SDimitry Andric for (const auto &UnderlyingMutex : UnderlyingMutexes) { 9260b57cec5SDimitry Andric const auto *Entry = FSet.findLock( 9270b57cec5SDimitry Andric FactMan, CapabilityExpr(UnderlyingMutex.getPointer(), false)); 9280b57cec5SDimitry Andric if ((UnderlyingMutex.getInt() == UCK_Acquired && Entry) || 9290b57cec5SDimitry Andric (UnderlyingMutex.getInt() != 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. 9320b57cec5SDimitry Andric Handler.handleMutexHeldEndOfScope( 9330b57cec5SDimitry Andric "mutex", sx::toString(UnderlyingMutex.getPointer()), loc(), JoinLoc, 9340b57cec5SDimitry Andric LEK); 9350b57cec5SDimitry Andric } 9360b57cec5SDimitry Andric } 9370b57cec5SDimitry Andric } 9380b57cec5SDimitry Andric 9390b57cec5SDimitry Andric void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry, 9400b57cec5SDimitry Andric ThreadSafetyHandler &Handler, 9410b57cec5SDimitry Andric StringRef DiagKind) const override { 9420b57cec5SDimitry Andric for (const auto &UnderlyingMutex : UnderlyingMutexes) { 9430b57cec5SDimitry Andric CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false); 9440b57cec5SDimitry Andric 9450b57cec5SDimitry Andric if (UnderlyingMutex.getInt() == UCK_Acquired) 9460b57cec5SDimitry Andric lock(FSet, FactMan, UnderCp, entry.kind(), entry.loc(), &Handler, 9470b57cec5SDimitry Andric DiagKind); 9480b57cec5SDimitry Andric else 9490b57cec5SDimitry Andric unlock(FSet, FactMan, UnderCp, entry.loc(), &Handler, DiagKind); 9500b57cec5SDimitry Andric } 9510b57cec5SDimitry Andric } 9520b57cec5SDimitry Andric 9530b57cec5SDimitry Andric void handleUnlock(FactSet &FSet, FactManager &FactMan, 9540b57cec5SDimitry Andric const CapabilityExpr &Cp, SourceLocation UnlockLoc, 9550b57cec5SDimitry Andric bool FullyRemove, ThreadSafetyHandler &Handler, 9560b57cec5SDimitry Andric StringRef DiagKind) const override { 9570b57cec5SDimitry Andric assert(!Cp.negative() && "Managing object cannot be negative."); 9580b57cec5SDimitry Andric for (const auto &UnderlyingMutex : UnderlyingMutexes) { 9590b57cec5SDimitry Andric CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false); 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric // Remove/lock the underlying mutex if it exists/is still unlocked; warn 9620b57cec5SDimitry Andric // on double unlocking/locking if we're not destroying the scoped object. 9630b57cec5SDimitry Andric ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler; 9640b57cec5SDimitry Andric if (UnderlyingMutex.getInt() == UCK_Acquired) { 9650b57cec5SDimitry Andric unlock(FSet, FactMan, UnderCp, UnlockLoc, TSHandler, DiagKind); 9660b57cec5SDimitry Andric } else { 9670b57cec5SDimitry Andric LockKind kind = UnderlyingMutex.getInt() == UCK_ReleasedShared 9680b57cec5SDimitry Andric ? LK_Shared 9690b57cec5SDimitry Andric : LK_Exclusive; 9700b57cec5SDimitry Andric lock(FSet, FactMan, UnderCp, kind, UnlockLoc, TSHandler, DiagKind); 9710b57cec5SDimitry Andric } 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric if (FullyRemove) 9740b57cec5SDimitry Andric FSet.removeLock(FactMan, Cp); 9750b57cec5SDimitry Andric } 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric private: 9780b57cec5SDimitry Andric void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp, 9790b57cec5SDimitry Andric LockKind kind, SourceLocation loc, ThreadSafetyHandler *Handler, 9800b57cec5SDimitry Andric StringRef DiagKind) const { 9810b57cec5SDimitry Andric if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) { 9820b57cec5SDimitry Andric if (Handler) 9830b57cec5SDimitry Andric Handler->handleDoubleLock(DiagKind, Cp.toString(), Fact->loc(), loc); 9840b57cec5SDimitry Andric } else { 9850b57cec5SDimitry Andric FSet.removeLock(FactMan, !Cp); 9860b57cec5SDimitry Andric FSet.addLock(FactMan, 987fe6060f1SDimitry Andric std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed)); 9880b57cec5SDimitry Andric } 9890b57cec5SDimitry Andric } 9900b57cec5SDimitry Andric 9910b57cec5SDimitry Andric void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp, 9920b57cec5SDimitry Andric SourceLocation loc, ThreadSafetyHandler *Handler, 9930b57cec5SDimitry Andric StringRef DiagKind) const { 9940b57cec5SDimitry Andric if (FSet.findLock(FactMan, Cp)) { 9950b57cec5SDimitry Andric FSet.removeLock(FactMan, Cp); 996a7dea167SDimitry Andric FSet.addLock(FactMan, std::make_unique<LockableFactEntry>( 9970b57cec5SDimitry Andric !Cp, LK_Exclusive, loc)); 9980b57cec5SDimitry Andric } else if (Handler) { 9995ffd83dbSDimitry Andric SourceLocation PrevLoc; 10005ffd83dbSDimitry Andric if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp)) 10015ffd83dbSDimitry Andric PrevLoc = Neg->loc(); 10025ffd83dbSDimitry Andric Handler->handleUnmatchedUnlock(DiagKind, Cp.toString(), loc, PrevLoc); 10030b57cec5SDimitry Andric } 10040b57cec5SDimitry Andric } 10050b57cec5SDimitry Andric }; 10060b57cec5SDimitry Andric 10070b57cec5SDimitry Andric /// Class which implements the core thread safety analysis routines. 10080b57cec5SDimitry Andric class ThreadSafetyAnalyzer { 10090b57cec5SDimitry Andric friend class BuildLockset; 10100b57cec5SDimitry Andric friend class threadSafety::BeforeSet; 10110b57cec5SDimitry Andric 10120b57cec5SDimitry Andric llvm::BumpPtrAllocator Bpa; 10130b57cec5SDimitry Andric threadSafety::til::MemRegionRef Arena; 10140b57cec5SDimitry Andric threadSafety::SExprBuilder SxBuilder; 10150b57cec5SDimitry Andric 10160b57cec5SDimitry Andric ThreadSafetyHandler &Handler; 10170b57cec5SDimitry Andric const CXXMethodDecl *CurrentMethod; 10180b57cec5SDimitry Andric LocalVariableMap LocalVarMap; 10190b57cec5SDimitry Andric FactManager FactMan; 10200b57cec5SDimitry Andric std::vector<CFGBlockInfo> BlockInfo; 10210b57cec5SDimitry Andric 10220b57cec5SDimitry Andric BeforeSet *GlobalBeforeSet; 10230b57cec5SDimitry Andric 10240b57cec5SDimitry Andric public: 10250b57cec5SDimitry Andric ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset) 10260b57cec5SDimitry Andric : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {} 10270b57cec5SDimitry Andric 10280b57cec5SDimitry Andric bool inCurrentScope(const CapabilityExpr &CapE); 10290b57cec5SDimitry Andric 10300b57cec5SDimitry Andric void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry, 10310b57cec5SDimitry Andric StringRef DiagKind, bool ReqAttr = false); 10320b57cec5SDimitry Andric void removeLock(FactSet &FSet, const CapabilityExpr &CapE, 10330b57cec5SDimitry Andric SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind, 10340b57cec5SDimitry Andric StringRef DiagKind); 10350b57cec5SDimitry Andric 10360b57cec5SDimitry Andric template <typename AttrType> 10370b57cec5SDimitry Andric void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp, 10380b57cec5SDimitry Andric const NamedDecl *D, VarDecl *SelfDecl = nullptr); 10390b57cec5SDimitry Andric 10400b57cec5SDimitry Andric template <class AttrType> 10410b57cec5SDimitry Andric void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp, 10420b57cec5SDimitry Andric const NamedDecl *D, 10430b57cec5SDimitry Andric const CFGBlock *PredBlock, const CFGBlock *CurrBlock, 10440b57cec5SDimitry Andric Expr *BrE, bool Neg); 10450b57cec5SDimitry Andric 10460b57cec5SDimitry Andric const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C, 10470b57cec5SDimitry Andric bool &Negate); 10480b57cec5SDimitry Andric 10490b57cec5SDimitry Andric void getEdgeLockset(FactSet &Result, const FactSet &ExitSet, 10500b57cec5SDimitry Andric const CFGBlock* PredBlock, 10510b57cec5SDimitry Andric const CFGBlock *CurrBlock); 10520b57cec5SDimitry Andric 1053*28a41182SDimitry Andric bool join(const FactEntry &a, const FactEntry &b, bool CanModify); 10540b57cec5SDimitry Andric 1055fe6060f1SDimitry Andric void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet, 1056fe6060f1SDimitry Andric SourceLocation JoinLoc, LockErrorKind EntryLEK, 1057fe6060f1SDimitry Andric LockErrorKind ExitLEK); 1058fe6060f1SDimitry Andric 1059fe6060f1SDimitry Andric void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet, 1060fe6060f1SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK) { 1061fe6060f1SDimitry Andric intersectAndWarn(EntrySet, ExitSet, JoinLoc, LEK, LEK); 10620b57cec5SDimitry Andric } 10630b57cec5SDimitry Andric 10640b57cec5SDimitry Andric void runAnalysis(AnalysisDeclContext &AC); 10650b57cec5SDimitry Andric }; 10660b57cec5SDimitry Andric 10670b57cec5SDimitry Andric } // namespace 10680b57cec5SDimitry Andric 10690b57cec5SDimitry Andric /// Process acquired_before and acquired_after attributes on Vd. 10700b57cec5SDimitry Andric BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd, 10710b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer) { 10720b57cec5SDimitry Andric // Create a new entry for Vd. 10730b57cec5SDimitry Andric BeforeInfo *Info = nullptr; 10740b57cec5SDimitry Andric { 10750b57cec5SDimitry Andric // Keep InfoPtr in its own scope in case BMap is modified later and the 10760b57cec5SDimitry Andric // reference becomes invalid. 10770b57cec5SDimitry Andric std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd]; 10780b57cec5SDimitry Andric if (!InfoPtr) 10790b57cec5SDimitry Andric InfoPtr.reset(new BeforeInfo()); 10800b57cec5SDimitry Andric Info = InfoPtr.get(); 10810b57cec5SDimitry Andric } 10820b57cec5SDimitry Andric 10830b57cec5SDimitry Andric for (const auto *At : Vd->attrs()) { 10840b57cec5SDimitry Andric switch (At->getKind()) { 10850b57cec5SDimitry Andric case attr::AcquiredBefore: { 10860b57cec5SDimitry Andric const auto *A = cast<AcquiredBeforeAttr>(At); 10870b57cec5SDimitry Andric 10880b57cec5SDimitry Andric // Read exprs from the attribute, and add them to BeforeVect. 10890b57cec5SDimitry Andric for (const auto *Arg : A->args()) { 10900b57cec5SDimitry Andric CapabilityExpr Cp = 10910b57cec5SDimitry Andric Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr); 10920b57cec5SDimitry Andric if (const ValueDecl *Cpvd = Cp.valueDecl()) { 10930b57cec5SDimitry Andric Info->Vect.push_back(Cpvd); 10940b57cec5SDimitry Andric const auto It = BMap.find(Cpvd); 10950b57cec5SDimitry Andric if (It == BMap.end()) 10960b57cec5SDimitry Andric insertAttrExprs(Cpvd, Analyzer); 10970b57cec5SDimitry Andric } 10980b57cec5SDimitry Andric } 10990b57cec5SDimitry Andric break; 11000b57cec5SDimitry Andric } 11010b57cec5SDimitry Andric case attr::AcquiredAfter: { 11020b57cec5SDimitry Andric const auto *A = cast<AcquiredAfterAttr>(At); 11030b57cec5SDimitry Andric 11040b57cec5SDimitry Andric // Read exprs from the attribute, and add them to BeforeVect. 11050b57cec5SDimitry Andric for (const auto *Arg : A->args()) { 11060b57cec5SDimitry Andric CapabilityExpr Cp = 11070b57cec5SDimitry Andric Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr); 11080b57cec5SDimitry Andric if (const ValueDecl *ArgVd = Cp.valueDecl()) { 11090b57cec5SDimitry Andric // Get entry for mutex listed in attribute 11100b57cec5SDimitry Andric BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer); 11110b57cec5SDimitry Andric ArgInfo->Vect.push_back(Vd); 11120b57cec5SDimitry Andric } 11130b57cec5SDimitry Andric } 11140b57cec5SDimitry Andric break; 11150b57cec5SDimitry Andric } 11160b57cec5SDimitry Andric default: 11170b57cec5SDimitry Andric break; 11180b57cec5SDimitry Andric } 11190b57cec5SDimitry Andric } 11200b57cec5SDimitry Andric 11210b57cec5SDimitry Andric return Info; 11220b57cec5SDimitry Andric } 11230b57cec5SDimitry Andric 11240b57cec5SDimitry Andric BeforeSet::BeforeInfo * 11250b57cec5SDimitry Andric BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd, 11260b57cec5SDimitry Andric ThreadSafetyAnalyzer &Analyzer) { 11270b57cec5SDimitry Andric auto It = BMap.find(Vd); 11280b57cec5SDimitry Andric BeforeInfo *Info = nullptr; 11290b57cec5SDimitry Andric if (It == BMap.end()) 11300b57cec5SDimitry Andric Info = insertAttrExprs(Vd, Analyzer); 11310b57cec5SDimitry Andric else 11320b57cec5SDimitry Andric Info = It->second.get(); 11330b57cec5SDimitry Andric assert(Info && "BMap contained nullptr?"); 11340b57cec5SDimitry Andric return Info; 11350b57cec5SDimitry Andric } 11360b57cec5SDimitry Andric 11370b57cec5SDimitry Andric /// Return true if any mutexes in FSet are in the acquired_before set of Vd. 11380b57cec5SDimitry Andric void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd, 11390b57cec5SDimitry Andric const FactSet& FSet, 11400b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer, 11410b57cec5SDimitry Andric SourceLocation Loc, StringRef CapKind) { 11420b57cec5SDimitry Andric SmallVector<BeforeInfo*, 8> InfoVect; 11430b57cec5SDimitry Andric 11440b57cec5SDimitry Andric // Do a depth-first traversal of Vd. 11450b57cec5SDimitry Andric // Return true if there are cycles. 11460b57cec5SDimitry Andric std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) { 11470b57cec5SDimitry Andric if (!Vd) 11480b57cec5SDimitry Andric return false; 11490b57cec5SDimitry Andric 11500b57cec5SDimitry Andric BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer); 11510b57cec5SDimitry Andric 11520b57cec5SDimitry Andric if (Info->Visited == 1) 11530b57cec5SDimitry Andric return true; 11540b57cec5SDimitry Andric 11550b57cec5SDimitry Andric if (Info->Visited == 2) 11560b57cec5SDimitry Andric return false; 11570b57cec5SDimitry Andric 11580b57cec5SDimitry Andric if (Info->Vect.empty()) 11590b57cec5SDimitry Andric return false; 11600b57cec5SDimitry Andric 11610b57cec5SDimitry Andric InfoVect.push_back(Info); 11620b57cec5SDimitry Andric Info->Visited = 1; 11630b57cec5SDimitry Andric for (const auto *Vdb : Info->Vect) { 11640b57cec5SDimitry Andric // Exclude mutexes in our immediate before set. 11650b57cec5SDimitry Andric if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) { 11660b57cec5SDimitry Andric StringRef L1 = StartVd->getName(); 11670b57cec5SDimitry Andric StringRef L2 = Vdb->getName(); 11680b57cec5SDimitry Andric Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc); 11690b57cec5SDimitry Andric } 11700b57cec5SDimitry Andric // Transitively search other before sets, and warn on cycles. 11710b57cec5SDimitry Andric if (traverse(Vdb)) { 11720b57cec5SDimitry Andric if (CycMap.find(Vd) == CycMap.end()) { 11730b57cec5SDimitry Andric CycMap.insert(std::make_pair(Vd, true)); 11740b57cec5SDimitry Andric StringRef L1 = Vd->getName(); 11750b57cec5SDimitry Andric Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation()); 11760b57cec5SDimitry Andric } 11770b57cec5SDimitry Andric } 11780b57cec5SDimitry Andric } 11790b57cec5SDimitry Andric Info->Visited = 2; 11800b57cec5SDimitry Andric return false; 11810b57cec5SDimitry Andric }; 11820b57cec5SDimitry Andric 11830b57cec5SDimitry Andric traverse(StartVd); 11840b57cec5SDimitry Andric 11850b57cec5SDimitry Andric for (auto *Info : InfoVect) 11860b57cec5SDimitry Andric Info->Visited = 0; 11870b57cec5SDimitry Andric } 11880b57cec5SDimitry Andric 11890b57cec5SDimitry Andric /// Gets the value decl pointer from DeclRefExprs or MemberExprs. 11900b57cec5SDimitry Andric static const ValueDecl *getValueDecl(const Expr *Exp) { 11910b57cec5SDimitry Andric if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp)) 11920b57cec5SDimitry Andric return getValueDecl(CE->getSubExpr()); 11930b57cec5SDimitry Andric 11940b57cec5SDimitry Andric if (const auto *DR = dyn_cast<DeclRefExpr>(Exp)) 11950b57cec5SDimitry Andric return DR->getDecl(); 11960b57cec5SDimitry Andric 11970b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(Exp)) 11980b57cec5SDimitry Andric return ME->getMemberDecl(); 11990b57cec5SDimitry Andric 12000b57cec5SDimitry Andric return nullptr; 12010b57cec5SDimitry Andric } 12020b57cec5SDimitry Andric 12030b57cec5SDimitry Andric namespace { 12040b57cec5SDimitry Andric 12050b57cec5SDimitry Andric template <typename Ty> 12060b57cec5SDimitry Andric class has_arg_iterator_range { 12070b57cec5SDimitry Andric using yes = char[1]; 12080b57cec5SDimitry Andric using no = char[2]; 12090b57cec5SDimitry Andric 12100b57cec5SDimitry Andric template <typename Inner> 12110b57cec5SDimitry Andric static yes& test(Inner *I, decltype(I->args()) * = nullptr); 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric template <typename> 12140b57cec5SDimitry Andric static no& test(...); 12150b57cec5SDimitry Andric 12160b57cec5SDimitry Andric public: 12170b57cec5SDimitry Andric static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); 12180b57cec5SDimitry Andric }; 12190b57cec5SDimitry Andric 12200b57cec5SDimitry Andric } // namespace 12210b57cec5SDimitry Andric 12220b57cec5SDimitry Andric static StringRef ClassifyDiagnostic(const CapabilityAttr *A) { 12230b57cec5SDimitry Andric return A->getName(); 12240b57cec5SDimitry Andric } 12250b57cec5SDimitry Andric 12260b57cec5SDimitry Andric static StringRef ClassifyDiagnostic(QualType VDT) { 12270b57cec5SDimitry Andric // We need to look at the declaration of the type of the value to determine 12280b57cec5SDimitry Andric // which it is. The type should either be a record or a typedef, or a pointer 12290b57cec5SDimitry Andric // or reference thereof. 12300b57cec5SDimitry Andric if (const auto *RT = VDT->getAs<RecordType>()) { 12310b57cec5SDimitry Andric if (const auto *RD = RT->getDecl()) 12320b57cec5SDimitry Andric if (const auto *CA = RD->getAttr<CapabilityAttr>()) 12330b57cec5SDimitry Andric return ClassifyDiagnostic(CA); 12340b57cec5SDimitry Andric } else if (const auto *TT = VDT->getAs<TypedefType>()) { 12350b57cec5SDimitry Andric if (const auto *TD = TT->getDecl()) 12360b57cec5SDimitry Andric if (const auto *CA = TD->getAttr<CapabilityAttr>()) 12370b57cec5SDimitry Andric return ClassifyDiagnostic(CA); 12380b57cec5SDimitry Andric } else if (VDT->isPointerType() || VDT->isReferenceType()) 12390b57cec5SDimitry Andric return ClassifyDiagnostic(VDT->getPointeeType()); 12400b57cec5SDimitry Andric 12410b57cec5SDimitry Andric return "mutex"; 12420b57cec5SDimitry Andric } 12430b57cec5SDimitry Andric 12440b57cec5SDimitry Andric static StringRef ClassifyDiagnostic(const ValueDecl *VD) { 12450b57cec5SDimitry Andric assert(VD && "No ValueDecl passed"); 12460b57cec5SDimitry Andric 12470b57cec5SDimitry Andric // The ValueDecl is the declaration of a mutex or role (hopefully). 12480b57cec5SDimitry Andric return ClassifyDiagnostic(VD->getType()); 12490b57cec5SDimitry Andric } 12500b57cec5SDimitry Andric 12510b57cec5SDimitry Andric template <typename AttrTy> 12525ffd83dbSDimitry Andric static std::enable_if_t<!has_arg_iterator_range<AttrTy>::value, StringRef> 12530b57cec5SDimitry Andric ClassifyDiagnostic(const AttrTy *A) { 12540b57cec5SDimitry Andric if (const ValueDecl *VD = getValueDecl(A->getArg())) 12550b57cec5SDimitry Andric return ClassifyDiagnostic(VD); 12560b57cec5SDimitry Andric return "mutex"; 12570b57cec5SDimitry Andric } 12580b57cec5SDimitry Andric 12590b57cec5SDimitry Andric template <typename AttrTy> 12605ffd83dbSDimitry Andric static std::enable_if_t<has_arg_iterator_range<AttrTy>::value, StringRef> 12610b57cec5SDimitry Andric ClassifyDiagnostic(const AttrTy *A) { 12620b57cec5SDimitry Andric for (const auto *Arg : A->args()) { 12630b57cec5SDimitry Andric if (const ValueDecl *VD = getValueDecl(Arg)) 12640b57cec5SDimitry Andric return ClassifyDiagnostic(VD); 12650b57cec5SDimitry Andric } 12660b57cec5SDimitry Andric return "mutex"; 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric 12690b57cec5SDimitry Andric bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) { 1270e8d8bef9SDimitry Andric const threadSafety::til::SExpr *SExp = CapE.sexpr(); 1271e8d8bef9SDimitry Andric assert(SExp && "Null expressions should be ignored"); 1272e8d8bef9SDimitry Andric 1273e8d8bef9SDimitry Andric if (const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) { 1274e8d8bef9SDimitry Andric const ValueDecl *VD = LP->clangDecl(); 1275e8d8bef9SDimitry Andric // Variables defined in a function are always inaccessible. 1276e8d8bef9SDimitry Andric if (!VD->isDefinedOutsideFunctionOrMethod()) 1277e8d8bef9SDimitry Andric return false; 1278e8d8bef9SDimitry Andric // For now we consider static class members to be inaccessible. 1279e8d8bef9SDimitry Andric if (isa<CXXRecordDecl>(VD->getDeclContext())) 1280e8d8bef9SDimitry Andric return false; 1281e8d8bef9SDimitry Andric // Global variables are always in scope. 1282e8d8bef9SDimitry Andric return true; 1283e8d8bef9SDimitry Andric } 1284e8d8bef9SDimitry Andric 1285e8d8bef9SDimitry Andric // Members are in scope from methods of the same class. 1286e8d8bef9SDimitry Andric if (const auto *P = dyn_cast<til::Project>(SExp)) { 12870b57cec5SDimitry Andric if (!CurrentMethod) 12880b57cec5SDimitry Andric return false; 1289e8d8bef9SDimitry Andric const ValueDecl *VD = P->clangDecl(); 12900b57cec5SDimitry Andric return VD->getDeclContext() == CurrentMethod->getDeclContext(); 12910b57cec5SDimitry Andric } 1292e8d8bef9SDimitry Andric 12930b57cec5SDimitry Andric return false; 12940b57cec5SDimitry Andric } 12950b57cec5SDimitry Andric 12960b57cec5SDimitry Andric /// Add a new lock to the lockset, warning if the lock is already there. 12970b57cec5SDimitry Andric /// \param ReqAttr -- true if this is part of an initial Requires attribute. 12980b57cec5SDimitry Andric void ThreadSafetyAnalyzer::addLock(FactSet &FSet, 12990b57cec5SDimitry Andric std::unique_ptr<FactEntry> Entry, 13000b57cec5SDimitry Andric StringRef DiagKind, bool ReqAttr) { 13010b57cec5SDimitry Andric if (Entry->shouldIgnore()) 13020b57cec5SDimitry Andric return; 13030b57cec5SDimitry Andric 13040b57cec5SDimitry Andric if (!ReqAttr && !Entry->negative()) { 13050b57cec5SDimitry Andric // look for the negative capability, and remove it from the fact set. 13060b57cec5SDimitry Andric CapabilityExpr NegC = !*Entry; 13070b57cec5SDimitry Andric const FactEntry *Nen = FSet.findLock(FactMan, NegC); 13080b57cec5SDimitry Andric if (Nen) { 13090b57cec5SDimitry Andric FSet.removeLock(FactMan, NegC); 13100b57cec5SDimitry Andric } 13110b57cec5SDimitry Andric else { 13120b57cec5SDimitry Andric if (inCurrentScope(*Entry) && !Entry->asserted()) 13130b57cec5SDimitry Andric Handler.handleNegativeNotHeld(DiagKind, Entry->toString(), 13140b57cec5SDimitry Andric NegC.toString(), Entry->loc()); 13150b57cec5SDimitry Andric } 13160b57cec5SDimitry Andric } 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric // Check before/after constraints 13190b57cec5SDimitry Andric if (Handler.issueBetaWarnings() && 13200b57cec5SDimitry Andric !Entry->asserted() && !Entry->declared()) { 13210b57cec5SDimitry Andric GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this, 13220b57cec5SDimitry Andric Entry->loc(), DiagKind); 13230b57cec5SDimitry Andric } 13240b57cec5SDimitry Andric 13250b57cec5SDimitry Andric // FIXME: Don't always warn when we have support for reentrant locks. 13260b57cec5SDimitry Andric if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) { 13270b57cec5SDimitry Andric if (!Entry->asserted()) 13280b57cec5SDimitry Andric Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind); 13290b57cec5SDimitry Andric } else { 13300b57cec5SDimitry Andric FSet.addLock(FactMan, std::move(Entry)); 13310b57cec5SDimitry Andric } 13320b57cec5SDimitry Andric } 13330b57cec5SDimitry Andric 13340b57cec5SDimitry Andric /// Remove a lock from the lockset, warning if the lock is not there. 13350b57cec5SDimitry Andric /// \param UnlockLoc The source location of the unlock (only used in error msg) 13360b57cec5SDimitry Andric void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp, 13370b57cec5SDimitry Andric SourceLocation UnlockLoc, 13380b57cec5SDimitry Andric bool FullyRemove, LockKind ReceivedKind, 13390b57cec5SDimitry Andric StringRef DiagKind) { 13400b57cec5SDimitry Andric if (Cp.shouldIgnore()) 13410b57cec5SDimitry Andric return; 13420b57cec5SDimitry Andric 13430b57cec5SDimitry Andric const FactEntry *LDat = FSet.findLock(FactMan, Cp); 13440b57cec5SDimitry Andric if (!LDat) { 13455ffd83dbSDimitry Andric SourceLocation PrevLoc; 13465ffd83dbSDimitry Andric if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp)) 13475ffd83dbSDimitry Andric PrevLoc = Neg->loc(); 13485ffd83dbSDimitry Andric Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc, PrevLoc); 13490b57cec5SDimitry Andric return; 13500b57cec5SDimitry Andric } 13510b57cec5SDimitry Andric 13520b57cec5SDimitry Andric // Generic lock removal doesn't care about lock kind mismatches, but 13530b57cec5SDimitry Andric // otherwise diagnose when the lock kinds are mismatched. 13540b57cec5SDimitry Andric if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) { 13550b57cec5SDimitry Andric Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(), LDat->kind(), 13560b57cec5SDimitry Andric ReceivedKind, LDat->loc(), UnlockLoc); 13570b57cec5SDimitry Andric } 13580b57cec5SDimitry Andric 13590b57cec5SDimitry Andric LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler, 13600b57cec5SDimitry Andric DiagKind); 13610b57cec5SDimitry Andric } 13620b57cec5SDimitry Andric 13630b57cec5SDimitry Andric /// Extract the list of mutexIDs from the attribute on an expression, 13640b57cec5SDimitry Andric /// and push them onto Mtxs, discarding any duplicates. 13650b57cec5SDimitry Andric template <typename AttrType> 13660b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, 13670b57cec5SDimitry Andric const Expr *Exp, const NamedDecl *D, 13680b57cec5SDimitry Andric VarDecl *SelfDecl) { 13690b57cec5SDimitry Andric if (Attr->args_size() == 0) { 13700b57cec5SDimitry Andric // The mutex held is the "this" object. 13710b57cec5SDimitry Andric CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl); 13720b57cec5SDimitry Andric if (Cp.isInvalid()) { 13730b57cec5SDimitry Andric warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr)); 13740b57cec5SDimitry Andric return; 13750b57cec5SDimitry Andric } 13760b57cec5SDimitry Andric //else 13770b57cec5SDimitry Andric if (!Cp.shouldIgnore()) 13780b57cec5SDimitry Andric Mtxs.push_back_nodup(Cp); 13790b57cec5SDimitry Andric return; 13800b57cec5SDimitry Andric } 13810b57cec5SDimitry Andric 13820b57cec5SDimitry Andric for (const auto *Arg : Attr->args()) { 13830b57cec5SDimitry Andric CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl); 13840b57cec5SDimitry Andric if (Cp.isInvalid()) { 13850b57cec5SDimitry Andric warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr)); 13860b57cec5SDimitry Andric continue; 13870b57cec5SDimitry Andric } 13880b57cec5SDimitry Andric //else 13890b57cec5SDimitry Andric if (!Cp.shouldIgnore()) 13900b57cec5SDimitry Andric Mtxs.push_back_nodup(Cp); 13910b57cec5SDimitry Andric } 13920b57cec5SDimitry Andric } 13930b57cec5SDimitry Andric 13940b57cec5SDimitry Andric /// Extract the list of mutexIDs from a trylock attribute. If the 13950b57cec5SDimitry Andric /// trylock applies to the given edge, then push them onto Mtxs, discarding 13960b57cec5SDimitry Andric /// any duplicates. 13970b57cec5SDimitry Andric template <class AttrType> 13980b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, 13990b57cec5SDimitry Andric const Expr *Exp, const NamedDecl *D, 14000b57cec5SDimitry Andric const CFGBlock *PredBlock, 14010b57cec5SDimitry Andric const CFGBlock *CurrBlock, 14020b57cec5SDimitry Andric Expr *BrE, bool Neg) { 14030b57cec5SDimitry Andric // Find out which branch has the lock 14040b57cec5SDimitry Andric bool branch = false; 14050b57cec5SDimitry Andric if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) 14060b57cec5SDimitry Andric branch = BLE->getValue(); 14070b57cec5SDimitry Andric else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) 14080b57cec5SDimitry Andric branch = ILE->getValue().getBoolValue(); 14090b57cec5SDimitry Andric 14100b57cec5SDimitry Andric int branchnum = branch ? 0 : 1; 14110b57cec5SDimitry Andric if (Neg) 14120b57cec5SDimitry Andric branchnum = !branchnum; 14130b57cec5SDimitry Andric 14140b57cec5SDimitry Andric // If we've taken the trylock branch, then add the lock 14150b57cec5SDimitry Andric int i = 0; 14160b57cec5SDimitry Andric for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(), 14170b57cec5SDimitry Andric SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) { 14180b57cec5SDimitry Andric if (*SI == CurrBlock && i == branchnum) 14190b57cec5SDimitry Andric getMutexIDs(Mtxs, Attr, Exp, D); 14200b57cec5SDimitry Andric } 14210b57cec5SDimitry Andric } 14220b57cec5SDimitry Andric 14230b57cec5SDimitry Andric static bool getStaticBooleanValue(Expr *E, bool &TCond) { 14240b57cec5SDimitry Andric if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) { 14250b57cec5SDimitry Andric TCond = false; 14260b57cec5SDimitry Andric return true; 14270b57cec5SDimitry Andric } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) { 14280b57cec5SDimitry Andric TCond = BLE->getValue(); 14290b57cec5SDimitry Andric return true; 14300b57cec5SDimitry Andric } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) { 14310b57cec5SDimitry Andric TCond = ILE->getValue().getBoolValue(); 14320b57cec5SDimitry Andric return true; 14330b57cec5SDimitry Andric } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E)) 14340b57cec5SDimitry Andric return getStaticBooleanValue(CE->getSubExpr(), TCond); 14350b57cec5SDimitry Andric return false; 14360b57cec5SDimitry Andric } 14370b57cec5SDimitry Andric 14380b57cec5SDimitry Andric // If Cond can be traced back to a function call, return the call expression. 14390b57cec5SDimitry Andric // The negate variable should be called with false, and will be set to true 14400b57cec5SDimitry Andric // if the function call is negated, e.g. if (!mu.tryLock(...)) 14410b57cec5SDimitry Andric const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond, 14420b57cec5SDimitry Andric LocalVarContext C, 14430b57cec5SDimitry Andric bool &Negate) { 14440b57cec5SDimitry Andric if (!Cond) 14450b57cec5SDimitry Andric return nullptr; 14460b57cec5SDimitry Andric 14470b57cec5SDimitry Andric if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) { 14480b57cec5SDimitry Andric if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect) 14490b57cec5SDimitry Andric return getTrylockCallExpr(CallExp->getArg(0), C, Negate); 14500b57cec5SDimitry Andric return CallExp; 14510b57cec5SDimitry Andric } 14520b57cec5SDimitry Andric else if (const auto *PE = dyn_cast<ParenExpr>(Cond)) 14530b57cec5SDimitry Andric return getTrylockCallExpr(PE->getSubExpr(), C, Negate); 14540b57cec5SDimitry Andric else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond)) 14550b57cec5SDimitry Andric return getTrylockCallExpr(CE->getSubExpr(), C, Negate); 14560b57cec5SDimitry Andric else if (const auto *FE = dyn_cast<FullExpr>(Cond)) 14570b57cec5SDimitry Andric return getTrylockCallExpr(FE->getSubExpr(), C, Negate); 14580b57cec5SDimitry Andric else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) { 14590b57cec5SDimitry Andric const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C); 14600b57cec5SDimitry Andric return getTrylockCallExpr(E, C, Negate); 14610b57cec5SDimitry Andric } 14620b57cec5SDimitry Andric else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) { 14630b57cec5SDimitry Andric if (UOP->getOpcode() == UO_LNot) { 14640b57cec5SDimitry Andric Negate = !Negate; 14650b57cec5SDimitry Andric return getTrylockCallExpr(UOP->getSubExpr(), C, Negate); 14660b57cec5SDimitry Andric } 14670b57cec5SDimitry Andric return nullptr; 14680b57cec5SDimitry Andric } 14690b57cec5SDimitry Andric else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) { 14700b57cec5SDimitry Andric if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) { 14710b57cec5SDimitry Andric if (BOP->getOpcode() == BO_NE) 14720b57cec5SDimitry Andric Negate = !Negate; 14730b57cec5SDimitry Andric 14740b57cec5SDimitry Andric bool TCond = false; 14750b57cec5SDimitry Andric if (getStaticBooleanValue(BOP->getRHS(), TCond)) { 14760b57cec5SDimitry Andric if (!TCond) Negate = !Negate; 14770b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getLHS(), C, Negate); 14780b57cec5SDimitry Andric } 14790b57cec5SDimitry Andric TCond = false; 14800b57cec5SDimitry Andric if (getStaticBooleanValue(BOP->getLHS(), TCond)) { 14810b57cec5SDimitry Andric if (!TCond) Negate = !Negate; 14820b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getRHS(), C, Negate); 14830b57cec5SDimitry Andric } 14840b57cec5SDimitry Andric return nullptr; 14850b57cec5SDimitry Andric } 14860b57cec5SDimitry Andric if (BOP->getOpcode() == BO_LAnd) { 14870b57cec5SDimitry Andric // LHS must have been evaluated in a different block. 14880b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getRHS(), C, Negate); 14890b57cec5SDimitry Andric } 14900b57cec5SDimitry Andric if (BOP->getOpcode() == BO_LOr) 14910b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getRHS(), C, Negate); 14920b57cec5SDimitry Andric return nullptr; 14930b57cec5SDimitry Andric } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) { 14940b57cec5SDimitry Andric bool TCond, FCond; 14950b57cec5SDimitry Andric if (getStaticBooleanValue(COP->getTrueExpr(), TCond) && 14960b57cec5SDimitry Andric getStaticBooleanValue(COP->getFalseExpr(), FCond)) { 14970b57cec5SDimitry Andric if (TCond && !FCond) 14980b57cec5SDimitry Andric return getTrylockCallExpr(COP->getCond(), C, Negate); 14990b57cec5SDimitry Andric if (!TCond && FCond) { 15000b57cec5SDimitry Andric Negate = !Negate; 15010b57cec5SDimitry Andric return getTrylockCallExpr(COP->getCond(), C, Negate); 15020b57cec5SDimitry Andric } 15030b57cec5SDimitry Andric } 15040b57cec5SDimitry Andric } 15050b57cec5SDimitry Andric return nullptr; 15060b57cec5SDimitry Andric } 15070b57cec5SDimitry Andric 15080b57cec5SDimitry Andric /// Find the lockset that holds on the edge between PredBlock 15090b57cec5SDimitry Andric /// and CurrBlock. The edge set is the exit set of PredBlock (passed 15100b57cec5SDimitry Andric /// as the ExitSet parameter) plus any trylocks, which are conditionally held. 15110b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result, 15120b57cec5SDimitry Andric const FactSet &ExitSet, 15130b57cec5SDimitry Andric const CFGBlock *PredBlock, 15140b57cec5SDimitry Andric const CFGBlock *CurrBlock) { 15150b57cec5SDimitry Andric Result = ExitSet; 15160b57cec5SDimitry Andric 15170b57cec5SDimitry Andric const Stmt *Cond = PredBlock->getTerminatorCondition(); 15180b57cec5SDimitry Andric // We don't acquire try-locks on ?: branches, only when its result is used. 15190b57cec5SDimitry Andric if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminatorStmt())) 15200b57cec5SDimitry Andric return; 15210b57cec5SDimitry Andric 15220b57cec5SDimitry Andric bool Negate = false; 15230b57cec5SDimitry Andric const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()]; 15240b57cec5SDimitry Andric const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext; 15250b57cec5SDimitry Andric StringRef CapDiagKind = "mutex"; 15260b57cec5SDimitry Andric 15270b57cec5SDimitry Andric const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate); 15280b57cec5SDimitry Andric if (!Exp) 15290b57cec5SDimitry Andric return; 15300b57cec5SDimitry Andric 15310b57cec5SDimitry Andric auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 15320b57cec5SDimitry Andric if(!FunDecl || !FunDecl->hasAttrs()) 15330b57cec5SDimitry Andric return; 15340b57cec5SDimitry Andric 15350b57cec5SDimitry Andric CapExprSet ExclusiveLocksToAdd; 15360b57cec5SDimitry Andric CapExprSet SharedLocksToAdd; 15370b57cec5SDimitry Andric 15380b57cec5SDimitry Andric // If the condition is a call to a Trylock function, then grab the attributes 15390b57cec5SDimitry Andric for (const auto *Attr : FunDecl->attrs()) { 15400b57cec5SDimitry Andric switch (Attr->getKind()) { 15410b57cec5SDimitry Andric case attr::TryAcquireCapability: { 15420b57cec5SDimitry Andric auto *A = cast<TryAcquireCapabilityAttr>(Attr); 15430b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 15440b57cec5SDimitry Andric Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(), 15450b57cec5SDimitry Andric Negate); 15460b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 15470b57cec5SDimitry Andric break; 15480b57cec5SDimitry Andric }; 15490b57cec5SDimitry Andric case attr::ExclusiveTrylockFunction: { 15500b57cec5SDimitry Andric const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr); 15510b57cec5SDimitry Andric getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, 15520b57cec5SDimitry Andric PredBlock, CurrBlock, A->getSuccessValue(), Negate); 15530b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 15540b57cec5SDimitry Andric break; 15550b57cec5SDimitry Andric } 15560b57cec5SDimitry Andric case attr::SharedTrylockFunction: { 15570b57cec5SDimitry Andric const auto *A = cast<SharedTrylockFunctionAttr>(Attr); 15580b57cec5SDimitry Andric getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, 15590b57cec5SDimitry Andric PredBlock, CurrBlock, A->getSuccessValue(), Negate); 15600b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 15610b57cec5SDimitry Andric break; 15620b57cec5SDimitry Andric } 15630b57cec5SDimitry Andric default: 15640b57cec5SDimitry Andric break; 15650b57cec5SDimitry Andric } 15660b57cec5SDimitry Andric } 15670b57cec5SDimitry Andric 15680b57cec5SDimitry Andric // Add and remove locks. 15690b57cec5SDimitry Andric SourceLocation Loc = Exp->getExprLoc(); 15700b57cec5SDimitry Andric for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd) 1571a7dea167SDimitry Andric addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd, 15720b57cec5SDimitry Andric LK_Exclusive, Loc), 15730b57cec5SDimitry Andric CapDiagKind); 15740b57cec5SDimitry Andric for (const auto &SharedLockToAdd : SharedLocksToAdd) 1575a7dea167SDimitry Andric addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd, 15760b57cec5SDimitry Andric LK_Shared, Loc), 15770b57cec5SDimitry Andric CapDiagKind); 15780b57cec5SDimitry Andric } 15790b57cec5SDimitry Andric 15800b57cec5SDimitry Andric namespace { 15810b57cec5SDimitry Andric 15820b57cec5SDimitry Andric /// We use this class to visit different types of expressions in 15830b57cec5SDimitry Andric /// CFGBlocks, and build up the lockset. 15840b57cec5SDimitry Andric /// An expression may cause us to add or remove locks from the lockset, or else 15850b57cec5SDimitry Andric /// output error messages related to missing locks. 15860b57cec5SDimitry Andric /// FIXME: In future, we may be able to not inherit from a visitor. 15870b57cec5SDimitry Andric class BuildLockset : public ConstStmtVisitor<BuildLockset> { 15880b57cec5SDimitry Andric friend class ThreadSafetyAnalyzer; 15890b57cec5SDimitry Andric 15900b57cec5SDimitry Andric ThreadSafetyAnalyzer *Analyzer; 15910b57cec5SDimitry Andric FactSet FSet; 15920b57cec5SDimitry Andric LocalVariableMap::Context LVarCtx; 15930b57cec5SDimitry Andric unsigned CtxIndex; 15940b57cec5SDimitry Andric 15950b57cec5SDimitry Andric // helper functions 15960b57cec5SDimitry Andric void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK, 15970b57cec5SDimitry Andric Expr *MutexExp, ProtectedOperationKind POK, 15980b57cec5SDimitry Andric StringRef DiagKind, SourceLocation Loc); 15990b57cec5SDimitry Andric void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp, 16000b57cec5SDimitry Andric StringRef DiagKind); 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric void checkAccess(const Expr *Exp, AccessKind AK, 16030b57cec5SDimitry Andric ProtectedOperationKind POK = POK_VarAccess); 16040b57cec5SDimitry Andric void checkPtAccess(const Expr *Exp, AccessKind AK, 16050b57cec5SDimitry Andric ProtectedOperationKind POK = POK_VarAccess); 16060b57cec5SDimitry Andric 16070b57cec5SDimitry Andric void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr); 16080b57cec5SDimitry Andric void examineArguments(const FunctionDecl *FD, 16090b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgBegin, 16100b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgEnd, 16110b57cec5SDimitry Andric bool SkipFirstParam = false); 16120b57cec5SDimitry Andric 16130b57cec5SDimitry Andric public: 16140b57cec5SDimitry Andric BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info) 16150b57cec5SDimitry Andric : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet), 16160b57cec5SDimitry Andric LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {} 16170b57cec5SDimitry Andric 16180b57cec5SDimitry Andric void VisitUnaryOperator(const UnaryOperator *UO); 16190b57cec5SDimitry Andric void VisitBinaryOperator(const BinaryOperator *BO); 16200b57cec5SDimitry Andric void VisitCastExpr(const CastExpr *CE); 16210b57cec5SDimitry Andric void VisitCallExpr(const CallExpr *Exp); 16220b57cec5SDimitry Andric void VisitCXXConstructExpr(const CXXConstructExpr *Exp); 16230b57cec5SDimitry Andric void VisitDeclStmt(const DeclStmt *S); 16240b57cec5SDimitry Andric }; 16250b57cec5SDimitry Andric 16260b57cec5SDimitry Andric } // namespace 16270b57cec5SDimitry Andric 16280b57cec5SDimitry Andric /// Warn if the LSet does not contain a lock sufficient to protect access 16290b57cec5SDimitry Andric /// of at least the passed in AccessKind. 16300b57cec5SDimitry Andric void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, 16310b57cec5SDimitry Andric AccessKind AK, Expr *MutexExp, 16320b57cec5SDimitry Andric ProtectedOperationKind POK, 16330b57cec5SDimitry Andric StringRef DiagKind, SourceLocation Loc) { 16340b57cec5SDimitry Andric LockKind LK = getLockKindFromAccessKind(AK); 16350b57cec5SDimitry Andric 16360b57cec5SDimitry Andric CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp); 16370b57cec5SDimitry Andric if (Cp.isInvalid()) { 16380b57cec5SDimitry Andric warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind); 16390b57cec5SDimitry Andric return; 16400b57cec5SDimitry Andric } else if (Cp.shouldIgnore()) { 16410b57cec5SDimitry Andric return; 16420b57cec5SDimitry Andric } 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric if (Cp.negative()) { 16450b57cec5SDimitry Andric // Negative capabilities act like locks excluded 16460b57cec5SDimitry Andric const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp); 16470b57cec5SDimitry Andric if (LDat) { 16480b57cec5SDimitry Andric Analyzer->Handler.handleFunExcludesLock( 16490b57cec5SDimitry Andric DiagKind, D->getNameAsString(), (!Cp).toString(), Loc); 16500b57cec5SDimitry Andric return; 16510b57cec5SDimitry Andric } 16520b57cec5SDimitry Andric 16530b57cec5SDimitry Andric // If this does not refer to a negative capability in the same class, 16540b57cec5SDimitry Andric // then stop here. 16550b57cec5SDimitry Andric if (!Analyzer->inCurrentScope(Cp)) 16560b57cec5SDimitry Andric return; 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric // Otherwise the negative requirement must be propagated to the caller. 16590b57cec5SDimitry Andric LDat = FSet.findLock(Analyzer->FactMan, Cp); 16600b57cec5SDimitry Andric if (!LDat) { 1661e8d8bef9SDimitry Andric Analyzer->Handler.handleNegativeNotHeld(D, Cp.toString(), Loc); 16620b57cec5SDimitry Andric } 16630b57cec5SDimitry Andric return; 16640b57cec5SDimitry Andric } 16650b57cec5SDimitry Andric 16660b57cec5SDimitry Andric const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp); 16670b57cec5SDimitry Andric bool NoError = true; 16680b57cec5SDimitry Andric if (!LDat) { 16690b57cec5SDimitry Andric // No exact match found. Look for a partial match. 16700b57cec5SDimitry Andric LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp); 16710b57cec5SDimitry Andric if (LDat) { 16720b57cec5SDimitry Andric // Warn that there's no precise match. 16730b57cec5SDimitry Andric std::string PartMatchStr = LDat->toString(); 16740b57cec5SDimitry Andric StringRef PartMatchName(PartMatchStr); 16750b57cec5SDimitry Andric Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(), 16760b57cec5SDimitry Andric LK, Loc, &PartMatchName); 16770b57cec5SDimitry Andric } else { 16780b57cec5SDimitry Andric // Warn that there's no match at all. 16790b57cec5SDimitry Andric Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(), 16800b57cec5SDimitry Andric LK, Loc); 16810b57cec5SDimitry Andric } 16820b57cec5SDimitry Andric NoError = false; 16830b57cec5SDimitry Andric } 16840b57cec5SDimitry Andric // Make sure the mutex we found is the right kind. 16850b57cec5SDimitry Andric if (NoError && LDat && !LDat->isAtLeast(LK)) { 16860b57cec5SDimitry Andric Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(), 16870b57cec5SDimitry Andric LK, Loc); 16880b57cec5SDimitry Andric } 16890b57cec5SDimitry Andric } 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric /// Warn if the LSet contains the given lock. 16920b57cec5SDimitry Andric void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, 16930b57cec5SDimitry Andric Expr *MutexExp, StringRef DiagKind) { 16940b57cec5SDimitry Andric CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp); 16950b57cec5SDimitry Andric if (Cp.isInvalid()) { 16960b57cec5SDimitry Andric warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind); 16970b57cec5SDimitry Andric return; 16980b57cec5SDimitry Andric } else if (Cp.shouldIgnore()) { 16990b57cec5SDimitry Andric return; 17000b57cec5SDimitry Andric } 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp); 17030b57cec5SDimitry Andric if (LDat) { 17040b57cec5SDimitry Andric Analyzer->Handler.handleFunExcludesLock( 17050b57cec5SDimitry Andric DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc()); 17060b57cec5SDimitry Andric } 17070b57cec5SDimitry Andric } 17080b57cec5SDimitry Andric 17090b57cec5SDimitry Andric /// Checks guarded_by and pt_guarded_by attributes. 17100b57cec5SDimitry Andric /// Whenever we identify an access (read or write) to a DeclRefExpr that is 17110b57cec5SDimitry Andric /// marked with guarded_by, we must ensure the appropriate mutexes are held. 17120b57cec5SDimitry Andric /// Similarly, we check if the access is to an expression that dereferences 17130b57cec5SDimitry Andric /// a pointer marked with pt_guarded_by. 17140b57cec5SDimitry Andric void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK, 17150b57cec5SDimitry Andric ProtectedOperationKind POK) { 17160b57cec5SDimitry Andric Exp = Exp->IgnoreImplicit()->IgnoreParenCasts(); 17170b57cec5SDimitry Andric 17180b57cec5SDimitry Andric SourceLocation Loc = Exp->getExprLoc(); 17190b57cec5SDimitry Andric 17200b57cec5SDimitry Andric // Local variables of reference type cannot be re-assigned; 17210b57cec5SDimitry Andric // map them to their initializer. 17220b57cec5SDimitry Andric while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) { 17230b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl()); 17240b57cec5SDimitry Andric if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) { 17250b57cec5SDimitry Andric if (const auto *E = VD->getInit()) { 17260b57cec5SDimitry Andric // Guard against self-initialization. e.g., int &i = i; 17270b57cec5SDimitry Andric if (E == Exp) 17280b57cec5SDimitry Andric break; 17290b57cec5SDimitry Andric Exp = E; 17300b57cec5SDimitry Andric continue; 17310b57cec5SDimitry Andric } 17320b57cec5SDimitry Andric } 17330b57cec5SDimitry Andric break; 17340b57cec5SDimitry Andric } 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) { 17370b57cec5SDimitry Andric // For dereferences 17380b57cec5SDimitry Andric if (UO->getOpcode() == UO_Deref) 17390b57cec5SDimitry Andric checkPtAccess(UO->getSubExpr(), AK, POK); 17400b57cec5SDimitry Andric return; 17410b57cec5SDimitry Andric } 17420b57cec5SDimitry Andric 17430b57cec5SDimitry Andric if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) { 17440b57cec5SDimitry Andric checkPtAccess(AE->getLHS(), AK, POK); 17450b57cec5SDimitry Andric return; 17460b57cec5SDimitry Andric } 17470b57cec5SDimitry Andric 17480b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(Exp)) { 17490b57cec5SDimitry Andric if (ME->isArrow()) 17500b57cec5SDimitry Andric checkPtAccess(ME->getBase(), AK, POK); 17510b57cec5SDimitry Andric else 17520b57cec5SDimitry Andric checkAccess(ME->getBase(), AK, POK); 17530b57cec5SDimitry Andric } 17540b57cec5SDimitry Andric 17550b57cec5SDimitry Andric const ValueDecl *D = getValueDecl(Exp); 17560b57cec5SDimitry Andric if (!D || !D->hasAttrs()) 17570b57cec5SDimitry Andric return; 17580b57cec5SDimitry Andric 17590b57cec5SDimitry Andric if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) { 17600b57cec5SDimitry Andric Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc); 17610b57cec5SDimitry Andric } 17620b57cec5SDimitry Andric 17630b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<GuardedByAttr>()) 17640b57cec5SDimitry Andric warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK, 17650b57cec5SDimitry Andric ClassifyDiagnostic(I), Loc); 17660b57cec5SDimitry Andric } 17670b57cec5SDimitry Andric 17680b57cec5SDimitry Andric /// Checks pt_guarded_by and pt_guarded_var attributes. 17690b57cec5SDimitry Andric /// POK is the same operationKind that was passed to checkAccess. 17700b57cec5SDimitry Andric void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK, 17710b57cec5SDimitry Andric ProtectedOperationKind POK) { 17720b57cec5SDimitry Andric while (true) { 17730b57cec5SDimitry Andric if (const auto *PE = dyn_cast<ParenExpr>(Exp)) { 17740b57cec5SDimitry Andric Exp = PE->getSubExpr(); 17750b57cec5SDimitry Andric continue; 17760b57cec5SDimitry Andric } 17770b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Exp)) { 17780b57cec5SDimitry Andric if (CE->getCastKind() == CK_ArrayToPointerDecay) { 17790b57cec5SDimitry Andric // If it's an actual array, and not a pointer, then it's elements 17800b57cec5SDimitry Andric // are protected by GUARDED_BY, not PT_GUARDED_BY; 17810b57cec5SDimitry Andric checkAccess(CE->getSubExpr(), AK, POK); 17820b57cec5SDimitry Andric return; 17830b57cec5SDimitry Andric } 17840b57cec5SDimitry Andric Exp = CE->getSubExpr(); 17850b57cec5SDimitry Andric continue; 17860b57cec5SDimitry Andric } 17870b57cec5SDimitry Andric break; 17880b57cec5SDimitry Andric } 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric // Pass by reference warnings are under a different flag. 17910b57cec5SDimitry Andric ProtectedOperationKind PtPOK = POK_VarDereference; 17920b57cec5SDimitry Andric if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef; 17930b57cec5SDimitry Andric 17940b57cec5SDimitry Andric const ValueDecl *D = getValueDecl(Exp); 17950b57cec5SDimitry Andric if (!D || !D->hasAttrs()) 17960b57cec5SDimitry Andric return; 17970b57cec5SDimitry Andric 17980b57cec5SDimitry Andric if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) 17990b57cec5SDimitry Andric Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK, 18000b57cec5SDimitry Andric Exp->getExprLoc()); 18010b57cec5SDimitry Andric 18020b57cec5SDimitry Andric for (auto const *I : D->specific_attrs<PtGuardedByAttr>()) 18030b57cec5SDimitry Andric warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK, 18040b57cec5SDimitry Andric ClassifyDiagnostic(I), Exp->getExprLoc()); 18050b57cec5SDimitry Andric } 18060b57cec5SDimitry Andric 18070b57cec5SDimitry Andric /// Process a function call, method call, constructor call, 18080b57cec5SDimitry Andric /// or destructor call. This involves looking at the attributes on the 18090b57cec5SDimitry Andric /// corresponding function/method/constructor/destructor, issuing warnings, 18100b57cec5SDimitry Andric /// and updating the locksets accordingly. 18110b57cec5SDimitry Andric /// 18120b57cec5SDimitry Andric /// FIXME: For classes annotated with one of the guarded annotations, we need 18130b57cec5SDimitry Andric /// to treat const method calls as reads and non-const method calls as writes, 18140b57cec5SDimitry Andric /// and check that the appropriate locks are held. Non-const method calls with 18150b57cec5SDimitry Andric /// the same signature as const method calls can be also treated as reads. 18160b57cec5SDimitry Andric /// 18170b57cec5SDimitry Andric void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D, 18180b57cec5SDimitry Andric VarDecl *VD) { 18190b57cec5SDimitry Andric SourceLocation Loc = Exp->getExprLoc(); 18200b57cec5SDimitry Andric CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd; 18210b57cec5SDimitry Andric CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove; 18225ffd83dbSDimitry Andric CapExprSet ScopedReqsAndExcludes; 18230b57cec5SDimitry Andric StringRef CapDiagKind = "mutex"; 18240b57cec5SDimitry Andric 18250b57cec5SDimitry Andric // Figure out if we're constructing an object of scoped lockable class 18260b57cec5SDimitry Andric bool isScopedVar = false; 18270b57cec5SDimitry Andric if (VD) { 18280b57cec5SDimitry Andric if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) { 18290b57cec5SDimitry Andric const CXXRecordDecl* PD = CD->getParent(); 18300b57cec5SDimitry Andric if (PD && PD->hasAttr<ScopedLockableAttr>()) 18310b57cec5SDimitry Andric isScopedVar = true; 18320b57cec5SDimitry Andric } 18330b57cec5SDimitry Andric } 18340b57cec5SDimitry Andric 18350b57cec5SDimitry Andric for(const Attr *At : D->attrs()) { 18360b57cec5SDimitry Andric switch (At->getKind()) { 18370b57cec5SDimitry Andric // When we encounter a lock function, we need to add the lock to our 18380b57cec5SDimitry Andric // lockset. 18390b57cec5SDimitry Andric case attr::AcquireCapability: { 18400b57cec5SDimitry Andric const auto *A = cast<AcquireCapabilityAttr>(At); 18410b57cec5SDimitry Andric Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd 18420b57cec5SDimitry Andric : ExclusiveLocksToAdd, 18430b57cec5SDimitry Andric A, Exp, D, VD); 18440b57cec5SDimitry Andric 18450b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 18460b57cec5SDimitry Andric break; 18470b57cec5SDimitry Andric } 18480b57cec5SDimitry Andric 18490b57cec5SDimitry Andric // An assert will add a lock to the lockset, but will not generate 18500b57cec5SDimitry Andric // a warning if it is already there, and will not generate a warning 18510b57cec5SDimitry Andric // if it is not removed. 18520b57cec5SDimitry Andric case attr::AssertExclusiveLock: { 18530b57cec5SDimitry Andric const auto *A = cast<AssertExclusiveLockAttr>(At); 18540b57cec5SDimitry Andric 18550b57cec5SDimitry Andric CapExprSet AssertLocks; 18560b57cec5SDimitry Andric Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 18570b57cec5SDimitry Andric for (const auto &AssertLock : AssertLocks) 1858fe6060f1SDimitry Andric Analyzer->addLock( 1859fe6060f1SDimitry Andric FSet, 1860fe6060f1SDimitry Andric std::make_unique<LockableFactEntry>(AssertLock, LK_Exclusive, Loc, 1861fe6060f1SDimitry Andric FactEntry::Asserted), 18620b57cec5SDimitry Andric ClassifyDiagnostic(A)); 18630b57cec5SDimitry Andric break; 18640b57cec5SDimitry Andric } 18650b57cec5SDimitry Andric case attr::AssertSharedLock: { 18660b57cec5SDimitry Andric const auto *A = cast<AssertSharedLockAttr>(At); 18670b57cec5SDimitry Andric 18680b57cec5SDimitry Andric CapExprSet AssertLocks; 18690b57cec5SDimitry Andric Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 18700b57cec5SDimitry Andric for (const auto &AssertLock : AssertLocks) 1871fe6060f1SDimitry Andric Analyzer->addLock( 1872fe6060f1SDimitry Andric FSet, 1873fe6060f1SDimitry Andric std::make_unique<LockableFactEntry>(AssertLock, LK_Shared, Loc, 1874fe6060f1SDimitry Andric FactEntry::Asserted), 18750b57cec5SDimitry Andric ClassifyDiagnostic(A)); 18760b57cec5SDimitry Andric break; 18770b57cec5SDimitry Andric } 18780b57cec5SDimitry Andric 18790b57cec5SDimitry Andric case attr::AssertCapability: { 18800b57cec5SDimitry Andric const auto *A = cast<AssertCapabilityAttr>(At); 18810b57cec5SDimitry Andric CapExprSet AssertLocks; 18820b57cec5SDimitry Andric Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 18830b57cec5SDimitry Andric for (const auto &AssertLock : AssertLocks) 18840b57cec5SDimitry Andric Analyzer->addLock(FSet, 1885a7dea167SDimitry Andric std::make_unique<LockableFactEntry>( 18860b57cec5SDimitry Andric AssertLock, 18870b57cec5SDimitry Andric A->isShared() ? LK_Shared : LK_Exclusive, Loc, 1888fe6060f1SDimitry Andric FactEntry::Asserted), 18890b57cec5SDimitry Andric ClassifyDiagnostic(A)); 18900b57cec5SDimitry Andric break; 18910b57cec5SDimitry Andric } 18920b57cec5SDimitry Andric 18930b57cec5SDimitry Andric // When we encounter an unlock function, we need to remove unlocked 18940b57cec5SDimitry Andric // mutexes from the lockset, and flag a warning if they are not there. 18950b57cec5SDimitry Andric case attr::ReleaseCapability: { 18960b57cec5SDimitry Andric const auto *A = cast<ReleaseCapabilityAttr>(At); 18970b57cec5SDimitry Andric if (A->isGeneric()) 18980b57cec5SDimitry Andric Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD); 18990b57cec5SDimitry Andric else if (A->isShared()) 19000b57cec5SDimitry Andric Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD); 19010b57cec5SDimitry Andric else 19020b57cec5SDimitry Andric Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD); 19030b57cec5SDimitry Andric 19040b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 19050b57cec5SDimitry Andric break; 19060b57cec5SDimitry Andric } 19070b57cec5SDimitry Andric 19080b57cec5SDimitry Andric case attr::RequiresCapability: { 19090b57cec5SDimitry Andric const auto *A = cast<RequiresCapabilityAttr>(At); 19100b57cec5SDimitry Andric for (auto *Arg : A->args()) { 19110b57cec5SDimitry Andric warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg, 19120b57cec5SDimitry Andric POK_FunctionCall, ClassifyDiagnostic(A), 19130b57cec5SDimitry Andric Exp->getExprLoc()); 19140b57cec5SDimitry Andric // use for adopting a lock 19155ffd83dbSDimitry Andric if (isScopedVar) 19165ffd83dbSDimitry Andric Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD); 19170b57cec5SDimitry Andric } 19180b57cec5SDimitry Andric break; 19190b57cec5SDimitry Andric } 19200b57cec5SDimitry Andric 19210b57cec5SDimitry Andric case attr::LocksExcluded: { 19220b57cec5SDimitry Andric const auto *A = cast<LocksExcludedAttr>(At); 19235ffd83dbSDimitry Andric for (auto *Arg : A->args()) { 19240b57cec5SDimitry Andric warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A)); 19255ffd83dbSDimitry Andric // use for deferring a lock 19265ffd83dbSDimitry Andric if (isScopedVar) 19275ffd83dbSDimitry Andric Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD); 19285ffd83dbSDimitry Andric } 19290b57cec5SDimitry Andric break; 19300b57cec5SDimitry Andric } 19310b57cec5SDimitry Andric 19320b57cec5SDimitry Andric // Ignore attributes unrelated to thread-safety 19330b57cec5SDimitry Andric default: 19340b57cec5SDimitry Andric break; 19350b57cec5SDimitry Andric } 19360b57cec5SDimitry Andric } 19370b57cec5SDimitry Andric 19380b57cec5SDimitry Andric // Remove locks first to allow lock upgrading/downgrading. 19390b57cec5SDimitry Andric // FIXME -- should only fully remove if the attribute refers to 'this'. 19400b57cec5SDimitry Andric bool Dtor = isa<CXXDestructorDecl>(D); 19410b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToRemove) 19420b57cec5SDimitry Andric Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind); 19430b57cec5SDimitry Andric for (const auto &M : SharedLocksToRemove) 19440b57cec5SDimitry Andric Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind); 19450b57cec5SDimitry Andric for (const auto &M : GenericLocksToRemove) 19460b57cec5SDimitry Andric Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind); 19470b57cec5SDimitry Andric 19480b57cec5SDimitry Andric // Add locks. 1949fe6060f1SDimitry Andric FactEntry::SourceKind Source = 1950fe6060f1SDimitry Andric isScopedVar ? FactEntry::Managed : FactEntry::Acquired; 19510b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToAdd) 1952fe6060f1SDimitry Andric Analyzer->addLock( 1953fe6060f1SDimitry Andric FSet, std::make_unique<LockableFactEntry>(M, LK_Exclusive, Loc, Source), 19540b57cec5SDimitry Andric CapDiagKind); 19550b57cec5SDimitry Andric for (const auto &M : SharedLocksToAdd) 1956fe6060f1SDimitry Andric Analyzer->addLock( 1957fe6060f1SDimitry Andric FSet, std::make_unique<LockableFactEntry>(M, LK_Shared, Loc, Source), 19580b57cec5SDimitry Andric CapDiagKind); 19590b57cec5SDimitry Andric 19600b57cec5SDimitry Andric if (isScopedVar) { 19610b57cec5SDimitry Andric // Add the managing object as a dummy mutex, mapped to the underlying mutex. 19620b57cec5SDimitry Andric SourceLocation MLoc = VD->getLocation(); 19630b57cec5SDimitry Andric DeclRefExpr DRE(VD->getASTContext(), VD, false, VD->getType(), VK_LValue, 19640b57cec5SDimitry Andric VD->getLocation()); 19650b57cec5SDimitry Andric // FIXME: does this store a pointer to DRE? 19660b57cec5SDimitry Andric CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr); 19670b57cec5SDimitry Andric 1968a7dea167SDimitry Andric auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, MLoc); 19690b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToAdd) 19705ffd83dbSDimitry Andric ScopedEntry->addLock(M); 19710b57cec5SDimitry Andric for (const auto &M : SharedLocksToAdd) 19725ffd83dbSDimitry Andric ScopedEntry->addLock(M); 19735ffd83dbSDimitry Andric for (const auto &M : ScopedReqsAndExcludes) 19745ffd83dbSDimitry Andric ScopedEntry->addLock(M); 19750b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToRemove) 19760b57cec5SDimitry Andric ScopedEntry->addExclusiveUnlock(M); 19770b57cec5SDimitry Andric for (const auto &M : SharedLocksToRemove) 19780b57cec5SDimitry Andric ScopedEntry->addSharedUnlock(M); 19790b57cec5SDimitry Andric Analyzer->addLock(FSet, std::move(ScopedEntry), CapDiagKind); 19800b57cec5SDimitry Andric } 19810b57cec5SDimitry Andric } 19820b57cec5SDimitry Andric 19830b57cec5SDimitry Andric /// For unary operations which read and write a variable, we need to 19840b57cec5SDimitry Andric /// check whether we hold any required mutexes. Reads are checked in 19850b57cec5SDimitry Andric /// VisitCastExpr. 19860b57cec5SDimitry Andric void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) { 19870b57cec5SDimitry Andric switch (UO->getOpcode()) { 19880b57cec5SDimitry Andric case UO_PostDec: 19890b57cec5SDimitry Andric case UO_PostInc: 19900b57cec5SDimitry Andric case UO_PreDec: 19910b57cec5SDimitry Andric case UO_PreInc: 19920b57cec5SDimitry Andric checkAccess(UO->getSubExpr(), AK_Written); 19930b57cec5SDimitry Andric break; 19940b57cec5SDimitry Andric default: 19950b57cec5SDimitry Andric break; 19960b57cec5SDimitry Andric } 19970b57cec5SDimitry Andric } 19980b57cec5SDimitry Andric 19990b57cec5SDimitry Andric /// For binary operations which assign to a variable (writes), we need to check 20000b57cec5SDimitry Andric /// whether we hold any required mutexes. 20010b57cec5SDimitry Andric /// FIXME: Deal with non-primitive types. 20020b57cec5SDimitry Andric void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) { 20030b57cec5SDimitry Andric if (!BO->isAssignmentOp()) 20040b57cec5SDimitry Andric return; 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric // adjust the context 20070b57cec5SDimitry Andric LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx); 20080b57cec5SDimitry Andric 20090b57cec5SDimitry Andric checkAccess(BO->getLHS(), AK_Written); 20100b57cec5SDimitry Andric } 20110b57cec5SDimitry Andric 20120b57cec5SDimitry Andric /// Whenever we do an LValue to Rvalue cast, we are reading a variable and 20130b57cec5SDimitry Andric /// need to ensure we hold any required mutexes. 20140b57cec5SDimitry Andric /// FIXME: Deal with non-primitive types. 20150b57cec5SDimitry Andric void BuildLockset::VisitCastExpr(const CastExpr *CE) { 20160b57cec5SDimitry Andric if (CE->getCastKind() != CK_LValueToRValue) 20170b57cec5SDimitry Andric return; 20180b57cec5SDimitry Andric checkAccess(CE->getSubExpr(), AK_Read); 20190b57cec5SDimitry Andric } 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric void BuildLockset::examineArguments(const FunctionDecl *FD, 20220b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgBegin, 20230b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgEnd, 20240b57cec5SDimitry Andric bool SkipFirstParam) { 20250b57cec5SDimitry Andric // Currently we can't do anything if we don't know the function declaration. 20260b57cec5SDimitry Andric if (!FD) 20270b57cec5SDimitry Andric return; 20280b57cec5SDimitry Andric 20290b57cec5SDimitry Andric // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it 20300b57cec5SDimitry Andric // only turns off checking within the body of a function, but we also 20310b57cec5SDimitry Andric // use it to turn off checking in arguments to the function. This 20320b57cec5SDimitry Andric // could result in some false negatives, but the alternative is to 20330b57cec5SDimitry Andric // create yet another attribute. 20340b57cec5SDimitry Andric if (FD->hasAttr<NoThreadSafetyAnalysisAttr>()) 20350b57cec5SDimitry Andric return; 20360b57cec5SDimitry Andric 20370b57cec5SDimitry Andric const ArrayRef<ParmVarDecl *> Params = FD->parameters(); 20380b57cec5SDimitry Andric auto Param = Params.begin(); 20390b57cec5SDimitry Andric if (SkipFirstParam) 20400b57cec5SDimitry Andric ++Param; 20410b57cec5SDimitry Andric 20420b57cec5SDimitry Andric // There can be default arguments, so we stop when one iterator is at end(). 20430b57cec5SDimitry Andric for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd; 20440b57cec5SDimitry Andric ++Param, ++Arg) { 20450b57cec5SDimitry Andric QualType Qt = (*Param)->getType(); 20460b57cec5SDimitry Andric if (Qt->isReferenceType()) 20470b57cec5SDimitry Andric checkAccess(*Arg, AK_Read, POK_PassByRef); 20480b57cec5SDimitry Andric } 20490b57cec5SDimitry Andric } 20500b57cec5SDimitry Andric 20510b57cec5SDimitry Andric void BuildLockset::VisitCallExpr(const CallExpr *Exp) { 20520b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) { 20530b57cec5SDimitry Andric const auto *ME = dyn_cast<MemberExpr>(CE->getCallee()); 20540b57cec5SDimitry Andric // ME can be null when calling a method pointer 20550b57cec5SDimitry Andric const CXXMethodDecl *MD = CE->getMethodDecl(); 20560b57cec5SDimitry Andric 20570b57cec5SDimitry Andric if (ME && MD) { 20580b57cec5SDimitry Andric if (ME->isArrow()) { 2059fe6060f1SDimitry Andric // Should perhaps be AK_Written if !MD->isConst(). 20600b57cec5SDimitry Andric checkPtAccess(CE->getImplicitObjectArgument(), AK_Read); 20610b57cec5SDimitry Andric } else { 2062fe6060f1SDimitry Andric // Should perhaps be AK_Written if !MD->isConst(). 20630b57cec5SDimitry Andric checkAccess(CE->getImplicitObjectArgument(), AK_Read); 20640b57cec5SDimitry Andric } 20650b57cec5SDimitry Andric } 20660b57cec5SDimitry Andric 20670b57cec5SDimitry Andric examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end()); 20680b57cec5SDimitry Andric } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) { 20690b57cec5SDimitry Andric auto OEop = OE->getOperator(); 20700b57cec5SDimitry Andric switch (OEop) { 20710b57cec5SDimitry Andric case OO_Equal: { 20720b57cec5SDimitry Andric const Expr *Target = OE->getArg(0); 20730b57cec5SDimitry Andric const Expr *Source = OE->getArg(1); 20740b57cec5SDimitry Andric checkAccess(Target, AK_Written); 20750b57cec5SDimitry Andric checkAccess(Source, AK_Read); 20760b57cec5SDimitry Andric break; 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric case OO_Star: 20790b57cec5SDimitry Andric case OO_Arrow: 20800b57cec5SDimitry Andric case OO_Subscript: 20810b57cec5SDimitry Andric if (!(OEop == OO_Star && OE->getNumArgs() > 1)) { 20820b57cec5SDimitry Andric // Grrr. operator* can be multiplication... 20830b57cec5SDimitry Andric checkPtAccess(OE->getArg(0), AK_Read); 20840b57cec5SDimitry Andric } 20850b57cec5SDimitry Andric LLVM_FALLTHROUGH; 20860b57cec5SDimitry Andric default: { 20870b57cec5SDimitry Andric // TODO: get rid of this, and rely on pass-by-ref instead. 20880b57cec5SDimitry Andric const Expr *Obj = OE->getArg(0); 20890b57cec5SDimitry Andric checkAccess(Obj, AK_Read); 20900b57cec5SDimitry Andric // Check the remaining arguments. For method operators, the first 20910b57cec5SDimitry Andric // argument is the implicit self argument, and doesn't appear in the 20920b57cec5SDimitry Andric // FunctionDecl, but for non-methods it does. 20930b57cec5SDimitry Andric const FunctionDecl *FD = OE->getDirectCallee(); 20940b57cec5SDimitry Andric examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(), 20950b57cec5SDimitry Andric /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD)); 20960b57cec5SDimitry Andric break; 20970b57cec5SDimitry Andric } 20980b57cec5SDimitry Andric } 20990b57cec5SDimitry Andric } else { 21000b57cec5SDimitry Andric examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end()); 21010b57cec5SDimitry Andric } 21020b57cec5SDimitry Andric 21030b57cec5SDimitry Andric auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 21040b57cec5SDimitry Andric if(!D || !D->hasAttrs()) 21050b57cec5SDimitry Andric return; 21060b57cec5SDimitry Andric handleCall(Exp, D); 21070b57cec5SDimitry Andric } 21080b57cec5SDimitry Andric 21090b57cec5SDimitry Andric void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) { 21100b57cec5SDimitry Andric const CXXConstructorDecl *D = Exp->getConstructor(); 21110b57cec5SDimitry Andric if (D && D->isCopyConstructor()) { 21120b57cec5SDimitry Andric const Expr* Source = Exp->getArg(0); 21130b57cec5SDimitry Andric checkAccess(Source, AK_Read); 21140b57cec5SDimitry Andric } else { 21150b57cec5SDimitry Andric examineArguments(D, Exp->arg_begin(), Exp->arg_end()); 21160b57cec5SDimitry Andric } 21170b57cec5SDimitry Andric } 21180b57cec5SDimitry Andric 21190b57cec5SDimitry Andric static CXXConstructorDecl * 21200b57cec5SDimitry Andric findConstructorForByValueReturn(const CXXRecordDecl *RD) { 21210b57cec5SDimitry Andric // Prefer a move constructor over a copy constructor. If there's more than 21220b57cec5SDimitry Andric // one copy constructor or more than one move constructor, we arbitrarily 21230b57cec5SDimitry Andric // pick the first declared such constructor rather than trying to guess which 21240b57cec5SDimitry Andric // one is more appropriate. 21250b57cec5SDimitry Andric CXXConstructorDecl *CopyCtor = nullptr; 21260b57cec5SDimitry Andric for (auto *Ctor : RD->ctors()) { 21270b57cec5SDimitry Andric if (Ctor->isDeleted()) 21280b57cec5SDimitry Andric continue; 21290b57cec5SDimitry Andric if (Ctor->isMoveConstructor()) 21300b57cec5SDimitry Andric return Ctor; 21310b57cec5SDimitry Andric if (!CopyCtor && Ctor->isCopyConstructor()) 21320b57cec5SDimitry Andric CopyCtor = Ctor; 21330b57cec5SDimitry Andric } 21340b57cec5SDimitry Andric return CopyCtor; 21350b57cec5SDimitry Andric } 21360b57cec5SDimitry Andric 21370b57cec5SDimitry Andric static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args, 21380b57cec5SDimitry Andric SourceLocation Loc) { 21390b57cec5SDimitry Andric ASTContext &Ctx = CD->getASTContext(); 21400b57cec5SDimitry Andric return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc, 21410b57cec5SDimitry Andric CD, true, Args, false, false, false, false, 21420b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, 21430b57cec5SDimitry Andric SourceRange(Loc, Loc)); 21440b57cec5SDimitry Andric } 21450b57cec5SDimitry Andric 21460b57cec5SDimitry Andric void BuildLockset::VisitDeclStmt(const DeclStmt *S) { 21470b57cec5SDimitry Andric // adjust the context 21480b57cec5SDimitry Andric LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx); 21490b57cec5SDimitry Andric 21500b57cec5SDimitry Andric for (auto *D : S->getDeclGroup()) { 21510b57cec5SDimitry Andric if (auto *VD = dyn_cast_or_null<VarDecl>(D)) { 21520b57cec5SDimitry Andric Expr *E = VD->getInit(); 21530b57cec5SDimitry Andric if (!E) 21540b57cec5SDimitry Andric continue; 21550b57cec5SDimitry Andric E = E->IgnoreParens(); 21560b57cec5SDimitry Andric 21570b57cec5SDimitry Andric // handle constructors that involve temporaries 21580b57cec5SDimitry Andric if (auto *EWC = dyn_cast<ExprWithCleanups>(E)) 21595ffd83dbSDimitry Andric E = EWC->getSubExpr()->IgnoreParens(); 21605ffd83dbSDimitry Andric if (auto *CE = dyn_cast<CastExpr>(E)) 21615ffd83dbSDimitry Andric if (CE->getCastKind() == CK_NoOp || 21625ffd83dbSDimitry Andric CE->getCastKind() == CK_ConstructorConversion || 21635ffd83dbSDimitry Andric CE->getCastKind() == CK_UserDefinedConversion) 21645ffd83dbSDimitry Andric E = CE->getSubExpr()->IgnoreParens(); 21650b57cec5SDimitry Andric if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E)) 21665ffd83dbSDimitry Andric E = BTE->getSubExpr()->IgnoreParens(); 21670b57cec5SDimitry Andric 21680b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) { 21690b57cec5SDimitry Andric const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor()); 21700b57cec5SDimitry Andric if (!CtorD || !CtorD->hasAttrs()) 21710b57cec5SDimitry Andric continue; 21720b57cec5SDimitry Andric handleCall(E, CtorD, VD); 2173fe6060f1SDimitry Andric } else if (isa<CallExpr>(E) && E->isPRValue()) { 21740b57cec5SDimitry Andric // If the object is initialized by a function call that returns a 21750b57cec5SDimitry Andric // scoped lockable by value, use the attributes on the copy or move 21760b57cec5SDimitry Andric // constructor to figure out what effect that should have on the 21770b57cec5SDimitry Andric // lockset. 21780b57cec5SDimitry Andric // FIXME: Is this really the best way to handle this situation? 21790b57cec5SDimitry Andric auto *RD = E->getType()->getAsCXXRecordDecl(); 21800b57cec5SDimitry Andric if (!RD || !RD->hasAttr<ScopedLockableAttr>()) 21810b57cec5SDimitry Andric continue; 21820b57cec5SDimitry Andric CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD); 21830b57cec5SDimitry Andric if (!CtorD || !CtorD->hasAttrs()) 21840b57cec5SDimitry Andric continue; 21850b57cec5SDimitry Andric handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD); 21860b57cec5SDimitry Andric } 21870b57cec5SDimitry Andric } 21880b57cec5SDimitry Andric } 21890b57cec5SDimitry Andric } 21900b57cec5SDimitry Andric 2191*28a41182SDimitry Andric /// Given two facts merging on a join point, possibly warn and decide whether to 2192*28a41182SDimitry Andric /// keep or replace. 2193fe6060f1SDimitry Andric /// 2194*28a41182SDimitry Andric /// \param CanModify Whether we can replace \p A by \p B. 2195*28a41182SDimitry Andric /// \return false if we should keep \p A, true if we should take \p B. 2196*28a41182SDimitry Andric bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B, 2197*28a41182SDimitry Andric bool CanModify) { 2198fe6060f1SDimitry Andric if (A.kind() != B.kind()) { 2199fe6060f1SDimitry Andric // For managed capabilities, the destructor should unlock in the right mode 2200fe6060f1SDimitry Andric // anyway. For asserted capabilities no unlocking is needed. 2201fe6060f1SDimitry Andric if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) { 2202*28a41182SDimitry Andric // The shared capability subsumes the exclusive capability, if possible. 2203*28a41182SDimitry Andric bool ShouldTakeB = B.kind() == LK_Shared; 2204*28a41182SDimitry Andric if (CanModify || !ShouldTakeB) 2205*28a41182SDimitry Andric return ShouldTakeB; 2206*28a41182SDimitry Andric } 2207fe6060f1SDimitry Andric Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc()); 2208fe6060f1SDimitry Andric // Take the exclusive capability to reduce further warnings. 2209*28a41182SDimitry Andric return CanModify && B.kind() == LK_Exclusive; 2210fe6060f1SDimitry Andric } else { 2211fe6060f1SDimitry Andric // The non-asserted capability is the one we want to track. 2212*28a41182SDimitry Andric return CanModify && A.asserted() && !B.asserted(); 2213fe6060f1SDimitry Andric } 2214fe6060f1SDimitry Andric } 2215fe6060f1SDimitry Andric 22160b57cec5SDimitry Andric /// Compute the intersection of two locksets and issue warnings for any 22170b57cec5SDimitry Andric /// locks in the symmetric difference. 22180b57cec5SDimitry Andric /// 22190b57cec5SDimitry Andric /// This function is used at a merge point in the CFG when comparing the lockset 22200b57cec5SDimitry Andric /// of each branch being merged. For example, given the following sequence: 22210b57cec5SDimitry Andric /// A; if () then B; else C; D; we need to check that the lockset after B and C 22220b57cec5SDimitry Andric /// are the same. In the event of a difference, we use the intersection of these 22230b57cec5SDimitry Andric /// two locksets at the start of D. 22240b57cec5SDimitry Andric /// 2225fe6060f1SDimitry Andric /// \param EntrySet A lockset for entry into a (possibly new) block. 2226fe6060f1SDimitry Andric /// \param ExitSet The lockset on exiting a preceding block. 22270b57cec5SDimitry Andric /// \param JoinLoc The location of the join point for error reporting 2228fe6060f1SDimitry Andric /// \param EntryLEK The warning if a mutex is missing from \p EntrySet. 2229fe6060f1SDimitry Andric /// \param ExitLEK The warning if a mutex is missing from \p ExitSet. 2230fe6060f1SDimitry Andric void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &EntrySet, 2231fe6060f1SDimitry Andric const FactSet &ExitSet, 22320b57cec5SDimitry Andric SourceLocation JoinLoc, 2233fe6060f1SDimitry Andric LockErrorKind EntryLEK, 2234fe6060f1SDimitry Andric LockErrorKind ExitLEK) { 2235fe6060f1SDimitry Andric FactSet EntrySetOrig = EntrySet; 22360b57cec5SDimitry Andric 2237fe6060f1SDimitry Andric // Find locks in ExitSet that conflict or are not in EntrySet, and warn. 2238fe6060f1SDimitry Andric for (const auto &Fact : ExitSet) { 2239fe6060f1SDimitry Andric const FactEntry &ExitFact = FactMan[Fact]; 22400b57cec5SDimitry Andric 2241fe6060f1SDimitry Andric FactSet::iterator EntryIt = EntrySet.findLockIter(FactMan, ExitFact); 2242fe6060f1SDimitry Andric if (EntryIt != EntrySet.end()) { 2243*28a41182SDimitry Andric if (join(FactMan[*EntryIt], ExitFact, 2244*28a41182SDimitry Andric EntryLEK != LEK_LockedSomeLoopIterations)) 2245fe6060f1SDimitry Andric *EntryIt = Fact; 2246fe6060f1SDimitry Andric } else if (!ExitFact.managed()) { 2247fe6060f1SDimitry Andric ExitFact.handleRemovalFromIntersection(ExitSet, FactMan, JoinLoc, 2248fe6060f1SDimitry Andric EntryLEK, Handler); 22490b57cec5SDimitry Andric } 22500b57cec5SDimitry Andric } 22510b57cec5SDimitry Andric 2252fe6060f1SDimitry Andric // Find locks in EntrySet that are not in ExitSet, and remove them. 2253fe6060f1SDimitry Andric for (const auto &Fact : EntrySetOrig) { 2254fe6060f1SDimitry Andric const FactEntry *EntryFact = &FactMan[Fact]; 2255fe6060f1SDimitry Andric const FactEntry *ExitFact = ExitSet.findLock(FactMan, *EntryFact); 22560b57cec5SDimitry Andric 2257fe6060f1SDimitry Andric if (!ExitFact) { 2258fe6060f1SDimitry Andric if (!EntryFact->managed() || ExitLEK == LEK_LockedSomeLoopIterations) 2259fe6060f1SDimitry Andric EntryFact->handleRemovalFromIntersection(EntrySetOrig, FactMan, JoinLoc, 2260fe6060f1SDimitry Andric ExitLEK, Handler); 2261fe6060f1SDimitry Andric if (ExitLEK == LEK_LockedSomePredecessors) 2262fe6060f1SDimitry Andric EntrySet.removeLock(FactMan, *EntryFact); 22630b57cec5SDimitry Andric } 22640b57cec5SDimitry Andric } 22650b57cec5SDimitry Andric } 22660b57cec5SDimitry Andric 22670b57cec5SDimitry Andric // Return true if block B never continues to its successors. 22680b57cec5SDimitry Andric static bool neverReturns(const CFGBlock *B) { 22690b57cec5SDimitry Andric if (B->hasNoReturnElement()) 22700b57cec5SDimitry Andric return true; 22710b57cec5SDimitry Andric if (B->empty()) 22720b57cec5SDimitry Andric return false; 22730b57cec5SDimitry Andric 22740b57cec5SDimitry Andric CFGElement Last = B->back(); 22750b57cec5SDimitry Andric if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) { 22760b57cec5SDimitry Andric if (isa<CXXThrowExpr>(S->getStmt())) 22770b57cec5SDimitry Andric return true; 22780b57cec5SDimitry Andric } 22790b57cec5SDimitry Andric return false; 22800b57cec5SDimitry Andric } 22810b57cec5SDimitry Andric 22820b57cec5SDimitry Andric /// Check a function's CFG for thread-safety violations. 22830b57cec5SDimitry Andric /// 22840b57cec5SDimitry Andric /// We traverse the blocks in the CFG, compute the set of mutexes that are held 22850b57cec5SDimitry Andric /// at the end of each block, and issue warnings for thread safety violations. 22860b57cec5SDimitry Andric /// Each block in the CFG is traversed exactly once. 22870b57cec5SDimitry Andric void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) { 22880b57cec5SDimitry Andric // TODO: this whole function needs be rewritten as a visitor for CFGWalker. 22890b57cec5SDimitry Andric // For now, we just use the walker to set things up. 22900b57cec5SDimitry Andric threadSafety::CFGWalker walker; 22910b57cec5SDimitry Andric if (!walker.init(AC)) 22920b57cec5SDimitry Andric return; 22930b57cec5SDimitry Andric 22940b57cec5SDimitry Andric // AC.dumpCFG(true); 22950b57cec5SDimitry Andric // threadSafety::printSCFG(walker); 22960b57cec5SDimitry Andric 22970b57cec5SDimitry Andric CFG *CFGraph = walker.getGraph(); 22980b57cec5SDimitry Andric const NamedDecl *D = walker.getDecl(); 22990b57cec5SDimitry Andric const auto *CurrentFunction = dyn_cast<FunctionDecl>(D); 23000b57cec5SDimitry Andric CurrentMethod = dyn_cast<CXXMethodDecl>(D); 23010b57cec5SDimitry Andric 23020b57cec5SDimitry Andric if (D->hasAttr<NoThreadSafetyAnalysisAttr>()) 23030b57cec5SDimitry Andric return; 23040b57cec5SDimitry Andric 23050b57cec5SDimitry Andric // FIXME: Do something a bit more intelligent inside constructor and 23060b57cec5SDimitry Andric // destructor code. Constructors and destructors must assume unique access 23070b57cec5SDimitry Andric // to 'this', so checks on member variable access is disabled, but we should 23080b57cec5SDimitry Andric // still enable checks on other objects. 23090b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D)) 23100b57cec5SDimitry Andric return; // Don't check inside constructors. 23110b57cec5SDimitry Andric if (isa<CXXDestructorDecl>(D)) 23120b57cec5SDimitry Andric return; // Don't check inside destructors. 23130b57cec5SDimitry Andric 23140b57cec5SDimitry Andric Handler.enterFunction(CurrentFunction); 23150b57cec5SDimitry Andric 23160b57cec5SDimitry Andric BlockInfo.resize(CFGraph->getNumBlockIDs(), 23170b57cec5SDimitry Andric CFGBlockInfo::getEmptyBlockInfo(LocalVarMap)); 23180b57cec5SDimitry Andric 23190b57cec5SDimitry Andric // We need to explore the CFG via a "topological" ordering. 23200b57cec5SDimitry Andric // That way, we will be guaranteed to have information about required 23210b57cec5SDimitry Andric // predecessor locksets when exploring a new block. 23220b57cec5SDimitry Andric const PostOrderCFGView *SortedGraph = walker.getSortedGraph(); 23230b57cec5SDimitry Andric PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 23240b57cec5SDimitry Andric 23250b57cec5SDimitry Andric // Mark entry block as reachable 23260b57cec5SDimitry Andric BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true; 23270b57cec5SDimitry Andric 23280b57cec5SDimitry Andric // Compute SSA names for local variables 23290b57cec5SDimitry Andric LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo); 23300b57cec5SDimitry Andric 23310b57cec5SDimitry Andric // Fill in source locations for all CFGBlocks. 23320b57cec5SDimitry Andric findBlockLocations(CFGraph, SortedGraph, BlockInfo); 23330b57cec5SDimitry Andric 23340b57cec5SDimitry Andric CapExprSet ExclusiveLocksAcquired; 23350b57cec5SDimitry Andric CapExprSet SharedLocksAcquired; 23360b57cec5SDimitry Andric CapExprSet LocksReleased; 23370b57cec5SDimitry Andric 23380b57cec5SDimitry Andric // Add locks from exclusive_locks_required and shared_locks_required 23390b57cec5SDimitry Andric // to initial lockset. Also turn off checking for lock and unlock functions. 23400b57cec5SDimitry Andric // FIXME: is there a more intelligent way to check lock/unlock functions? 23410b57cec5SDimitry Andric if (!SortedGraph->empty() && D->hasAttrs()) { 23420b57cec5SDimitry Andric const CFGBlock *FirstBlock = *SortedGraph->begin(); 23430b57cec5SDimitry Andric FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet; 23440b57cec5SDimitry Andric 23450b57cec5SDimitry Andric CapExprSet ExclusiveLocksToAdd; 23460b57cec5SDimitry Andric CapExprSet SharedLocksToAdd; 23470b57cec5SDimitry Andric StringRef CapDiagKind = "mutex"; 23480b57cec5SDimitry Andric 23490b57cec5SDimitry Andric SourceLocation Loc = D->getLocation(); 23500b57cec5SDimitry Andric for (const auto *Attr : D->attrs()) { 23510b57cec5SDimitry Andric Loc = Attr->getLocation(); 23520b57cec5SDimitry Andric if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) { 23530b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 23540b57cec5SDimitry Andric nullptr, D); 23550b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 23560b57cec5SDimitry Andric } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) { 23570b57cec5SDimitry Andric // UNLOCK_FUNCTION() is used to hide the underlying lock implementation. 23580b57cec5SDimitry Andric // We must ignore such methods. 23590b57cec5SDimitry Andric if (A->args_size() == 0) 23600b57cec5SDimitry Andric return; 23610b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 23620b57cec5SDimitry Andric nullptr, D); 23630b57cec5SDimitry Andric getMutexIDs(LocksReleased, A, nullptr, D); 23640b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 23650b57cec5SDimitry Andric } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) { 23660b57cec5SDimitry Andric if (A->args_size() == 0) 23670b57cec5SDimitry Andric return; 23680b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksAcquired 23690b57cec5SDimitry Andric : ExclusiveLocksAcquired, 23700b57cec5SDimitry Andric A, nullptr, D); 23710b57cec5SDimitry Andric CapDiagKind = ClassifyDiagnostic(A); 23720b57cec5SDimitry Andric } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) { 23730b57cec5SDimitry Andric // Don't try to check trylock functions for now. 23740b57cec5SDimitry Andric return; 23750b57cec5SDimitry Andric } else if (isa<SharedTrylockFunctionAttr>(Attr)) { 23760b57cec5SDimitry Andric // Don't try to check trylock functions for now. 23770b57cec5SDimitry Andric return; 23780b57cec5SDimitry Andric } else if (isa<TryAcquireCapabilityAttr>(Attr)) { 23790b57cec5SDimitry Andric // Don't try to check trylock functions for now. 23800b57cec5SDimitry Andric return; 23810b57cec5SDimitry Andric } 23820b57cec5SDimitry Andric } 23830b57cec5SDimitry Andric 23840b57cec5SDimitry Andric // FIXME -- Loc can be wrong here. 23850b57cec5SDimitry Andric for (const auto &Mu : ExclusiveLocksToAdd) { 2386fe6060f1SDimitry Andric auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc, 2387fe6060f1SDimitry Andric FactEntry::Declared); 23880b57cec5SDimitry Andric addLock(InitialLockset, std::move(Entry), CapDiagKind, true); 23890b57cec5SDimitry Andric } 23900b57cec5SDimitry Andric for (const auto &Mu : SharedLocksToAdd) { 2391fe6060f1SDimitry Andric auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc, 2392fe6060f1SDimitry Andric FactEntry::Declared); 23930b57cec5SDimitry Andric addLock(InitialLockset, std::move(Entry), CapDiagKind, true); 23940b57cec5SDimitry Andric } 23950b57cec5SDimitry Andric } 23960b57cec5SDimitry Andric 23970b57cec5SDimitry Andric for (const auto *CurrBlock : *SortedGraph) { 23980b57cec5SDimitry Andric unsigned CurrBlockID = CurrBlock->getBlockID(); 23990b57cec5SDimitry Andric CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 24000b57cec5SDimitry Andric 24010b57cec5SDimitry Andric // Use the default initial lockset in case there are no predecessors. 24020b57cec5SDimitry Andric VisitedBlocks.insert(CurrBlock); 24030b57cec5SDimitry Andric 24040b57cec5SDimitry Andric // Iterate through the predecessor blocks and warn if the lockset for all 24050b57cec5SDimitry Andric // predecessors is not the same. We take the entry lockset of the current 24060b57cec5SDimitry Andric // block to be the intersection of all previous locksets. 24070b57cec5SDimitry Andric // FIXME: By keeping the intersection, we may output more errors in future 24080b57cec5SDimitry Andric // for a lock which is not in the intersection, but was in the union. We 24090b57cec5SDimitry Andric // may want to also keep the union in future. As an example, let's say 24100b57cec5SDimitry Andric // the intersection contains Mutex L, and the union contains L and M. 24110b57cec5SDimitry Andric // Later we unlock M. At this point, we would output an error because we 24120b57cec5SDimitry Andric // never locked M; although the real error is probably that we forgot to 24130b57cec5SDimitry Andric // lock M on all code paths. Conversely, let's say that later we lock M. 24140b57cec5SDimitry Andric // In this case, we should compare against the intersection instead of the 24150b57cec5SDimitry Andric // union because the real error is probably that we forgot to unlock M on 24160b57cec5SDimitry Andric // all code paths. 24170b57cec5SDimitry Andric bool LocksetInitialized = false; 24180b57cec5SDimitry Andric SmallVector<CFGBlock *, 8> SpecialBlocks; 24190b57cec5SDimitry Andric for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 24200b57cec5SDimitry Andric PE = CurrBlock->pred_end(); PI != PE; ++PI) { 24210b57cec5SDimitry Andric // if *PI -> CurrBlock is a back edge 24220b57cec5SDimitry Andric if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) 24230b57cec5SDimitry Andric continue; 24240b57cec5SDimitry Andric 24250b57cec5SDimitry Andric unsigned PrevBlockID = (*PI)->getBlockID(); 24260b57cec5SDimitry Andric CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 24270b57cec5SDimitry Andric 24280b57cec5SDimitry Andric // Ignore edges from blocks that can't return. 24290b57cec5SDimitry Andric if (neverReturns(*PI) || !PrevBlockInfo->Reachable) 24300b57cec5SDimitry Andric continue; 24310b57cec5SDimitry Andric 24320b57cec5SDimitry Andric // Okay, we can reach this block from the entry. 24330b57cec5SDimitry Andric CurrBlockInfo->Reachable = true; 24340b57cec5SDimitry Andric 24350b57cec5SDimitry Andric // If the previous block ended in a 'continue' or 'break' statement, then 24360b57cec5SDimitry Andric // a difference in locksets is probably due to a bug in that block, rather 24370b57cec5SDimitry Andric // than in some other predecessor. In that case, keep the other 24380b57cec5SDimitry Andric // predecessor's lockset. 24390b57cec5SDimitry Andric if (const Stmt *Terminator = (*PI)->getTerminatorStmt()) { 24400b57cec5SDimitry Andric if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) { 24410b57cec5SDimitry Andric SpecialBlocks.push_back(*PI); 24420b57cec5SDimitry Andric continue; 24430b57cec5SDimitry Andric } 24440b57cec5SDimitry Andric } 24450b57cec5SDimitry Andric 24460b57cec5SDimitry Andric FactSet PrevLockset; 24470b57cec5SDimitry Andric getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock); 24480b57cec5SDimitry Andric 24490b57cec5SDimitry Andric if (!LocksetInitialized) { 24500b57cec5SDimitry Andric CurrBlockInfo->EntrySet = PrevLockset; 24510b57cec5SDimitry Andric LocksetInitialized = true; 24520b57cec5SDimitry Andric } else { 24530b57cec5SDimitry Andric intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset, 24540b57cec5SDimitry Andric CurrBlockInfo->EntryLoc, 24550b57cec5SDimitry Andric LEK_LockedSomePredecessors); 24560b57cec5SDimitry Andric } 24570b57cec5SDimitry Andric } 24580b57cec5SDimitry Andric 24590b57cec5SDimitry Andric // Skip rest of block if it's not reachable. 24600b57cec5SDimitry Andric if (!CurrBlockInfo->Reachable) 24610b57cec5SDimitry Andric continue; 24620b57cec5SDimitry Andric 24630b57cec5SDimitry Andric // Process continue and break blocks. Assume that the lockset for the 24640b57cec5SDimitry Andric // resulting block is unaffected by any discrepancies in them. 24650b57cec5SDimitry Andric for (const auto *PrevBlock : SpecialBlocks) { 24660b57cec5SDimitry Andric unsigned PrevBlockID = PrevBlock->getBlockID(); 24670b57cec5SDimitry Andric CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 24680b57cec5SDimitry Andric 24690b57cec5SDimitry Andric if (!LocksetInitialized) { 24700b57cec5SDimitry Andric CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet; 24710b57cec5SDimitry Andric LocksetInitialized = true; 24720b57cec5SDimitry Andric } else { 24730b57cec5SDimitry Andric // Determine whether this edge is a loop terminator for diagnostic 24740b57cec5SDimitry Andric // purposes. FIXME: A 'break' statement might be a loop terminator, but 24750b57cec5SDimitry Andric // it might also be part of a switch. Also, a subsequent destructor 24760b57cec5SDimitry Andric // might add to the lockset, in which case the real issue might be a 24770b57cec5SDimitry Andric // double lock on the other path. 24780b57cec5SDimitry Andric const Stmt *Terminator = PrevBlock->getTerminatorStmt(); 24790b57cec5SDimitry Andric bool IsLoop = Terminator && isa<ContinueStmt>(Terminator); 24800b57cec5SDimitry Andric 24810b57cec5SDimitry Andric FactSet PrevLockset; 24820b57cec5SDimitry Andric getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, 24830b57cec5SDimitry Andric PrevBlock, CurrBlock); 24840b57cec5SDimitry Andric 24850b57cec5SDimitry Andric // Do not update EntrySet. 2486fe6060f1SDimitry Andric intersectAndWarn( 2487fe6060f1SDimitry Andric CurrBlockInfo->EntrySet, PrevLockset, PrevBlockInfo->ExitLoc, 2488fe6060f1SDimitry Andric IsLoop ? LEK_LockedSomeLoopIterations : LEK_LockedSomePredecessors); 24890b57cec5SDimitry Andric } 24900b57cec5SDimitry Andric } 24910b57cec5SDimitry Andric 24920b57cec5SDimitry Andric BuildLockset LocksetBuilder(this, *CurrBlockInfo); 24930b57cec5SDimitry Andric 24940b57cec5SDimitry Andric // Visit all the statements in the basic block. 24950b57cec5SDimitry Andric for (const auto &BI : *CurrBlock) { 24960b57cec5SDimitry Andric switch (BI.getKind()) { 24970b57cec5SDimitry Andric case CFGElement::Statement: { 24980b57cec5SDimitry Andric CFGStmt CS = BI.castAs<CFGStmt>(); 24990b57cec5SDimitry Andric LocksetBuilder.Visit(CS.getStmt()); 25000b57cec5SDimitry Andric break; 25010b57cec5SDimitry Andric } 25020b57cec5SDimitry Andric // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now. 25030b57cec5SDimitry Andric case CFGElement::AutomaticObjectDtor: { 25040b57cec5SDimitry Andric CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>(); 25050b57cec5SDimitry Andric const auto *DD = AD.getDestructorDecl(AC.getASTContext()); 25060b57cec5SDimitry Andric if (!DD->hasAttrs()) 25070b57cec5SDimitry Andric break; 25080b57cec5SDimitry Andric 25090b57cec5SDimitry Andric // Create a dummy expression, 25100b57cec5SDimitry Andric auto *VD = const_cast<VarDecl *>(AD.getVarDecl()); 25110b57cec5SDimitry Andric DeclRefExpr DRE(VD->getASTContext(), VD, false, 25120b57cec5SDimitry Andric VD->getType().getNonReferenceType(), VK_LValue, 25130b57cec5SDimitry Andric AD.getTriggerStmt()->getEndLoc()); 25140b57cec5SDimitry Andric LocksetBuilder.handleCall(&DRE, DD); 25150b57cec5SDimitry Andric break; 25160b57cec5SDimitry Andric } 25170b57cec5SDimitry Andric default: 25180b57cec5SDimitry Andric break; 25190b57cec5SDimitry Andric } 25200b57cec5SDimitry Andric } 25210b57cec5SDimitry Andric CurrBlockInfo->ExitSet = LocksetBuilder.FSet; 25220b57cec5SDimitry Andric 25230b57cec5SDimitry Andric // For every back edge from CurrBlock (the end of the loop) to another block 25240b57cec5SDimitry Andric // (FirstLoopBlock) we need to check that the Lockset of Block is equal to 25250b57cec5SDimitry Andric // the one held at the beginning of FirstLoopBlock. We can look up the 25260b57cec5SDimitry Andric // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map. 25270b57cec5SDimitry Andric for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 25280b57cec5SDimitry Andric SE = CurrBlock->succ_end(); SI != SE; ++SI) { 25290b57cec5SDimitry Andric // if CurrBlock -> *SI is *not* a back edge 25300b57cec5SDimitry Andric if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI)) 25310b57cec5SDimitry Andric continue; 25320b57cec5SDimitry Andric 25330b57cec5SDimitry Andric CFGBlock *FirstLoopBlock = *SI; 25340b57cec5SDimitry Andric CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()]; 25350b57cec5SDimitry Andric CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID]; 2536fe6060f1SDimitry Andric intersectAndWarn(PreLoop->EntrySet, LoopEnd->ExitSet, PreLoop->EntryLoc, 2537fe6060f1SDimitry Andric LEK_LockedSomeLoopIterations); 25380b57cec5SDimitry Andric } 25390b57cec5SDimitry Andric } 25400b57cec5SDimitry Andric 25410b57cec5SDimitry Andric CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()]; 25420b57cec5SDimitry Andric CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()]; 25430b57cec5SDimitry Andric 25440b57cec5SDimitry Andric // Skip the final check if the exit block is unreachable. 25450b57cec5SDimitry Andric if (!Final->Reachable) 25460b57cec5SDimitry Andric return; 25470b57cec5SDimitry Andric 25480b57cec5SDimitry Andric // By default, we expect all locks held on entry to be held on exit. 25490b57cec5SDimitry Andric FactSet ExpectedExitSet = Initial->EntrySet; 25500b57cec5SDimitry Andric 25510b57cec5SDimitry Andric // Adjust the expected exit set by adding or removing locks, as declared 25520b57cec5SDimitry Andric // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then 25530b57cec5SDimitry Andric // issue the appropriate warning. 25540b57cec5SDimitry Andric // FIXME: the location here is not quite right. 25550b57cec5SDimitry Andric for (const auto &Lock : ExclusiveLocksAcquired) 2556a7dea167SDimitry Andric ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>( 25570b57cec5SDimitry Andric Lock, LK_Exclusive, D->getLocation())); 25580b57cec5SDimitry Andric for (const auto &Lock : SharedLocksAcquired) 2559a7dea167SDimitry Andric ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>( 25600b57cec5SDimitry Andric Lock, LK_Shared, D->getLocation())); 25610b57cec5SDimitry Andric for (const auto &Lock : LocksReleased) 25620b57cec5SDimitry Andric ExpectedExitSet.removeLock(FactMan, Lock); 25630b57cec5SDimitry Andric 25640b57cec5SDimitry Andric // FIXME: Should we call this function for all blocks which exit the function? 2565fe6060f1SDimitry Andric intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc, 2566fe6060f1SDimitry Andric LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction); 25670b57cec5SDimitry Andric 25680b57cec5SDimitry Andric Handler.leaveFunction(CurrentFunction); 25690b57cec5SDimitry Andric } 25700b57cec5SDimitry Andric 25710b57cec5SDimitry Andric /// Check a function's CFG for thread-safety violations. 25720b57cec5SDimitry Andric /// 25730b57cec5SDimitry Andric /// We traverse the blocks in the CFG, compute the set of mutexes that are held 25740b57cec5SDimitry Andric /// at the end of each block, and issue warnings for thread safety violations. 25750b57cec5SDimitry Andric /// Each block in the CFG is traversed exactly once. 25760b57cec5SDimitry Andric void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC, 25770b57cec5SDimitry Andric ThreadSafetyHandler &Handler, 25780b57cec5SDimitry Andric BeforeSet **BSet) { 25790b57cec5SDimitry Andric if (!*BSet) 25800b57cec5SDimitry Andric *BSet = new BeforeSet; 25810b57cec5SDimitry Andric ThreadSafetyAnalyzer Analyzer(Handler, *BSet); 25820b57cec5SDimitry Andric Analyzer.runAnalysis(AC); 25830b57cec5SDimitry Andric } 25840b57cec5SDimitry Andric 25850b57cec5SDimitry Andric void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; } 25860b57cec5SDimitry Andric 25870b57cec5SDimitry Andric /// Helper function that returns a LockKind required for the given level 25880b57cec5SDimitry Andric /// of access. 25890b57cec5SDimitry Andric LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) { 25900b57cec5SDimitry Andric switch (AK) { 25910b57cec5SDimitry Andric case AK_Read : 25920b57cec5SDimitry Andric return LK_Shared; 25930b57cec5SDimitry Andric case AK_Written : 25940b57cec5SDimitry Andric return LK_Exclusive; 25950b57cec5SDimitry Andric } 25960b57cec5SDimitry Andric llvm_unreachable("Unknown AccessKind"); 25970b57cec5SDimitry Andric } 2598