1f4a2713aSLionel Sambuc //===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // A intra-procedural analysis for thread safety (e.g. deadlocks and race
11f4a2713aSLionel Sambuc // conditions), based off of an annotation system.
12f4a2713aSLionel Sambuc //
13*0a6a1f1dSLionel Sambuc // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
14f4a2713aSLionel Sambuc // for more information.
15f4a2713aSLionel Sambuc //
16f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
17f4a2713aSLionel Sambuc
18f4a2713aSLionel Sambuc #include "clang/AST/Attr.h"
19f4a2713aSLionel Sambuc #include "clang/AST/DeclCXX.h"
20f4a2713aSLionel Sambuc #include "clang/AST/ExprCXX.h"
21f4a2713aSLionel Sambuc #include "clang/AST/StmtCXX.h"
22f4a2713aSLionel Sambuc #include "clang/AST/StmtVisitor.h"
23f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/PostOrderCFGView.h"
24*0a6a1f1dSLionel Sambuc #include "clang/Analysis/Analyses/ThreadSafety.h"
25*0a6a1f1dSLionel Sambuc #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
26*0a6a1f1dSLionel Sambuc #include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
27*0a6a1f1dSLionel Sambuc #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
28*0a6a1f1dSLionel Sambuc #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
29f4a2713aSLionel Sambuc #include "clang/Analysis/AnalysisContext.h"
30f4a2713aSLionel Sambuc #include "clang/Analysis/CFG.h"
31f4a2713aSLionel Sambuc #include "clang/Analysis/CFGStmtMap.h"
32f4a2713aSLionel Sambuc #include "clang/Basic/OperatorKinds.h"
33f4a2713aSLionel Sambuc #include "clang/Basic/SourceLocation.h"
34f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
35f4a2713aSLionel Sambuc #include "llvm/ADT/BitVector.h"
36f4a2713aSLionel Sambuc #include "llvm/ADT/FoldingSet.h"
37f4a2713aSLionel Sambuc #include "llvm/ADT/ImmutableMap.h"
38f4a2713aSLionel Sambuc #include "llvm/ADT/PostOrderIterator.h"
39f4a2713aSLionel Sambuc #include "llvm/ADT/SmallVector.h"
40f4a2713aSLionel Sambuc #include "llvm/ADT/StringRef.h"
41f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
42f4a2713aSLionel Sambuc #include <algorithm>
43*0a6a1f1dSLionel Sambuc #include <ostream>
44*0a6a1f1dSLionel Sambuc #include <sstream>
45f4a2713aSLionel Sambuc #include <utility>
46f4a2713aSLionel Sambuc #include <vector>
47f4a2713aSLionel Sambuc
48*0a6a1f1dSLionel Sambuc
49*0a6a1f1dSLionel Sambuc namespace clang {
50*0a6a1f1dSLionel Sambuc namespace threadSafety {
51f4a2713aSLionel Sambuc
52f4a2713aSLionel Sambuc // Key method definition
~ThreadSafetyHandler()53f4a2713aSLionel Sambuc ThreadSafetyHandler::~ThreadSafetyHandler() {}
54f4a2713aSLionel Sambuc
55*0a6a1f1dSLionel Sambuc class TILPrinter :
56*0a6a1f1dSLionel Sambuc public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
57f4a2713aSLionel Sambuc
58f4a2713aSLionel Sambuc
59f4a2713aSLionel Sambuc /// Issue a warning about an invalid lock expression
warnInvalidLock(ThreadSafetyHandler & Handler,const Expr * MutexExp,const NamedDecl * D,const Expr * DeclExp,StringRef Kind)60f4a2713aSLionel Sambuc static void warnInvalidLock(ThreadSafetyHandler &Handler,
61*0a6a1f1dSLionel Sambuc const Expr *MutexExp, const NamedDecl *D,
62*0a6a1f1dSLionel Sambuc const Expr *DeclExp, StringRef Kind) {
63f4a2713aSLionel Sambuc SourceLocation Loc;
64f4a2713aSLionel Sambuc if (DeclExp)
65f4a2713aSLionel Sambuc Loc = DeclExp->getExprLoc();
66f4a2713aSLionel Sambuc
67f4a2713aSLionel Sambuc // FIXME: add a note about the attribute location in MutexExp or D
68f4a2713aSLionel Sambuc if (Loc.isValid())
69*0a6a1f1dSLionel Sambuc Handler.handleInvalidLockExp(Kind, Loc);
70f4a2713aSLionel Sambuc }
71f4a2713aSLionel Sambuc
72f4a2713aSLionel Sambuc
73*0a6a1f1dSLionel Sambuc /// \brief A set of CapabilityInfo objects, which are compiled from the
74*0a6a1f1dSLionel Sambuc /// requires attributes on a function.
75*0a6a1f1dSLionel Sambuc class CapExprSet : public SmallVector<CapabilityExpr, 4> {
76f4a2713aSLionel Sambuc public:
77*0a6a1f1dSLionel Sambuc /// \brief Push M onto list, but discard duplicates.
push_back_nodup(const CapabilityExpr & CapE)78*0a6a1f1dSLionel Sambuc void push_back_nodup(const CapabilityExpr &CapE) {
79*0a6a1f1dSLionel Sambuc iterator It = std::find_if(begin(), end(),
80*0a6a1f1dSLionel Sambuc [=](const CapabilityExpr &CapE2) {
81*0a6a1f1dSLionel Sambuc return CapE.equals(CapE2);
82*0a6a1f1dSLionel Sambuc });
83*0a6a1f1dSLionel Sambuc if (It == end())
84*0a6a1f1dSLionel Sambuc push_back(CapE);
85f4a2713aSLionel Sambuc }
86f4a2713aSLionel Sambuc };
87f4a2713aSLionel Sambuc
88*0a6a1f1dSLionel Sambuc class FactManager;
89*0a6a1f1dSLionel Sambuc class FactSet;
90f4a2713aSLionel Sambuc
91*0a6a1f1dSLionel Sambuc /// \brief This is a helper class that stores a fact that is known at a
92*0a6a1f1dSLionel Sambuc /// particular point in program execution. Currently, a fact is a capability,
93*0a6a1f1dSLionel Sambuc /// along with additional information, such as where it was acquired, whether
94*0a6a1f1dSLionel Sambuc /// it is exclusive or shared, etc.
95f4a2713aSLionel Sambuc ///
96*0a6a1f1dSLionel Sambuc /// FIXME: this analysis does not currently support either re-entrant
97f4a2713aSLionel Sambuc /// locking or lock "upgrading" and "downgrading" between exclusive and
98f4a2713aSLionel Sambuc /// shared.
99*0a6a1f1dSLionel Sambuc class FactEntry : public CapabilityExpr {
100*0a6a1f1dSLionel Sambuc private:
101*0a6a1f1dSLionel Sambuc LockKind LKind; ///< exclusive or shared
102*0a6a1f1dSLionel Sambuc SourceLocation AcquireLoc; ///< where it was acquired.
103*0a6a1f1dSLionel Sambuc bool Asserted; ///< true if the lock was asserted
104f4a2713aSLionel Sambuc
105*0a6a1f1dSLionel Sambuc public:
FactEntry(const CapabilityExpr & CE,LockKind LK,SourceLocation Loc,bool Asrt)106*0a6a1f1dSLionel Sambuc FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
107*0a6a1f1dSLionel Sambuc bool Asrt)
108*0a6a1f1dSLionel Sambuc : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt) {}
109f4a2713aSLionel Sambuc
~FactEntry()110*0a6a1f1dSLionel Sambuc virtual ~FactEntry() {}
111f4a2713aSLionel Sambuc
kind() const112*0a6a1f1dSLionel Sambuc LockKind kind() const { return LKind; }
loc() const113*0a6a1f1dSLionel Sambuc SourceLocation loc() const { return AcquireLoc; }
asserted() const114*0a6a1f1dSLionel Sambuc bool asserted() const { return Asserted; }
115f4a2713aSLionel Sambuc
116*0a6a1f1dSLionel Sambuc virtual void
117*0a6a1f1dSLionel Sambuc handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
118*0a6a1f1dSLionel Sambuc SourceLocation JoinLoc, LockErrorKind LEK,
119*0a6a1f1dSLionel Sambuc ThreadSafetyHandler &Handler) const = 0;
120*0a6a1f1dSLionel Sambuc virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
121*0a6a1f1dSLionel Sambuc const CapabilityExpr &Cp, SourceLocation UnlockLoc,
122*0a6a1f1dSLionel Sambuc bool FullyRemove, ThreadSafetyHandler &Handler,
123*0a6a1f1dSLionel Sambuc StringRef DiagKind) const = 0;
124f4a2713aSLionel Sambuc
125*0a6a1f1dSLionel Sambuc // Return true if LKind >= LK, where exclusive > shared
isAtLeast(LockKind LK)126f4a2713aSLionel Sambuc bool isAtLeast(LockKind LK) {
127*0a6a1f1dSLionel Sambuc return (LKind == LK_Exclusive) || (LK == LK_Shared);
128f4a2713aSLionel Sambuc }
129f4a2713aSLionel Sambuc };
130f4a2713aSLionel Sambuc
131f4a2713aSLionel Sambuc
132f4a2713aSLionel Sambuc typedef unsigned short FactID;
133f4a2713aSLionel Sambuc
134f4a2713aSLionel Sambuc /// \brief FactManager manages the memory for all facts that are created during
135f4a2713aSLionel Sambuc /// the analysis of a single routine.
136f4a2713aSLionel Sambuc class FactManager {
137f4a2713aSLionel Sambuc private:
138*0a6a1f1dSLionel Sambuc std::vector<std::unique_ptr<FactEntry>> Facts;
139f4a2713aSLionel Sambuc
140f4a2713aSLionel Sambuc public:
newFact(std::unique_ptr<FactEntry> Entry)141*0a6a1f1dSLionel Sambuc FactID newFact(std::unique_ptr<FactEntry> Entry) {
142*0a6a1f1dSLionel Sambuc Facts.push_back(std::move(Entry));
143f4a2713aSLionel Sambuc return static_cast<unsigned short>(Facts.size() - 1);
144f4a2713aSLionel Sambuc }
145f4a2713aSLionel Sambuc
operator [](FactID F) const146*0a6a1f1dSLionel Sambuc const FactEntry &operator[](FactID F) const { return *Facts[F]; }
operator [](FactID F)147*0a6a1f1dSLionel Sambuc FactEntry &operator[](FactID F) { return *Facts[F]; }
148f4a2713aSLionel Sambuc };
149f4a2713aSLionel Sambuc
150f4a2713aSLionel Sambuc
151f4a2713aSLionel Sambuc /// \brief A FactSet is the set of facts that are known to be true at a
152f4a2713aSLionel Sambuc /// particular program point. FactSets must be small, because they are
153f4a2713aSLionel Sambuc /// frequently copied, and are thus implemented as a set of indices into a
154f4a2713aSLionel Sambuc /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
155f4a2713aSLionel Sambuc /// locks, so we can get away with doing a linear search for lookup. Note
156f4a2713aSLionel Sambuc /// that a hashtable or map is inappropriate in this case, because lookups
157f4a2713aSLionel Sambuc /// may involve partial pattern matches, rather than exact matches.
158f4a2713aSLionel Sambuc class FactSet {
159f4a2713aSLionel Sambuc private:
160f4a2713aSLionel Sambuc typedef SmallVector<FactID, 4> FactVec;
161f4a2713aSLionel Sambuc
162f4a2713aSLionel Sambuc FactVec FactIDs;
163f4a2713aSLionel Sambuc
164f4a2713aSLionel Sambuc public:
165f4a2713aSLionel Sambuc typedef FactVec::iterator iterator;
166f4a2713aSLionel Sambuc typedef FactVec::const_iterator const_iterator;
167f4a2713aSLionel Sambuc
begin()168f4a2713aSLionel Sambuc iterator begin() { return FactIDs.begin(); }
begin() const169f4a2713aSLionel Sambuc const_iterator begin() const { return FactIDs.begin(); }
170f4a2713aSLionel Sambuc
end()171f4a2713aSLionel Sambuc iterator end() { return FactIDs.end(); }
end() const172f4a2713aSLionel Sambuc const_iterator end() const { return FactIDs.end(); }
173f4a2713aSLionel Sambuc
isEmpty() const174f4a2713aSLionel Sambuc bool isEmpty() const { return FactIDs.size() == 0; }
175f4a2713aSLionel Sambuc
176*0a6a1f1dSLionel Sambuc // Return true if the set contains only negative facts
isEmpty(FactManager & FactMan) const177*0a6a1f1dSLionel Sambuc bool isEmpty(FactManager &FactMan) const {
178*0a6a1f1dSLionel Sambuc for (FactID FID : *this) {
179*0a6a1f1dSLionel Sambuc if (!FactMan[FID].negative())
180*0a6a1f1dSLionel Sambuc return false;
181*0a6a1f1dSLionel Sambuc }
182*0a6a1f1dSLionel Sambuc return true;
183*0a6a1f1dSLionel Sambuc }
184*0a6a1f1dSLionel Sambuc
addLockByID(FactID ID)185*0a6a1f1dSLionel Sambuc void addLockByID(FactID ID) { FactIDs.push_back(ID); }
186*0a6a1f1dSLionel Sambuc
addLock(FactManager & FM,std::unique_ptr<FactEntry> Entry)187*0a6a1f1dSLionel Sambuc FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
188*0a6a1f1dSLionel Sambuc FactID F = FM.newFact(std::move(Entry));
189f4a2713aSLionel Sambuc FactIDs.push_back(F);
190f4a2713aSLionel Sambuc return F;
191f4a2713aSLionel Sambuc }
192f4a2713aSLionel Sambuc
removeLock(FactManager & FM,const CapabilityExpr & CapE)193*0a6a1f1dSLionel Sambuc bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
194f4a2713aSLionel Sambuc unsigned n = FactIDs.size();
195f4a2713aSLionel Sambuc if (n == 0)
196f4a2713aSLionel Sambuc return false;
197f4a2713aSLionel Sambuc
198f4a2713aSLionel Sambuc for (unsigned i = 0; i < n-1; ++i) {
199*0a6a1f1dSLionel Sambuc if (FM[FactIDs[i]].matches(CapE)) {
200f4a2713aSLionel Sambuc FactIDs[i] = FactIDs[n-1];
201f4a2713aSLionel Sambuc FactIDs.pop_back();
202f4a2713aSLionel Sambuc return true;
203f4a2713aSLionel Sambuc }
204f4a2713aSLionel Sambuc }
205*0a6a1f1dSLionel Sambuc if (FM[FactIDs[n-1]].matches(CapE)) {
206f4a2713aSLionel Sambuc FactIDs.pop_back();
207f4a2713aSLionel Sambuc return true;
208f4a2713aSLionel Sambuc }
209f4a2713aSLionel Sambuc return false;
210f4a2713aSLionel Sambuc }
211f4a2713aSLionel Sambuc
findLockIter(FactManager & FM,const CapabilityExpr & CapE)212*0a6a1f1dSLionel Sambuc iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
213*0a6a1f1dSLionel Sambuc return std::find_if(begin(), end(), [&](FactID ID) {
214*0a6a1f1dSLionel Sambuc return FM[ID].matches(CapE);
215*0a6a1f1dSLionel Sambuc });
216f4a2713aSLionel Sambuc }
217f4a2713aSLionel Sambuc
findLock(FactManager & FM,const CapabilityExpr & CapE) const218*0a6a1f1dSLionel Sambuc FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
219*0a6a1f1dSLionel Sambuc auto I = std::find_if(begin(), end(), [&](FactID ID) {
220*0a6a1f1dSLionel Sambuc return FM[ID].matches(CapE);
221*0a6a1f1dSLionel Sambuc });
222*0a6a1f1dSLionel Sambuc return I != end() ? &FM[*I] : nullptr;
223f4a2713aSLionel Sambuc }
224f4a2713aSLionel Sambuc
findLockUniv(FactManager & FM,const CapabilityExpr & CapE) const225*0a6a1f1dSLionel Sambuc FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
226*0a6a1f1dSLionel Sambuc auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
227*0a6a1f1dSLionel Sambuc return FM[ID].matchesUniv(CapE);
228*0a6a1f1dSLionel Sambuc });
229*0a6a1f1dSLionel Sambuc return I != end() ? &FM[*I] : nullptr;
230f4a2713aSLionel Sambuc }
231f4a2713aSLionel Sambuc
findPartialMatch(FactManager & FM,const CapabilityExpr & CapE) const232*0a6a1f1dSLionel Sambuc FactEntry *findPartialMatch(FactManager &FM,
233*0a6a1f1dSLionel Sambuc const CapabilityExpr &CapE) const {
234*0a6a1f1dSLionel Sambuc auto I = std::find_if(begin(), end(), [&](FactID ID) {
235*0a6a1f1dSLionel Sambuc return FM[ID].partiallyMatches(CapE);
236*0a6a1f1dSLionel Sambuc });
237*0a6a1f1dSLionel Sambuc return I != end() ? &FM[*I] : nullptr;
238f4a2713aSLionel Sambuc }
239f4a2713aSLionel Sambuc };
240f4a2713aSLionel Sambuc
241f4a2713aSLionel Sambuc
242f4a2713aSLionel Sambuc typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
243f4a2713aSLionel Sambuc class LocalVariableMap;
244f4a2713aSLionel Sambuc
245f4a2713aSLionel Sambuc /// A side (entry or exit) of a CFG node.
246f4a2713aSLionel Sambuc enum CFGBlockSide { CBS_Entry, CBS_Exit };
247f4a2713aSLionel Sambuc
248f4a2713aSLionel Sambuc /// CFGBlockInfo is a struct which contains all the information that is
249f4a2713aSLionel Sambuc /// maintained for each block in the CFG. See LocalVariableMap for more
250f4a2713aSLionel Sambuc /// information about the contexts.
251f4a2713aSLionel Sambuc struct CFGBlockInfo {
252f4a2713aSLionel Sambuc FactSet EntrySet; // Lockset held at entry to block
253f4a2713aSLionel Sambuc FactSet ExitSet; // Lockset held at exit from block
254f4a2713aSLionel Sambuc LocalVarContext EntryContext; // Context held at entry to block
255f4a2713aSLionel Sambuc LocalVarContext ExitContext; // Context held at exit from block
256f4a2713aSLionel Sambuc SourceLocation EntryLoc; // Location of first statement in block
257f4a2713aSLionel Sambuc SourceLocation ExitLoc; // Location of last statement in block.
258f4a2713aSLionel Sambuc unsigned EntryIndex; // Used to replay contexts later
259f4a2713aSLionel Sambuc bool Reachable; // Is this block reachable?
260f4a2713aSLionel Sambuc
getSetclang::threadSafety::CFGBlockInfo261f4a2713aSLionel Sambuc const FactSet &getSet(CFGBlockSide Side) const {
262f4a2713aSLionel Sambuc return Side == CBS_Entry ? EntrySet : ExitSet;
263f4a2713aSLionel Sambuc }
getLocationclang::threadSafety::CFGBlockInfo264f4a2713aSLionel Sambuc SourceLocation getLocation(CFGBlockSide Side) const {
265f4a2713aSLionel Sambuc return Side == CBS_Entry ? EntryLoc : ExitLoc;
266f4a2713aSLionel Sambuc }
267f4a2713aSLionel Sambuc
268f4a2713aSLionel Sambuc private:
CFGBlockInfoclang::threadSafety::CFGBlockInfo269f4a2713aSLionel Sambuc CFGBlockInfo(LocalVarContext EmptyCtx)
270f4a2713aSLionel Sambuc : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
271f4a2713aSLionel Sambuc { }
272f4a2713aSLionel Sambuc
273f4a2713aSLionel Sambuc public:
274f4a2713aSLionel Sambuc static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
275f4a2713aSLionel Sambuc };
276f4a2713aSLionel Sambuc
277f4a2713aSLionel Sambuc
278f4a2713aSLionel Sambuc
279f4a2713aSLionel Sambuc // A LocalVariableMap maintains a map from local variables to their currently
280f4a2713aSLionel Sambuc // valid definitions. It provides SSA-like functionality when traversing the
281f4a2713aSLionel Sambuc // CFG. Like SSA, each definition or assignment to a variable is assigned a
282f4a2713aSLionel Sambuc // unique name (an integer), which acts as the SSA name for that definition.
283f4a2713aSLionel Sambuc // The total set of names is shared among all CFG basic blocks.
284f4a2713aSLionel Sambuc // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
285f4a2713aSLionel Sambuc // with their SSA-names. Instead, we compute a Context for each point in the
286f4a2713aSLionel Sambuc // code, which maps local variables to the appropriate SSA-name. This map
287f4a2713aSLionel Sambuc // changes with each assignment.
288f4a2713aSLionel Sambuc //
289f4a2713aSLionel Sambuc // The map is computed in a single pass over the CFG. Subsequent analyses can
290f4a2713aSLionel Sambuc // then query the map to find the appropriate Context for a statement, and use
291f4a2713aSLionel Sambuc // that Context to look up the definitions of variables.
292f4a2713aSLionel Sambuc class LocalVariableMap {
293f4a2713aSLionel Sambuc public:
294f4a2713aSLionel Sambuc typedef LocalVarContext Context;
295f4a2713aSLionel Sambuc
296f4a2713aSLionel Sambuc /// A VarDefinition consists of an expression, representing the value of the
297f4a2713aSLionel Sambuc /// variable, along with the context in which that expression should be
298f4a2713aSLionel Sambuc /// interpreted. A reference VarDefinition does not itself contain this
299f4a2713aSLionel Sambuc /// information, but instead contains a pointer to a previous VarDefinition.
300f4a2713aSLionel Sambuc struct VarDefinition {
301f4a2713aSLionel Sambuc public:
302f4a2713aSLionel Sambuc friend class LocalVariableMap;
303f4a2713aSLionel Sambuc
304f4a2713aSLionel Sambuc const NamedDecl *Dec; // The original declaration for this variable.
305f4a2713aSLionel Sambuc const Expr *Exp; // The expression for this variable, OR
306f4a2713aSLionel Sambuc unsigned Ref; // Reference to another VarDefinition
307f4a2713aSLionel Sambuc Context Ctx; // The map with which Exp should be interpreted.
308f4a2713aSLionel Sambuc
isReferenceclang::threadSafety::LocalVariableMap::VarDefinition309f4a2713aSLionel Sambuc bool isReference() { return !Exp; }
310f4a2713aSLionel Sambuc
311f4a2713aSLionel Sambuc private:
312f4a2713aSLionel Sambuc // Create ordinary variable definition
VarDefinitionclang::threadSafety::LocalVariableMap::VarDefinition313f4a2713aSLionel Sambuc VarDefinition(const NamedDecl *D, const Expr *E, Context C)
314f4a2713aSLionel Sambuc : Dec(D), Exp(E), Ref(0), Ctx(C)
315f4a2713aSLionel Sambuc { }
316f4a2713aSLionel Sambuc
317f4a2713aSLionel Sambuc // Create reference to previous definition
VarDefinitionclang::threadSafety::LocalVariableMap::VarDefinition318f4a2713aSLionel Sambuc VarDefinition(const NamedDecl *D, unsigned R, Context C)
319*0a6a1f1dSLionel Sambuc : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
320f4a2713aSLionel Sambuc { }
321f4a2713aSLionel Sambuc };
322f4a2713aSLionel Sambuc
323f4a2713aSLionel Sambuc private:
324f4a2713aSLionel Sambuc Context::Factory ContextFactory;
325f4a2713aSLionel Sambuc std::vector<VarDefinition> VarDefinitions;
326f4a2713aSLionel Sambuc std::vector<unsigned> CtxIndices;
327f4a2713aSLionel Sambuc std::vector<std::pair<Stmt*, Context> > SavedContexts;
328f4a2713aSLionel Sambuc
329f4a2713aSLionel Sambuc public:
LocalVariableMap()330f4a2713aSLionel Sambuc LocalVariableMap() {
331f4a2713aSLionel Sambuc // index 0 is a placeholder for undefined variables (aka phi-nodes).
332*0a6a1f1dSLionel Sambuc VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
333f4a2713aSLionel Sambuc }
334f4a2713aSLionel Sambuc
335f4a2713aSLionel Sambuc /// Look up a definition, within the given context.
lookup(const NamedDecl * D,Context Ctx)336f4a2713aSLionel Sambuc const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
337f4a2713aSLionel Sambuc const unsigned *i = Ctx.lookup(D);
338f4a2713aSLionel Sambuc if (!i)
339*0a6a1f1dSLionel Sambuc return nullptr;
340f4a2713aSLionel Sambuc assert(*i < VarDefinitions.size());
341f4a2713aSLionel Sambuc return &VarDefinitions[*i];
342f4a2713aSLionel Sambuc }
343f4a2713aSLionel Sambuc
344f4a2713aSLionel Sambuc /// Look up the definition for D within the given context. Returns
345f4a2713aSLionel Sambuc /// NULL if the expression is not statically known. If successful, also
346f4a2713aSLionel Sambuc /// modifies Ctx to hold the context of the return Expr.
lookupExpr(const NamedDecl * D,Context & Ctx)347f4a2713aSLionel Sambuc const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
348f4a2713aSLionel Sambuc const unsigned *P = Ctx.lookup(D);
349f4a2713aSLionel Sambuc if (!P)
350*0a6a1f1dSLionel Sambuc return nullptr;
351f4a2713aSLionel Sambuc
352f4a2713aSLionel Sambuc unsigned i = *P;
353f4a2713aSLionel Sambuc while (i > 0) {
354f4a2713aSLionel Sambuc if (VarDefinitions[i].Exp) {
355f4a2713aSLionel Sambuc Ctx = VarDefinitions[i].Ctx;
356f4a2713aSLionel Sambuc return VarDefinitions[i].Exp;
357f4a2713aSLionel Sambuc }
358f4a2713aSLionel Sambuc i = VarDefinitions[i].Ref;
359f4a2713aSLionel Sambuc }
360*0a6a1f1dSLionel Sambuc return nullptr;
361f4a2713aSLionel Sambuc }
362f4a2713aSLionel Sambuc
getEmptyContext()363f4a2713aSLionel Sambuc Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
364f4a2713aSLionel Sambuc
365f4a2713aSLionel Sambuc /// Return the next context after processing S. This function is used by
366f4a2713aSLionel Sambuc /// clients of the class to get the appropriate context when traversing the
367f4a2713aSLionel Sambuc /// CFG. It must be called for every assignment or DeclStmt.
getNextContext(unsigned & CtxIndex,Stmt * S,Context C)368f4a2713aSLionel Sambuc Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
369f4a2713aSLionel Sambuc if (SavedContexts[CtxIndex+1].first == S) {
370f4a2713aSLionel Sambuc CtxIndex++;
371f4a2713aSLionel Sambuc Context Result = SavedContexts[CtxIndex].second;
372f4a2713aSLionel Sambuc return Result;
373f4a2713aSLionel Sambuc }
374f4a2713aSLionel Sambuc return C;
375f4a2713aSLionel Sambuc }
376f4a2713aSLionel Sambuc
dumpVarDefinitionName(unsigned i)377f4a2713aSLionel Sambuc void dumpVarDefinitionName(unsigned i) {
378f4a2713aSLionel Sambuc if (i == 0) {
379f4a2713aSLionel Sambuc llvm::errs() << "Undefined";
380f4a2713aSLionel Sambuc return;
381f4a2713aSLionel Sambuc }
382f4a2713aSLionel Sambuc const NamedDecl *Dec = VarDefinitions[i].Dec;
383f4a2713aSLionel Sambuc if (!Dec) {
384f4a2713aSLionel Sambuc llvm::errs() << "<<NULL>>";
385f4a2713aSLionel Sambuc return;
386f4a2713aSLionel Sambuc }
387f4a2713aSLionel Sambuc Dec->printName(llvm::errs());
388f4a2713aSLionel Sambuc llvm::errs() << "." << i << " " << ((const void*) Dec);
389f4a2713aSLionel Sambuc }
390f4a2713aSLionel Sambuc
391f4a2713aSLionel Sambuc /// Dumps an ASCII representation of the variable map to llvm::errs()
dump()392f4a2713aSLionel Sambuc void dump() {
393f4a2713aSLionel Sambuc for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
394f4a2713aSLionel Sambuc const Expr *Exp = VarDefinitions[i].Exp;
395f4a2713aSLionel Sambuc unsigned Ref = VarDefinitions[i].Ref;
396f4a2713aSLionel Sambuc
397f4a2713aSLionel Sambuc dumpVarDefinitionName(i);
398f4a2713aSLionel Sambuc llvm::errs() << " = ";
399f4a2713aSLionel Sambuc if (Exp) Exp->dump();
400f4a2713aSLionel Sambuc else {
401f4a2713aSLionel Sambuc dumpVarDefinitionName(Ref);
402f4a2713aSLionel Sambuc llvm::errs() << "\n";
403f4a2713aSLionel Sambuc }
404f4a2713aSLionel Sambuc }
405f4a2713aSLionel Sambuc }
406f4a2713aSLionel Sambuc
407f4a2713aSLionel Sambuc /// Dumps an ASCII representation of a Context to llvm::errs()
dumpContext(Context C)408f4a2713aSLionel Sambuc void dumpContext(Context C) {
409f4a2713aSLionel Sambuc for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
410f4a2713aSLionel Sambuc const NamedDecl *D = I.getKey();
411f4a2713aSLionel Sambuc D->printName(llvm::errs());
412f4a2713aSLionel Sambuc const unsigned *i = C.lookup(D);
413f4a2713aSLionel Sambuc llvm::errs() << " -> ";
414f4a2713aSLionel Sambuc dumpVarDefinitionName(*i);
415f4a2713aSLionel Sambuc llvm::errs() << "\n";
416f4a2713aSLionel Sambuc }
417f4a2713aSLionel Sambuc }
418f4a2713aSLionel Sambuc
419f4a2713aSLionel Sambuc /// Builds the variable map.
420*0a6a1f1dSLionel Sambuc void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
421f4a2713aSLionel Sambuc std::vector<CFGBlockInfo> &BlockInfo);
422f4a2713aSLionel Sambuc
423f4a2713aSLionel Sambuc protected:
424f4a2713aSLionel Sambuc // Get the current context index
getContextIndex()425f4a2713aSLionel Sambuc unsigned getContextIndex() { return SavedContexts.size()-1; }
426f4a2713aSLionel Sambuc
427f4a2713aSLionel Sambuc // Save the current context for later replay
saveContext(Stmt * S,Context C)428f4a2713aSLionel Sambuc void saveContext(Stmt *S, Context C) {
429f4a2713aSLionel Sambuc SavedContexts.push_back(std::make_pair(S,C));
430f4a2713aSLionel Sambuc }
431f4a2713aSLionel Sambuc
432f4a2713aSLionel Sambuc // Adds a new definition to the given context, and returns a new context.
433f4a2713aSLionel Sambuc // This method should be called when declaring a new variable.
addDefinition(const NamedDecl * D,const Expr * Exp,Context Ctx)434*0a6a1f1dSLionel Sambuc Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
435f4a2713aSLionel Sambuc assert(!Ctx.contains(D));
436f4a2713aSLionel Sambuc unsigned newID = VarDefinitions.size();
437f4a2713aSLionel Sambuc Context NewCtx = ContextFactory.add(Ctx, D, newID);
438f4a2713aSLionel Sambuc VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
439f4a2713aSLionel Sambuc return NewCtx;
440f4a2713aSLionel Sambuc }
441f4a2713aSLionel Sambuc
442f4a2713aSLionel Sambuc // Add a new reference to an existing definition.
addReference(const NamedDecl * D,unsigned i,Context Ctx)443f4a2713aSLionel Sambuc Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
444f4a2713aSLionel Sambuc unsigned newID = VarDefinitions.size();
445f4a2713aSLionel Sambuc Context NewCtx = ContextFactory.add(Ctx, D, newID);
446f4a2713aSLionel Sambuc VarDefinitions.push_back(VarDefinition(D, i, Ctx));
447f4a2713aSLionel Sambuc return NewCtx;
448f4a2713aSLionel Sambuc }
449f4a2713aSLionel Sambuc
450f4a2713aSLionel Sambuc // Updates a definition only if that definition is already in the map.
451f4a2713aSLionel Sambuc // This method should be called when assigning to an existing variable.
updateDefinition(const NamedDecl * D,Expr * Exp,Context Ctx)452f4a2713aSLionel Sambuc Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
453f4a2713aSLionel Sambuc if (Ctx.contains(D)) {
454f4a2713aSLionel Sambuc unsigned newID = VarDefinitions.size();
455f4a2713aSLionel Sambuc Context NewCtx = ContextFactory.remove(Ctx, D);
456f4a2713aSLionel Sambuc NewCtx = ContextFactory.add(NewCtx, D, newID);
457f4a2713aSLionel Sambuc VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
458f4a2713aSLionel Sambuc return NewCtx;
459f4a2713aSLionel Sambuc }
460f4a2713aSLionel Sambuc return Ctx;
461f4a2713aSLionel Sambuc }
462f4a2713aSLionel Sambuc
463f4a2713aSLionel Sambuc // Removes a definition from the context, but keeps the variable name
464f4a2713aSLionel Sambuc // as a valid variable. The index 0 is a placeholder for cleared definitions.
clearDefinition(const NamedDecl * D,Context Ctx)465f4a2713aSLionel Sambuc Context clearDefinition(const NamedDecl *D, Context Ctx) {
466f4a2713aSLionel Sambuc Context NewCtx = Ctx;
467f4a2713aSLionel Sambuc if (NewCtx.contains(D)) {
468f4a2713aSLionel Sambuc NewCtx = ContextFactory.remove(NewCtx, D);
469f4a2713aSLionel Sambuc NewCtx = ContextFactory.add(NewCtx, D, 0);
470f4a2713aSLionel Sambuc }
471f4a2713aSLionel Sambuc return NewCtx;
472f4a2713aSLionel Sambuc }
473f4a2713aSLionel Sambuc
474f4a2713aSLionel Sambuc // Remove a definition entirely frmo the context.
removeDefinition(const NamedDecl * D,Context Ctx)475f4a2713aSLionel Sambuc Context removeDefinition(const NamedDecl *D, Context Ctx) {
476f4a2713aSLionel Sambuc Context NewCtx = Ctx;
477f4a2713aSLionel Sambuc if (NewCtx.contains(D)) {
478f4a2713aSLionel Sambuc NewCtx = ContextFactory.remove(NewCtx, D);
479f4a2713aSLionel Sambuc }
480f4a2713aSLionel Sambuc return NewCtx;
481f4a2713aSLionel Sambuc }
482f4a2713aSLionel Sambuc
483f4a2713aSLionel Sambuc Context intersectContexts(Context C1, Context C2);
484f4a2713aSLionel Sambuc Context createReferenceContext(Context C);
485f4a2713aSLionel Sambuc void intersectBackEdge(Context C1, Context C2);
486f4a2713aSLionel Sambuc
487f4a2713aSLionel Sambuc friend class VarMapBuilder;
488f4a2713aSLionel Sambuc };
489f4a2713aSLionel Sambuc
490f4a2713aSLionel Sambuc
491f4a2713aSLionel Sambuc // This has to be defined after LocalVariableMap.
getEmptyBlockInfo(LocalVariableMap & M)492f4a2713aSLionel Sambuc CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
493f4a2713aSLionel Sambuc return CFGBlockInfo(M.getEmptyContext());
494f4a2713aSLionel Sambuc }
495f4a2713aSLionel Sambuc
496f4a2713aSLionel Sambuc
497f4a2713aSLionel Sambuc /// Visitor which builds a LocalVariableMap
498f4a2713aSLionel Sambuc class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
499f4a2713aSLionel Sambuc public:
500f4a2713aSLionel Sambuc LocalVariableMap* VMap;
501f4a2713aSLionel Sambuc LocalVariableMap::Context Ctx;
502f4a2713aSLionel Sambuc
VarMapBuilder(LocalVariableMap * VM,LocalVariableMap::Context C)503f4a2713aSLionel Sambuc VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
504f4a2713aSLionel Sambuc : VMap(VM), Ctx(C) {}
505f4a2713aSLionel Sambuc
506f4a2713aSLionel Sambuc void VisitDeclStmt(DeclStmt *S);
507f4a2713aSLionel Sambuc void VisitBinaryOperator(BinaryOperator *BO);
508f4a2713aSLionel Sambuc };
509f4a2713aSLionel Sambuc
510f4a2713aSLionel Sambuc
511f4a2713aSLionel Sambuc // Add new local variables to the variable map
VisitDeclStmt(DeclStmt * S)512f4a2713aSLionel Sambuc void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
513f4a2713aSLionel Sambuc bool modifiedCtx = false;
514f4a2713aSLionel Sambuc DeclGroupRef DGrp = S->getDeclGroup();
515*0a6a1f1dSLionel Sambuc for (const auto *D : DGrp) {
516*0a6a1f1dSLionel Sambuc if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
517*0a6a1f1dSLionel Sambuc const Expr *E = VD->getInit();
518f4a2713aSLionel Sambuc
519f4a2713aSLionel Sambuc // Add local variables with trivial type to the variable map
520f4a2713aSLionel Sambuc QualType T = VD->getType();
521f4a2713aSLionel Sambuc if (T.isTrivialType(VD->getASTContext())) {
522f4a2713aSLionel Sambuc Ctx = VMap->addDefinition(VD, E, Ctx);
523f4a2713aSLionel Sambuc modifiedCtx = true;
524f4a2713aSLionel Sambuc }
525f4a2713aSLionel Sambuc }
526f4a2713aSLionel Sambuc }
527f4a2713aSLionel Sambuc if (modifiedCtx)
528f4a2713aSLionel Sambuc VMap->saveContext(S, Ctx);
529f4a2713aSLionel Sambuc }
530f4a2713aSLionel Sambuc
531f4a2713aSLionel Sambuc // Update local variable definitions in variable map
VisitBinaryOperator(BinaryOperator * BO)532f4a2713aSLionel Sambuc void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
533f4a2713aSLionel Sambuc if (!BO->isAssignmentOp())
534f4a2713aSLionel Sambuc return;
535f4a2713aSLionel Sambuc
536f4a2713aSLionel Sambuc Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
537f4a2713aSLionel Sambuc
538f4a2713aSLionel Sambuc // Update the variable map and current context.
539f4a2713aSLionel Sambuc if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
540f4a2713aSLionel Sambuc ValueDecl *VDec = DRE->getDecl();
541f4a2713aSLionel Sambuc if (Ctx.lookup(VDec)) {
542f4a2713aSLionel Sambuc if (BO->getOpcode() == BO_Assign)
543f4a2713aSLionel Sambuc Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
544f4a2713aSLionel Sambuc else
545f4a2713aSLionel Sambuc // FIXME -- handle compound assignment operators
546f4a2713aSLionel Sambuc Ctx = VMap->clearDefinition(VDec, Ctx);
547f4a2713aSLionel Sambuc VMap->saveContext(BO, Ctx);
548f4a2713aSLionel Sambuc }
549f4a2713aSLionel Sambuc }
550f4a2713aSLionel Sambuc }
551f4a2713aSLionel Sambuc
552f4a2713aSLionel Sambuc
553f4a2713aSLionel Sambuc // Computes the intersection of two contexts. The intersection is the
554f4a2713aSLionel Sambuc // set of variables which have the same definition in both contexts;
555f4a2713aSLionel Sambuc // variables with different definitions are discarded.
556f4a2713aSLionel Sambuc LocalVariableMap::Context
intersectContexts(Context C1,Context C2)557f4a2713aSLionel Sambuc LocalVariableMap::intersectContexts(Context C1, Context C2) {
558f4a2713aSLionel Sambuc Context Result = C1;
559*0a6a1f1dSLionel Sambuc for (const auto &P : C1) {
560*0a6a1f1dSLionel Sambuc const NamedDecl *Dec = P.first;
561f4a2713aSLionel Sambuc const unsigned *i2 = C2.lookup(Dec);
562f4a2713aSLionel Sambuc if (!i2) // variable doesn't exist on second path
563f4a2713aSLionel Sambuc Result = removeDefinition(Dec, Result);
564*0a6a1f1dSLionel Sambuc else if (*i2 != P.second) // variable exists, but has different definition
565f4a2713aSLionel Sambuc Result = clearDefinition(Dec, Result);
566f4a2713aSLionel Sambuc }
567f4a2713aSLionel Sambuc return Result;
568f4a2713aSLionel Sambuc }
569f4a2713aSLionel Sambuc
570f4a2713aSLionel Sambuc // For every variable in C, create a new variable that refers to the
571f4a2713aSLionel Sambuc // definition in C. Return a new context that contains these new variables.
572f4a2713aSLionel Sambuc // (We use this for a naive implementation of SSA on loop back-edges.)
createReferenceContext(Context C)573f4a2713aSLionel Sambuc LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
574f4a2713aSLionel Sambuc Context Result = getEmptyContext();
575*0a6a1f1dSLionel Sambuc for (const auto &P : C)
576*0a6a1f1dSLionel Sambuc Result = addReference(P.first, P.second, Result);
577f4a2713aSLionel Sambuc return Result;
578f4a2713aSLionel Sambuc }
579f4a2713aSLionel Sambuc
580f4a2713aSLionel Sambuc // This routine also takes the intersection of C1 and C2, but it does so by
581f4a2713aSLionel Sambuc // altering the VarDefinitions. C1 must be the result of an earlier call to
582f4a2713aSLionel Sambuc // createReferenceContext.
intersectBackEdge(Context C1,Context C2)583f4a2713aSLionel Sambuc void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
584*0a6a1f1dSLionel Sambuc for (const auto &P : C1) {
585*0a6a1f1dSLionel Sambuc unsigned i1 = P.second;
586f4a2713aSLionel Sambuc VarDefinition *VDef = &VarDefinitions[i1];
587f4a2713aSLionel Sambuc assert(VDef->isReference());
588f4a2713aSLionel Sambuc
589*0a6a1f1dSLionel Sambuc const unsigned *i2 = C2.lookup(P.first);
590f4a2713aSLionel Sambuc if (!i2 || (*i2 != i1))
591f4a2713aSLionel Sambuc VDef->Ref = 0; // Mark this variable as undefined
592f4a2713aSLionel Sambuc }
593f4a2713aSLionel Sambuc }
594f4a2713aSLionel Sambuc
595f4a2713aSLionel Sambuc
596f4a2713aSLionel Sambuc // Traverse the CFG in topological order, so all predecessors of a block
597f4a2713aSLionel Sambuc // (excluding back-edges) are visited before the block itself. At
598f4a2713aSLionel Sambuc // each point in the code, we calculate a Context, which holds the set of
599f4a2713aSLionel Sambuc // variable definitions which are visible at that point in execution.
600f4a2713aSLionel Sambuc // Visible variables are mapped to their definitions using an array that
601f4a2713aSLionel Sambuc // contains all definitions.
602f4a2713aSLionel Sambuc //
603f4a2713aSLionel Sambuc // At join points in the CFG, the set is computed as the intersection of
604f4a2713aSLionel Sambuc // the incoming sets along each edge, E.g.
605f4a2713aSLionel Sambuc //
606f4a2713aSLionel Sambuc // { Context | VarDefinitions }
607f4a2713aSLionel Sambuc // int x = 0; { x -> x1 | x1 = 0 }
608f4a2713aSLionel Sambuc // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
609f4a2713aSLionel Sambuc // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
610f4a2713aSLionel Sambuc // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
611f4a2713aSLionel Sambuc // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
612f4a2713aSLionel Sambuc //
613f4a2713aSLionel Sambuc // This is essentially a simpler and more naive version of the standard SSA
614f4a2713aSLionel Sambuc // algorithm. Those definitions that remain in the intersection are from blocks
615f4a2713aSLionel Sambuc // that strictly dominate the current block. We do not bother to insert proper
616f4a2713aSLionel Sambuc // phi nodes, because they are not used in our analysis; instead, wherever
617f4a2713aSLionel Sambuc // a phi node would be required, we simply remove that definition from the
618f4a2713aSLionel Sambuc // context (E.g. x above).
619f4a2713aSLionel Sambuc //
620f4a2713aSLionel Sambuc // The initial traversal does not capture back-edges, so those need to be
621f4a2713aSLionel Sambuc // handled on a separate pass. Whenever the first pass encounters an
622f4a2713aSLionel Sambuc // incoming back edge, it duplicates the context, creating new definitions
623f4a2713aSLionel Sambuc // that refer back to the originals. (These correspond to places where SSA
624f4a2713aSLionel Sambuc // might have to insert a phi node.) On the second pass, these definitions are
625f4a2713aSLionel Sambuc // set to NULL if the variable has changed on the back-edge (i.e. a phi
626f4a2713aSLionel Sambuc // node was actually required.) E.g.
627f4a2713aSLionel Sambuc //
628f4a2713aSLionel Sambuc // { Context | VarDefinitions }
629f4a2713aSLionel Sambuc // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
630f4a2713aSLionel Sambuc // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
631f4a2713aSLionel Sambuc // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
632f4a2713aSLionel Sambuc // ... { y -> y1 | x3 = 2, x2 = 1, ... }
633f4a2713aSLionel Sambuc //
traverseCFG(CFG * CFGraph,const PostOrderCFGView * SortedGraph,std::vector<CFGBlockInfo> & BlockInfo)634f4a2713aSLionel Sambuc void LocalVariableMap::traverseCFG(CFG *CFGraph,
635*0a6a1f1dSLionel Sambuc const PostOrderCFGView *SortedGraph,
636f4a2713aSLionel Sambuc std::vector<CFGBlockInfo> &BlockInfo) {
637f4a2713aSLionel Sambuc PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
638f4a2713aSLionel Sambuc
639f4a2713aSLionel Sambuc CtxIndices.resize(CFGraph->getNumBlockIDs());
640f4a2713aSLionel Sambuc
641*0a6a1f1dSLionel Sambuc for (const auto *CurrBlock : *SortedGraph) {
642f4a2713aSLionel Sambuc int CurrBlockID = CurrBlock->getBlockID();
643f4a2713aSLionel Sambuc CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
644f4a2713aSLionel Sambuc
645f4a2713aSLionel Sambuc VisitedBlocks.insert(CurrBlock);
646f4a2713aSLionel Sambuc
647f4a2713aSLionel Sambuc // Calculate the entry context for the current block
648f4a2713aSLionel Sambuc bool HasBackEdges = false;
649f4a2713aSLionel Sambuc bool CtxInit = true;
650f4a2713aSLionel Sambuc for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
651f4a2713aSLionel Sambuc PE = CurrBlock->pred_end(); PI != PE; ++PI) {
652f4a2713aSLionel Sambuc // if *PI -> CurrBlock is a back edge, so skip it
653*0a6a1f1dSLionel Sambuc if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
654f4a2713aSLionel Sambuc HasBackEdges = true;
655f4a2713aSLionel Sambuc continue;
656f4a2713aSLionel Sambuc }
657f4a2713aSLionel Sambuc
658f4a2713aSLionel Sambuc int PrevBlockID = (*PI)->getBlockID();
659f4a2713aSLionel Sambuc CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
660f4a2713aSLionel Sambuc
661f4a2713aSLionel Sambuc if (CtxInit) {
662f4a2713aSLionel Sambuc CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
663f4a2713aSLionel Sambuc CtxInit = false;
664f4a2713aSLionel Sambuc }
665f4a2713aSLionel Sambuc else {
666f4a2713aSLionel Sambuc CurrBlockInfo->EntryContext =
667f4a2713aSLionel Sambuc intersectContexts(CurrBlockInfo->EntryContext,
668f4a2713aSLionel Sambuc PrevBlockInfo->ExitContext);
669f4a2713aSLionel Sambuc }
670f4a2713aSLionel Sambuc }
671f4a2713aSLionel Sambuc
672f4a2713aSLionel Sambuc // Duplicate the context if we have back-edges, so we can call
673f4a2713aSLionel Sambuc // intersectBackEdges later.
674f4a2713aSLionel Sambuc if (HasBackEdges)
675f4a2713aSLionel Sambuc CurrBlockInfo->EntryContext =
676f4a2713aSLionel Sambuc createReferenceContext(CurrBlockInfo->EntryContext);
677f4a2713aSLionel Sambuc
678f4a2713aSLionel Sambuc // Create a starting context index for the current block
679*0a6a1f1dSLionel Sambuc saveContext(nullptr, CurrBlockInfo->EntryContext);
680f4a2713aSLionel Sambuc CurrBlockInfo->EntryIndex = getContextIndex();
681f4a2713aSLionel Sambuc
682f4a2713aSLionel Sambuc // Visit all the statements in the basic block.
683f4a2713aSLionel Sambuc VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
684f4a2713aSLionel Sambuc for (CFGBlock::const_iterator BI = CurrBlock->begin(),
685f4a2713aSLionel Sambuc BE = CurrBlock->end(); BI != BE; ++BI) {
686f4a2713aSLionel Sambuc switch (BI->getKind()) {
687f4a2713aSLionel Sambuc case CFGElement::Statement: {
688f4a2713aSLionel Sambuc CFGStmt CS = BI->castAs<CFGStmt>();
689f4a2713aSLionel Sambuc VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
690f4a2713aSLionel Sambuc break;
691f4a2713aSLionel Sambuc }
692f4a2713aSLionel Sambuc default:
693f4a2713aSLionel Sambuc break;
694f4a2713aSLionel Sambuc }
695f4a2713aSLionel Sambuc }
696f4a2713aSLionel Sambuc CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
697f4a2713aSLionel Sambuc
698f4a2713aSLionel Sambuc // Mark variables on back edges as "unknown" if they've been changed.
699f4a2713aSLionel Sambuc for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
700f4a2713aSLionel Sambuc SE = CurrBlock->succ_end(); SI != SE; ++SI) {
701f4a2713aSLionel Sambuc // if CurrBlock -> *SI is *not* a back edge
702*0a6a1f1dSLionel Sambuc if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
703f4a2713aSLionel Sambuc continue;
704f4a2713aSLionel Sambuc
705f4a2713aSLionel Sambuc CFGBlock *FirstLoopBlock = *SI;
706f4a2713aSLionel Sambuc Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
707f4a2713aSLionel Sambuc Context LoopEnd = CurrBlockInfo->ExitContext;
708f4a2713aSLionel Sambuc intersectBackEdge(LoopBegin, LoopEnd);
709f4a2713aSLionel Sambuc }
710f4a2713aSLionel Sambuc }
711f4a2713aSLionel Sambuc
712f4a2713aSLionel Sambuc // Put an extra entry at the end of the indexed context array
713f4a2713aSLionel Sambuc unsigned exitID = CFGraph->getExit().getBlockID();
714*0a6a1f1dSLionel Sambuc saveContext(nullptr, BlockInfo[exitID].ExitContext);
715f4a2713aSLionel Sambuc }
716f4a2713aSLionel Sambuc
717f4a2713aSLionel Sambuc /// Find the appropriate source locations to use when producing diagnostics for
718f4a2713aSLionel Sambuc /// each block in the CFG.
findBlockLocations(CFG * CFGraph,const PostOrderCFGView * SortedGraph,std::vector<CFGBlockInfo> & BlockInfo)719f4a2713aSLionel Sambuc static void findBlockLocations(CFG *CFGraph,
720*0a6a1f1dSLionel Sambuc const PostOrderCFGView *SortedGraph,
721f4a2713aSLionel Sambuc std::vector<CFGBlockInfo> &BlockInfo) {
722*0a6a1f1dSLionel Sambuc for (const auto *CurrBlock : *SortedGraph) {
723f4a2713aSLionel Sambuc CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
724f4a2713aSLionel Sambuc
725f4a2713aSLionel Sambuc // Find the source location of the last statement in the block, if the
726f4a2713aSLionel Sambuc // block is not empty.
727f4a2713aSLionel Sambuc if (const Stmt *S = CurrBlock->getTerminator()) {
728f4a2713aSLionel Sambuc CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
729f4a2713aSLionel Sambuc } else {
730f4a2713aSLionel Sambuc for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
731f4a2713aSLionel Sambuc BE = CurrBlock->rend(); BI != BE; ++BI) {
732f4a2713aSLionel Sambuc // FIXME: Handle other CFGElement kinds.
733f4a2713aSLionel Sambuc if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
734f4a2713aSLionel Sambuc CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
735f4a2713aSLionel Sambuc break;
736f4a2713aSLionel Sambuc }
737f4a2713aSLionel Sambuc }
738f4a2713aSLionel Sambuc }
739f4a2713aSLionel Sambuc
740f4a2713aSLionel Sambuc if (!CurrBlockInfo->ExitLoc.isInvalid()) {
741f4a2713aSLionel Sambuc // This block contains at least one statement. Find the source location
742f4a2713aSLionel Sambuc // of the first statement in the block.
743f4a2713aSLionel Sambuc for (CFGBlock::const_iterator BI = CurrBlock->begin(),
744f4a2713aSLionel Sambuc BE = CurrBlock->end(); BI != BE; ++BI) {
745f4a2713aSLionel Sambuc // FIXME: Handle other CFGElement kinds.
746f4a2713aSLionel Sambuc if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
747f4a2713aSLionel Sambuc CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
748f4a2713aSLionel Sambuc break;
749f4a2713aSLionel Sambuc }
750f4a2713aSLionel Sambuc }
751f4a2713aSLionel Sambuc } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
752f4a2713aSLionel Sambuc CurrBlock != &CFGraph->getExit()) {
753f4a2713aSLionel Sambuc // The block is empty, and has a single predecessor. Use its exit
754f4a2713aSLionel Sambuc // location.
755f4a2713aSLionel Sambuc CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
756f4a2713aSLionel Sambuc BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
757f4a2713aSLionel Sambuc }
758f4a2713aSLionel Sambuc }
759f4a2713aSLionel Sambuc }
760f4a2713aSLionel Sambuc
761*0a6a1f1dSLionel Sambuc class LockableFactEntry : public FactEntry {
762*0a6a1f1dSLionel Sambuc private:
763*0a6a1f1dSLionel Sambuc bool Managed; ///< managed by ScopedLockable object
764*0a6a1f1dSLionel Sambuc
765*0a6a1f1dSLionel Sambuc public:
LockableFactEntry(const CapabilityExpr & CE,LockKind LK,SourceLocation Loc,bool Mng=false,bool Asrt=false)766*0a6a1f1dSLionel Sambuc LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
767*0a6a1f1dSLionel Sambuc bool Mng = false, bool Asrt = false)
768*0a6a1f1dSLionel Sambuc : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
769*0a6a1f1dSLionel Sambuc
770*0a6a1f1dSLionel Sambuc void
handleRemovalFromIntersection(const FactSet & FSet,FactManager & FactMan,SourceLocation JoinLoc,LockErrorKind LEK,ThreadSafetyHandler & Handler) const771*0a6a1f1dSLionel Sambuc handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
772*0a6a1f1dSLionel Sambuc SourceLocation JoinLoc, LockErrorKind LEK,
773*0a6a1f1dSLionel Sambuc ThreadSafetyHandler &Handler) const override {
774*0a6a1f1dSLionel Sambuc if (!Managed && !asserted() && !negative() && !isUniversal()) {
775*0a6a1f1dSLionel Sambuc Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
776*0a6a1f1dSLionel Sambuc LEK);
777*0a6a1f1dSLionel Sambuc }
778*0a6a1f1dSLionel Sambuc }
779*0a6a1f1dSLionel Sambuc
handleUnlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,ThreadSafetyHandler & Handler,StringRef DiagKind) const780*0a6a1f1dSLionel Sambuc void handleUnlock(FactSet &FSet, FactManager &FactMan,
781*0a6a1f1dSLionel Sambuc const CapabilityExpr &Cp, SourceLocation UnlockLoc,
782*0a6a1f1dSLionel Sambuc bool FullyRemove, ThreadSafetyHandler &Handler,
783*0a6a1f1dSLionel Sambuc StringRef DiagKind) const override {
784*0a6a1f1dSLionel Sambuc FSet.removeLock(FactMan, Cp);
785*0a6a1f1dSLionel Sambuc if (!Cp.negative()) {
786*0a6a1f1dSLionel Sambuc FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
787*0a6a1f1dSLionel Sambuc !Cp, LK_Exclusive, UnlockLoc));
788*0a6a1f1dSLionel Sambuc }
789*0a6a1f1dSLionel Sambuc }
790*0a6a1f1dSLionel Sambuc };
791*0a6a1f1dSLionel Sambuc
792*0a6a1f1dSLionel Sambuc class ScopedLockableFactEntry : public FactEntry {
793*0a6a1f1dSLionel Sambuc private:
794*0a6a1f1dSLionel Sambuc SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
795*0a6a1f1dSLionel Sambuc
796*0a6a1f1dSLionel Sambuc public:
ScopedLockableFactEntry(const CapabilityExpr & CE,SourceLocation Loc,const CapExprSet & Excl,const CapExprSet & Shrd)797*0a6a1f1dSLionel Sambuc ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
798*0a6a1f1dSLionel Sambuc const CapExprSet &Excl, const CapExprSet &Shrd)
799*0a6a1f1dSLionel Sambuc : FactEntry(CE, LK_Exclusive, Loc, false) {
800*0a6a1f1dSLionel Sambuc for (const auto &M : Excl)
801*0a6a1f1dSLionel Sambuc UnderlyingMutexes.push_back(M.sexpr());
802*0a6a1f1dSLionel Sambuc for (const auto &M : Shrd)
803*0a6a1f1dSLionel Sambuc UnderlyingMutexes.push_back(M.sexpr());
804*0a6a1f1dSLionel Sambuc }
805*0a6a1f1dSLionel Sambuc
806*0a6a1f1dSLionel Sambuc void
handleRemovalFromIntersection(const FactSet & FSet,FactManager & FactMan,SourceLocation JoinLoc,LockErrorKind LEK,ThreadSafetyHandler & Handler) const807*0a6a1f1dSLionel Sambuc handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
808*0a6a1f1dSLionel Sambuc SourceLocation JoinLoc, LockErrorKind LEK,
809*0a6a1f1dSLionel Sambuc ThreadSafetyHandler &Handler) const override {
810*0a6a1f1dSLionel Sambuc for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
811*0a6a1f1dSLionel Sambuc if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
812*0a6a1f1dSLionel Sambuc // If this scoped lock manages another mutex, and if the underlying
813*0a6a1f1dSLionel Sambuc // mutex is still held, then warn about the underlying mutex.
814*0a6a1f1dSLionel Sambuc Handler.handleMutexHeldEndOfScope(
815*0a6a1f1dSLionel Sambuc "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
816*0a6a1f1dSLionel Sambuc }
817*0a6a1f1dSLionel Sambuc }
818*0a6a1f1dSLionel Sambuc }
819*0a6a1f1dSLionel Sambuc
handleUnlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,ThreadSafetyHandler & Handler,StringRef DiagKind) const820*0a6a1f1dSLionel Sambuc void handleUnlock(FactSet &FSet, FactManager &FactMan,
821*0a6a1f1dSLionel Sambuc const CapabilityExpr &Cp, SourceLocation UnlockLoc,
822*0a6a1f1dSLionel Sambuc bool FullyRemove, ThreadSafetyHandler &Handler,
823*0a6a1f1dSLionel Sambuc StringRef DiagKind) const override {
824*0a6a1f1dSLionel Sambuc assert(!Cp.negative() && "Managing object cannot be negative.");
825*0a6a1f1dSLionel Sambuc for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
826*0a6a1f1dSLionel Sambuc CapabilityExpr UnderCp(UnderlyingMutex, false);
827*0a6a1f1dSLionel Sambuc auto UnderEntry = llvm::make_unique<LockableFactEntry>(
828*0a6a1f1dSLionel Sambuc !UnderCp, LK_Exclusive, UnlockLoc);
829*0a6a1f1dSLionel Sambuc
830*0a6a1f1dSLionel Sambuc if (FullyRemove) {
831*0a6a1f1dSLionel Sambuc // We're destroying the managing object.
832*0a6a1f1dSLionel Sambuc // Remove the underlying mutex if it exists; but don't warn.
833*0a6a1f1dSLionel Sambuc if (FSet.findLock(FactMan, UnderCp)) {
834*0a6a1f1dSLionel Sambuc FSet.removeLock(FactMan, UnderCp);
835*0a6a1f1dSLionel Sambuc FSet.addLock(FactMan, std::move(UnderEntry));
836*0a6a1f1dSLionel Sambuc }
837*0a6a1f1dSLionel Sambuc } else {
838*0a6a1f1dSLionel Sambuc // We're releasing the underlying mutex, but not destroying the
839*0a6a1f1dSLionel Sambuc // managing object. Warn on dual release.
840*0a6a1f1dSLionel Sambuc if (!FSet.findLock(FactMan, UnderCp)) {
841*0a6a1f1dSLionel Sambuc Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
842*0a6a1f1dSLionel Sambuc UnlockLoc);
843*0a6a1f1dSLionel Sambuc }
844*0a6a1f1dSLionel Sambuc FSet.removeLock(FactMan, UnderCp);
845*0a6a1f1dSLionel Sambuc FSet.addLock(FactMan, std::move(UnderEntry));
846*0a6a1f1dSLionel Sambuc }
847*0a6a1f1dSLionel Sambuc }
848*0a6a1f1dSLionel Sambuc if (FullyRemove)
849*0a6a1f1dSLionel Sambuc FSet.removeLock(FactMan, Cp);
850*0a6a1f1dSLionel Sambuc }
851*0a6a1f1dSLionel Sambuc };
852*0a6a1f1dSLionel Sambuc
853f4a2713aSLionel Sambuc /// \brief Class which implements the core thread safety analysis routines.
854f4a2713aSLionel Sambuc class ThreadSafetyAnalyzer {
855f4a2713aSLionel Sambuc friend class BuildLockset;
856f4a2713aSLionel Sambuc
857*0a6a1f1dSLionel Sambuc llvm::BumpPtrAllocator Bpa;
858*0a6a1f1dSLionel Sambuc threadSafety::til::MemRegionRef Arena;
859*0a6a1f1dSLionel Sambuc threadSafety::SExprBuilder SxBuilder;
860*0a6a1f1dSLionel Sambuc
861f4a2713aSLionel Sambuc ThreadSafetyHandler &Handler;
862*0a6a1f1dSLionel Sambuc const CXXMethodDecl *CurrentMethod;
863f4a2713aSLionel Sambuc LocalVariableMap LocalVarMap;
864f4a2713aSLionel Sambuc FactManager FactMan;
865f4a2713aSLionel Sambuc std::vector<CFGBlockInfo> BlockInfo;
866f4a2713aSLionel Sambuc
867f4a2713aSLionel Sambuc public:
ThreadSafetyAnalyzer(ThreadSafetyHandler & H)868*0a6a1f1dSLionel Sambuc ThreadSafetyAnalyzer(ThreadSafetyHandler &H)
869*0a6a1f1dSLionel Sambuc : Arena(&Bpa), SxBuilder(Arena), Handler(H) {}
870f4a2713aSLionel Sambuc
871*0a6a1f1dSLionel Sambuc bool inCurrentScope(const CapabilityExpr &CapE);
872*0a6a1f1dSLionel Sambuc
873*0a6a1f1dSLionel Sambuc void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
874*0a6a1f1dSLionel Sambuc StringRef DiagKind, bool ReqAttr = false);
875*0a6a1f1dSLionel Sambuc void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
876*0a6a1f1dSLionel Sambuc SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
877*0a6a1f1dSLionel Sambuc StringRef DiagKind);
878f4a2713aSLionel Sambuc
879f4a2713aSLionel Sambuc template <typename AttrType>
880*0a6a1f1dSLionel Sambuc void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
881*0a6a1f1dSLionel Sambuc const NamedDecl *D, VarDecl *SelfDecl = nullptr);
882f4a2713aSLionel Sambuc
883f4a2713aSLionel Sambuc template <class AttrType>
884*0a6a1f1dSLionel Sambuc void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
885f4a2713aSLionel Sambuc const NamedDecl *D,
886f4a2713aSLionel Sambuc const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
887f4a2713aSLionel Sambuc Expr *BrE, bool Neg);
888f4a2713aSLionel Sambuc
889f4a2713aSLionel Sambuc const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
890f4a2713aSLionel Sambuc bool &Negate);
891f4a2713aSLionel Sambuc
892f4a2713aSLionel Sambuc void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
893f4a2713aSLionel Sambuc const CFGBlock* PredBlock,
894f4a2713aSLionel Sambuc const CFGBlock *CurrBlock);
895f4a2713aSLionel Sambuc
896f4a2713aSLionel Sambuc void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
897f4a2713aSLionel Sambuc SourceLocation JoinLoc,
898f4a2713aSLionel Sambuc LockErrorKind LEK1, LockErrorKind LEK2,
899f4a2713aSLionel Sambuc bool Modify=true);
900f4a2713aSLionel Sambuc
intersectAndWarn(FactSet & FSet1,const FactSet & FSet2,SourceLocation JoinLoc,LockErrorKind LEK1,bool Modify=true)901f4a2713aSLionel Sambuc void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
902f4a2713aSLionel Sambuc SourceLocation JoinLoc, LockErrorKind LEK1,
903f4a2713aSLionel Sambuc bool Modify=true) {
904f4a2713aSLionel Sambuc intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
905f4a2713aSLionel Sambuc }
906f4a2713aSLionel Sambuc
907f4a2713aSLionel Sambuc void runAnalysis(AnalysisDeclContext &AC);
908f4a2713aSLionel Sambuc };
909f4a2713aSLionel Sambuc
910*0a6a1f1dSLionel Sambuc /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
getValueDecl(const Expr * Exp)911*0a6a1f1dSLionel Sambuc static const ValueDecl *getValueDecl(const Expr *Exp) {
912*0a6a1f1dSLionel Sambuc if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
913*0a6a1f1dSLionel Sambuc return getValueDecl(CE->getSubExpr());
914*0a6a1f1dSLionel Sambuc
915*0a6a1f1dSLionel Sambuc if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
916*0a6a1f1dSLionel Sambuc return DR->getDecl();
917*0a6a1f1dSLionel Sambuc
918*0a6a1f1dSLionel Sambuc if (const auto *ME = dyn_cast<MemberExpr>(Exp))
919*0a6a1f1dSLionel Sambuc return ME->getMemberDecl();
920*0a6a1f1dSLionel Sambuc
921*0a6a1f1dSLionel Sambuc return nullptr;
922*0a6a1f1dSLionel Sambuc }
923*0a6a1f1dSLionel Sambuc
924*0a6a1f1dSLionel Sambuc template <typename Ty>
925*0a6a1f1dSLionel Sambuc class has_arg_iterator_range {
926*0a6a1f1dSLionel Sambuc typedef char yes[1];
927*0a6a1f1dSLionel Sambuc typedef char no[2];
928*0a6a1f1dSLionel Sambuc
929*0a6a1f1dSLionel Sambuc template <typename Inner>
930*0a6a1f1dSLionel Sambuc static yes& test(Inner *I, decltype(I->args()) * = nullptr);
931*0a6a1f1dSLionel Sambuc
932*0a6a1f1dSLionel Sambuc template <typename>
933*0a6a1f1dSLionel Sambuc static no& test(...);
934*0a6a1f1dSLionel Sambuc
935*0a6a1f1dSLionel Sambuc public:
936*0a6a1f1dSLionel Sambuc static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
937*0a6a1f1dSLionel Sambuc };
938*0a6a1f1dSLionel Sambuc
ClassifyDiagnostic(const CapabilityAttr * A)939*0a6a1f1dSLionel Sambuc static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
940*0a6a1f1dSLionel Sambuc return A->getName();
941*0a6a1f1dSLionel Sambuc }
942*0a6a1f1dSLionel Sambuc
ClassifyDiagnostic(QualType VDT)943*0a6a1f1dSLionel Sambuc static StringRef ClassifyDiagnostic(QualType VDT) {
944*0a6a1f1dSLionel Sambuc // We need to look at the declaration of the type of the value to determine
945*0a6a1f1dSLionel Sambuc // which it is. The type should either be a record or a typedef, or a pointer
946*0a6a1f1dSLionel Sambuc // or reference thereof.
947*0a6a1f1dSLionel Sambuc if (const auto *RT = VDT->getAs<RecordType>()) {
948*0a6a1f1dSLionel Sambuc if (const auto *RD = RT->getDecl())
949*0a6a1f1dSLionel Sambuc if (const auto *CA = RD->getAttr<CapabilityAttr>())
950*0a6a1f1dSLionel Sambuc return ClassifyDiagnostic(CA);
951*0a6a1f1dSLionel Sambuc } else if (const auto *TT = VDT->getAs<TypedefType>()) {
952*0a6a1f1dSLionel Sambuc if (const auto *TD = TT->getDecl())
953*0a6a1f1dSLionel Sambuc if (const auto *CA = TD->getAttr<CapabilityAttr>())
954*0a6a1f1dSLionel Sambuc return ClassifyDiagnostic(CA);
955*0a6a1f1dSLionel Sambuc } else if (VDT->isPointerType() || VDT->isReferenceType())
956*0a6a1f1dSLionel Sambuc return ClassifyDiagnostic(VDT->getPointeeType());
957*0a6a1f1dSLionel Sambuc
958*0a6a1f1dSLionel Sambuc return "mutex";
959*0a6a1f1dSLionel Sambuc }
960*0a6a1f1dSLionel Sambuc
ClassifyDiagnostic(const ValueDecl * VD)961*0a6a1f1dSLionel Sambuc static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
962*0a6a1f1dSLionel Sambuc assert(VD && "No ValueDecl passed");
963*0a6a1f1dSLionel Sambuc
964*0a6a1f1dSLionel Sambuc // The ValueDecl is the declaration of a mutex or role (hopefully).
965*0a6a1f1dSLionel Sambuc return ClassifyDiagnostic(VD->getType());
966*0a6a1f1dSLionel Sambuc }
967*0a6a1f1dSLionel Sambuc
968*0a6a1f1dSLionel Sambuc template <typename AttrTy>
969*0a6a1f1dSLionel Sambuc static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
970*0a6a1f1dSLionel Sambuc StringRef>::type
ClassifyDiagnostic(const AttrTy * A)971*0a6a1f1dSLionel Sambuc ClassifyDiagnostic(const AttrTy *A) {
972*0a6a1f1dSLionel Sambuc if (const ValueDecl *VD = getValueDecl(A->getArg()))
973*0a6a1f1dSLionel Sambuc return ClassifyDiagnostic(VD);
974*0a6a1f1dSLionel Sambuc return "mutex";
975*0a6a1f1dSLionel Sambuc }
976*0a6a1f1dSLionel Sambuc
977*0a6a1f1dSLionel Sambuc template <typename AttrTy>
978*0a6a1f1dSLionel Sambuc static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
979*0a6a1f1dSLionel Sambuc StringRef>::type
ClassifyDiagnostic(const AttrTy * A)980*0a6a1f1dSLionel Sambuc ClassifyDiagnostic(const AttrTy *A) {
981*0a6a1f1dSLionel Sambuc for (const auto *Arg : A->args()) {
982*0a6a1f1dSLionel Sambuc if (const ValueDecl *VD = getValueDecl(Arg))
983*0a6a1f1dSLionel Sambuc return ClassifyDiagnostic(VD);
984*0a6a1f1dSLionel Sambuc }
985*0a6a1f1dSLionel Sambuc return "mutex";
986*0a6a1f1dSLionel Sambuc }
987*0a6a1f1dSLionel Sambuc
988*0a6a1f1dSLionel Sambuc
inCurrentScope(const CapabilityExpr & CapE)989*0a6a1f1dSLionel Sambuc inline bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
990*0a6a1f1dSLionel Sambuc if (!CurrentMethod)
991*0a6a1f1dSLionel Sambuc return false;
992*0a6a1f1dSLionel Sambuc if (auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
993*0a6a1f1dSLionel Sambuc auto *VD = P->clangDecl();
994*0a6a1f1dSLionel Sambuc if (VD)
995*0a6a1f1dSLionel Sambuc return VD->getDeclContext() == CurrentMethod->getDeclContext();
996*0a6a1f1dSLionel Sambuc }
997*0a6a1f1dSLionel Sambuc return false;
998*0a6a1f1dSLionel Sambuc }
999*0a6a1f1dSLionel Sambuc
1000f4a2713aSLionel Sambuc
1001f4a2713aSLionel Sambuc /// \brief Add a new lock to the lockset, warning if the lock is already there.
1002*0a6a1f1dSLionel Sambuc /// \param ReqAttr -- true if this is part of an initial Requires attribute.
addLock(FactSet & FSet,std::unique_ptr<FactEntry> Entry,StringRef DiagKind,bool ReqAttr)1003*0a6a1f1dSLionel Sambuc void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1004*0a6a1f1dSLionel Sambuc std::unique_ptr<FactEntry> Entry,
1005*0a6a1f1dSLionel Sambuc StringRef DiagKind, bool ReqAttr) {
1006*0a6a1f1dSLionel Sambuc if (Entry->shouldIgnore())
1007f4a2713aSLionel Sambuc return;
1008f4a2713aSLionel Sambuc
1009*0a6a1f1dSLionel Sambuc if (!ReqAttr && !Entry->negative()) {
1010*0a6a1f1dSLionel Sambuc // look for the negative capability, and remove it from the fact set.
1011*0a6a1f1dSLionel Sambuc CapabilityExpr NegC = !*Entry;
1012*0a6a1f1dSLionel Sambuc FactEntry *Nen = FSet.findLock(FactMan, NegC);
1013*0a6a1f1dSLionel Sambuc if (Nen) {
1014*0a6a1f1dSLionel Sambuc FSet.removeLock(FactMan, NegC);
1015*0a6a1f1dSLionel Sambuc }
1016*0a6a1f1dSLionel Sambuc else {
1017*0a6a1f1dSLionel Sambuc if (inCurrentScope(*Entry) && !Entry->asserted())
1018*0a6a1f1dSLionel Sambuc Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1019*0a6a1f1dSLionel Sambuc NegC.toString(), Entry->loc());
1020*0a6a1f1dSLionel Sambuc }
1021*0a6a1f1dSLionel Sambuc }
1022*0a6a1f1dSLionel Sambuc
1023*0a6a1f1dSLionel Sambuc // FIXME: deal with acquired before/after annotations.
1024*0a6a1f1dSLionel Sambuc // FIXME: Don't always warn when we have support for reentrant locks.
1025*0a6a1f1dSLionel Sambuc if (FSet.findLock(FactMan, *Entry)) {
1026*0a6a1f1dSLionel Sambuc if (!Entry->asserted())
1027*0a6a1f1dSLionel Sambuc Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
1028f4a2713aSLionel Sambuc } else {
1029*0a6a1f1dSLionel Sambuc FSet.addLock(FactMan, std::move(Entry));
1030f4a2713aSLionel Sambuc }
1031f4a2713aSLionel Sambuc }
1032f4a2713aSLionel Sambuc
1033f4a2713aSLionel Sambuc
1034f4a2713aSLionel Sambuc /// \brief Remove a lock from the lockset, warning if the lock is not there.
1035f4a2713aSLionel Sambuc /// \param UnlockLoc The source location of the unlock (only used in error msg)
removeLock(FactSet & FSet,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,LockKind ReceivedKind,StringRef DiagKind)1036*0a6a1f1dSLionel Sambuc void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
1037f4a2713aSLionel Sambuc SourceLocation UnlockLoc,
1038*0a6a1f1dSLionel Sambuc bool FullyRemove, LockKind ReceivedKind,
1039*0a6a1f1dSLionel Sambuc StringRef DiagKind) {
1040*0a6a1f1dSLionel Sambuc if (Cp.shouldIgnore())
1041f4a2713aSLionel Sambuc return;
1042f4a2713aSLionel Sambuc
1043*0a6a1f1dSLionel Sambuc const FactEntry *LDat = FSet.findLock(FactMan, Cp);
1044f4a2713aSLionel Sambuc if (!LDat) {
1045*0a6a1f1dSLionel Sambuc Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
1046f4a2713aSLionel Sambuc return;
1047f4a2713aSLionel Sambuc }
1048f4a2713aSLionel Sambuc
1049*0a6a1f1dSLionel Sambuc // Generic lock removal doesn't care about lock kind mismatches, but
1050*0a6a1f1dSLionel Sambuc // otherwise diagnose when the lock kinds are mismatched.
1051*0a6a1f1dSLionel Sambuc if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1052*0a6a1f1dSLionel Sambuc Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1053*0a6a1f1dSLionel Sambuc LDat->kind(), ReceivedKind, UnlockLoc);
1054f4a2713aSLionel Sambuc }
1055*0a6a1f1dSLionel Sambuc
1056*0a6a1f1dSLionel Sambuc LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1057*0a6a1f1dSLionel Sambuc DiagKind);
1058f4a2713aSLionel Sambuc }
1059f4a2713aSLionel Sambuc
1060f4a2713aSLionel Sambuc
1061f4a2713aSLionel Sambuc /// \brief Extract the list of mutexIDs from the attribute on an expression,
1062f4a2713aSLionel Sambuc /// and push them onto Mtxs, discarding any duplicates.
1063f4a2713aSLionel Sambuc template <typename AttrType>
getMutexIDs(CapExprSet & Mtxs,AttrType * Attr,Expr * Exp,const NamedDecl * D,VarDecl * SelfDecl)1064*0a6a1f1dSLionel Sambuc void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1065f4a2713aSLionel Sambuc Expr *Exp, const NamedDecl *D,
1066f4a2713aSLionel Sambuc VarDecl *SelfDecl) {
1067f4a2713aSLionel Sambuc if (Attr->args_size() == 0) {
1068f4a2713aSLionel Sambuc // The mutex held is the "this" object.
1069*0a6a1f1dSLionel Sambuc CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1070*0a6a1f1dSLionel Sambuc if (Cp.isInvalid()) {
1071*0a6a1f1dSLionel Sambuc warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1072*0a6a1f1dSLionel Sambuc return;
1073*0a6a1f1dSLionel Sambuc }
1074*0a6a1f1dSLionel Sambuc //else
1075*0a6a1f1dSLionel Sambuc if (!Cp.shouldIgnore())
1076*0a6a1f1dSLionel Sambuc Mtxs.push_back_nodup(Cp);
1077f4a2713aSLionel Sambuc return;
1078f4a2713aSLionel Sambuc }
1079f4a2713aSLionel Sambuc
1080*0a6a1f1dSLionel Sambuc for (const auto *Arg : Attr->args()) {
1081*0a6a1f1dSLionel Sambuc CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1082*0a6a1f1dSLionel Sambuc if (Cp.isInvalid()) {
1083*0a6a1f1dSLionel Sambuc warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1084*0a6a1f1dSLionel Sambuc continue;
1085*0a6a1f1dSLionel Sambuc }
1086*0a6a1f1dSLionel Sambuc //else
1087*0a6a1f1dSLionel Sambuc if (!Cp.shouldIgnore())
1088*0a6a1f1dSLionel Sambuc Mtxs.push_back_nodup(Cp);
1089f4a2713aSLionel Sambuc }
1090f4a2713aSLionel Sambuc }
1091f4a2713aSLionel Sambuc
1092f4a2713aSLionel Sambuc
1093f4a2713aSLionel Sambuc /// \brief Extract the list of mutexIDs from a trylock attribute. If the
1094f4a2713aSLionel Sambuc /// trylock applies to the given edge, then push them onto Mtxs, discarding
1095f4a2713aSLionel Sambuc /// any duplicates.
1096f4a2713aSLionel Sambuc template <class AttrType>
getMutexIDs(CapExprSet & Mtxs,AttrType * Attr,Expr * Exp,const NamedDecl * D,const CFGBlock * PredBlock,const CFGBlock * CurrBlock,Expr * BrE,bool Neg)1097*0a6a1f1dSLionel Sambuc void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1098f4a2713aSLionel Sambuc Expr *Exp, const NamedDecl *D,
1099f4a2713aSLionel Sambuc const CFGBlock *PredBlock,
1100f4a2713aSLionel Sambuc const CFGBlock *CurrBlock,
1101f4a2713aSLionel Sambuc Expr *BrE, bool Neg) {
1102f4a2713aSLionel Sambuc // Find out which branch has the lock
1103*0a6a1f1dSLionel Sambuc bool branch = false;
1104*0a6a1f1dSLionel Sambuc if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1105f4a2713aSLionel Sambuc branch = BLE->getValue();
1106*0a6a1f1dSLionel Sambuc else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1107f4a2713aSLionel Sambuc branch = ILE->getValue().getBoolValue();
1108*0a6a1f1dSLionel Sambuc
1109f4a2713aSLionel Sambuc int branchnum = branch ? 0 : 1;
1110*0a6a1f1dSLionel Sambuc if (Neg)
1111*0a6a1f1dSLionel Sambuc branchnum = !branchnum;
1112f4a2713aSLionel Sambuc
1113f4a2713aSLionel Sambuc // If we've taken the trylock branch, then add the lock
1114f4a2713aSLionel Sambuc int i = 0;
1115f4a2713aSLionel Sambuc for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1116f4a2713aSLionel Sambuc SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1117*0a6a1f1dSLionel Sambuc if (*SI == CurrBlock && i == branchnum)
1118f4a2713aSLionel Sambuc getMutexIDs(Mtxs, Attr, Exp, D);
1119f4a2713aSLionel Sambuc }
1120f4a2713aSLionel Sambuc }
1121f4a2713aSLionel Sambuc
1122f4a2713aSLionel Sambuc
getStaticBooleanValue(Expr * E,bool & TCond)1123f4a2713aSLionel Sambuc bool getStaticBooleanValue(Expr* E, bool& TCond) {
1124f4a2713aSLionel Sambuc if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1125f4a2713aSLionel Sambuc TCond = false;
1126f4a2713aSLionel Sambuc return true;
1127f4a2713aSLionel Sambuc } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1128f4a2713aSLionel Sambuc TCond = BLE->getValue();
1129f4a2713aSLionel Sambuc return true;
1130f4a2713aSLionel Sambuc } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1131f4a2713aSLionel Sambuc TCond = ILE->getValue().getBoolValue();
1132f4a2713aSLionel Sambuc return true;
1133f4a2713aSLionel Sambuc } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1134f4a2713aSLionel Sambuc return getStaticBooleanValue(CE->getSubExpr(), TCond);
1135f4a2713aSLionel Sambuc }
1136f4a2713aSLionel Sambuc return false;
1137f4a2713aSLionel Sambuc }
1138f4a2713aSLionel Sambuc
1139f4a2713aSLionel Sambuc
1140f4a2713aSLionel Sambuc // If Cond can be traced back to a function call, return the call expression.
1141f4a2713aSLionel Sambuc // The negate variable should be called with false, and will be set to true
1142f4a2713aSLionel Sambuc // if the function call is negated, e.g. if (!mu.tryLock(...))
getTrylockCallExpr(const Stmt * Cond,LocalVarContext C,bool & Negate)1143f4a2713aSLionel Sambuc const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1144f4a2713aSLionel Sambuc LocalVarContext C,
1145f4a2713aSLionel Sambuc bool &Negate) {
1146f4a2713aSLionel Sambuc if (!Cond)
1147*0a6a1f1dSLionel Sambuc return nullptr;
1148f4a2713aSLionel Sambuc
1149f4a2713aSLionel Sambuc if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1150f4a2713aSLionel Sambuc return CallExp;
1151f4a2713aSLionel Sambuc }
1152f4a2713aSLionel Sambuc else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1153f4a2713aSLionel Sambuc return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1154f4a2713aSLionel Sambuc }
1155f4a2713aSLionel Sambuc else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1156f4a2713aSLionel Sambuc return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1157f4a2713aSLionel Sambuc }
1158f4a2713aSLionel Sambuc else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1159f4a2713aSLionel Sambuc return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1160f4a2713aSLionel Sambuc }
1161f4a2713aSLionel Sambuc else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1162f4a2713aSLionel Sambuc const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1163f4a2713aSLionel Sambuc return getTrylockCallExpr(E, C, Negate);
1164f4a2713aSLionel Sambuc }
1165f4a2713aSLionel Sambuc else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1166f4a2713aSLionel Sambuc if (UOP->getOpcode() == UO_LNot) {
1167f4a2713aSLionel Sambuc Negate = !Negate;
1168f4a2713aSLionel Sambuc return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1169f4a2713aSLionel Sambuc }
1170*0a6a1f1dSLionel Sambuc return nullptr;
1171f4a2713aSLionel Sambuc }
1172f4a2713aSLionel Sambuc else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1173f4a2713aSLionel Sambuc if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1174f4a2713aSLionel Sambuc if (BOP->getOpcode() == BO_NE)
1175f4a2713aSLionel Sambuc Negate = !Negate;
1176f4a2713aSLionel Sambuc
1177f4a2713aSLionel Sambuc bool TCond = false;
1178f4a2713aSLionel Sambuc if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1179f4a2713aSLionel Sambuc if (!TCond) Negate = !Negate;
1180f4a2713aSLionel Sambuc return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1181f4a2713aSLionel Sambuc }
1182f4a2713aSLionel Sambuc TCond = false;
1183f4a2713aSLionel Sambuc if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1184f4a2713aSLionel Sambuc if (!TCond) Negate = !Negate;
1185f4a2713aSLionel Sambuc return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1186f4a2713aSLionel Sambuc }
1187*0a6a1f1dSLionel Sambuc return nullptr;
1188f4a2713aSLionel Sambuc }
1189f4a2713aSLionel Sambuc if (BOP->getOpcode() == BO_LAnd) {
1190f4a2713aSLionel Sambuc // LHS must have been evaluated in a different block.
1191f4a2713aSLionel Sambuc return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1192f4a2713aSLionel Sambuc }
1193f4a2713aSLionel Sambuc if (BOP->getOpcode() == BO_LOr) {
1194f4a2713aSLionel Sambuc return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1195f4a2713aSLionel Sambuc }
1196*0a6a1f1dSLionel Sambuc return nullptr;
1197f4a2713aSLionel Sambuc }
1198*0a6a1f1dSLionel Sambuc return nullptr;
1199f4a2713aSLionel Sambuc }
1200f4a2713aSLionel Sambuc
1201f4a2713aSLionel Sambuc
1202f4a2713aSLionel Sambuc /// \brief Find the lockset that holds on the edge between PredBlock
1203f4a2713aSLionel Sambuc /// and CurrBlock. The edge set is the exit set of PredBlock (passed
1204f4a2713aSLionel Sambuc /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
getEdgeLockset(FactSet & Result,const FactSet & ExitSet,const CFGBlock * PredBlock,const CFGBlock * CurrBlock)1205f4a2713aSLionel Sambuc void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1206f4a2713aSLionel Sambuc const FactSet &ExitSet,
1207f4a2713aSLionel Sambuc const CFGBlock *PredBlock,
1208f4a2713aSLionel Sambuc const CFGBlock *CurrBlock) {
1209f4a2713aSLionel Sambuc Result = ExitSet;
1210f4a2713aSLionel Sambuc
1211f4a2713aSLionel Sambuc const Stmt *Cond = PredBlock->getTerminatorCondition();
1212f4a2713aSLionel Sambuc if (!Cond)
1213f4a2713aSLionel Sambuc return;
1214f4a2713aSLionel Sambuc
1215f4a2713aSLionel Sambuc bool Negate = false;
1216f4a2713aSLionel Sambuc const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1217f4a2713aSLionel Sambuc const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1218*0a6a1f1dSLionel Sambuc StringRef CapDiagKind = "mutex";
1219f4a2713aSLionel Sambuc
1220f4a2713aSLionel Sambuc CallExpr *Exp =
1221f4a2713aSLionel Sambuc const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
1222f4a2713aSLionel Sambuc if (!Exp)
1223f4a2713aSLionel Sambuc return;
1224f4a2713aSLionel Sambuc
1225f4a2713aSLionel Sambuc NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1226f4a2713aSLionel Sambuc if(!FunDecl || !FunDecl->hasAttrs())
1227f4a2713aSLionel Sambuc return;
1228f4a2713aSLionel Sambuc
1229*0a6a1f1dSLionel Sambuc CapExprSet ExclusiveLocksToAdd;
1230*0a6a1f1dSLionel Sambuc CapExprSet SharedLocksToAdd;
1231f4a2713aSLionel Sambuc
1232f4a2713aSLionel Sambuc // If the condition is a call to a Trylock function, then grab the attributes
1233*0a6a1f1dSLionel Sambuc for (auto *Attr : FunDecl->getAttrs()) {
1234f4a2713aSLionel Sambuc switch (Attr->getKind()) {
1235f4a2713aSLionel Sambuc case attr::ExclusiveTrylockFunction: {
1236f4a2713aSLionel Sambuc ExclusiveTrylockFunctionAttr *A =
1237f4a2713aSLionel Sambuc cast<ExclusiveTrylockFunctionAttr>(Attr);
1238f4a2713aSLionel Sambuc getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1239f4a2713aSLionel Sambuc PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1240*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1241f4a2713aSLionel Sambuc break;
1242f4a2713aSLionel Sambuc }
1243f4a2713aSLionel Sambuc case attr::SharedTrylockFunction: {
1244f4a2713aSLionel Sambuc SharedTrylockFunctionAttr *A =
1245f4a2713aSLionel Sambuc cast<SharedTrylockFunctionAttr>(Attr);
1246f4a2713aSLionel Sambuc getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
1247f4a2713aSLionel Sambuc PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1248*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1249f4a2713aSLionel Sambuc break;
1250f4a2713aSLionel Sambuc }
1251f4a2713aSLionel Sambuc default:
1252f4a2713aSLionel Sambuc break;
1253f4a2713aSLionel Sambuc }
1254f4a2713aSLionel Sambuc }
1255f4a2713aSLionel Sambuc
1256f4a2713aSLionel Sambuc // Add and remove locks.
1257f4a2713aSLionel Sambuc SourceLocation Loc = Exp->getExprLoc();
1258*0a6a1f1dSLionel Sambuc for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1259*0a6a1f1dSLionel Sambuc addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1260*0a6a1f1dSLionel Sambuc LK_Exclusive, Loc),
1261*0a6a1f1dSLionel Sambuc CapDiagKind);
1262*0a6a1f1dSLionel Sambuc for (const auto &SharedLockToAdd : SharedLocksToAdd)
1263*0a6a1f1dSLionel Sambuc addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1264*0a6a1f1dSLionel Sambuc LK_Shared, Loc),
1265*0a6a1f1dSLionel Sambuc CapDiagKind);
1266f4a2713aSLionel Sambuc }
1267f4a2713aSLionel Sambuc
1268f4a2713aSLionel Sambuc /// \brief We use this class to visit different types of expressions in
1269f4a2713aSLionel Sambuc /// CFGBlocks, and build up the lockset.
1270f4a2713aSLionel Sambuc /// An expression may cause us to add or remove locks from the lockset, or else
1271f4a2713aSLionel Sambuc /// output error messages related to missing locks.
1272f4a2713aSLionel Sambuc /// FIXME: In future, we may be able to not inherit from a visitor.
1273f4a2713aSLionel Sambuc class BuildLockset : public StmtVisitor<BuildLockset> {
1274f4a2713aSLionel Sambuc friend class ThreadSafetyAnalyzer;
1275f4a2713aSLionel Sambuc
1276f4a2713aSLionel Sambuc ThreadSafetyAnalyzer *Analyzer;
1277f4a2713aSLionel Sambuc FactSet FSet;
1278f4a2713aSLionel Sambuc LocalVariableMap::Context LVarCtx;
1279f4a2713aSLionel Sambuc unsigned CtxIndex;
1280f4a2713aSLionel Sambuc
1281*0a6a1f1dSLionel Sambuc // helper functions
1282f4a2713aSLionel Sambuc void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1283*0a6a1f1dSLionel Sambuc Expr *MutexExp, ProtectedOperationKind POK,
1284*0a6a1f1dSLionel Sambuc StringRef DiagKind, SourceLocation Loc);
1285*0a6a1f1dSLionel Sambuc void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1286*0a6a1f1dSLionel Sambuc StringRef DiagKind);
1287f4a2713aSLionel Sambuc
1288*0a6a1f1dSLionel Sambuc void checkAccess(const Expr *Exp, AccessKind AK,
1289*0a6a1f1dSLionel Sambuc ProtectedOperationKind POK = POK_VarAccess);
1290*0a6a1f1dSLionel Sambuc void checkPtAccess(const Expr *Exp, AccessKind AK,
1291*0a6a1f1dSLionel Sambuc ProtectedOperationKind POK = POK_VarAccess);
1292f4a2713aSLionel Sambuc
1293*0a6a1f1dSLionel Sambuc void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
1294f4a2713aSLionel Sambuc
1295f4a2713aSLionel Sambuc public:
BuildLockset(ThreadSafetyAnalyzer * Anlzr,CFGBlockInfo & Info)1296f4a2713aSLionel Sambuc BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1297f4a2713aSLionel Sambuc : StmtVisitor<BuildLockset>(),
1298f4a2713aSLionel Sambuc Analyzer(Anlzr),
1299f4a2713aSLionel Sambuc FSet(Info.EntrySet),
1300f4a2713aSLionel Sambuc LVarCtx(Info.EntryContext),
1301f4a2713aSLionel Sambuc CtxIndex(Info.EntryIndex)
1302f4a2713aSLionel Sambuc {}
1303f4a2713aSLionel Sambuc
1304f4a2713aSLionel Sambuc void VisitUnaryOperator(UnaryOperator *UO);
1305f4a2713aSLionel Sambuc void VisitBinaryOperator(BinaryOperator *BO);
1306f4a2713aSLionel Sambuc void VisitCastExpr(CastExpr *CE);
1307f4a2713aSLionel Sambuc void VisitCallExpr(CallExpr *Exp);
1308f4a2713aSLionel Sambuc void VisitCXXConstructExpr(CXXConstructExpr *Exp);
1309f4a2713aSLionel Sambuc void VisitDeclStmt(DeclStmt *S);
1310f4a2713aSLionel Sambuc };
1311f4a2713aSLionel Sambuc
1312f4a2713aSLionel Sambuc
1313f4a2713aSLionel Sambuc /// \brief Warn if the LSet does not contain a lock sufficient to protect access
1314f4a2713aSLionel Sambuc /// of at least the passed in AccessKind.
warnIfMutexNotHeld(const NamedDecl * D,const Expr * Exp,AccessKind AK,Expr * MutexExp,ProtectedOperationKind POK,StringRef DiagKind,SourceLocation Loc)1315f4a2713aSLionel Sambuc void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1316f4a2713aSLionel Sambuc AccessKind AK, Expr *MutexExp,
1317*0a6a1f1dSLionel Sambuc ProtectedOperationKind POK,
1318*0a6a1f1dSLionel Sambuc StringRef DiagKind, SourceLocation Loc) {
1319f4a2713aSLionel Sambuc LockKind LK = getLockKindFromAccessKind(AK);
1320f4a2713aSLionel Sambuc
1321*0a6a1f1dSLionel Sambuc CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1322*0a6a1f1dSLionel Sambuc if (Cp.isInvalid()) {
1323*0a6a1f1dSLionel Sambuc warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1324f4a2713aSLionel Sambuc return;
1325*0a6a1f1dSLionel Sambuc } else if (Cp.shouldIgnore()) {
1326f4a2713aSLionel Sambuc return;
1327f4a2713aSLionel Sambuc }
1328f4a2713aSLionel Sambuc
1329*0a6a1f1dSLionel Sambuc if (Cp.negative()) {
1330*0a6a1f1dSLionel Sambuc // Negative capabilities act like locks excluded
1331*0a6a1f1dSLionel Sambuc FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1332*0a6a1f1dSLionel Sambuc if (LDat) {
1333*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleFunExcludesLock(
1334*0a6a1f1dSLionel Sambuc DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
1335*0a6a1f1dSLionel Sambuc return;
1336*0a6a1f1dSLionel Sambuc }
1337*0a6a1f1dSLionel Sambuc
1338*0a6a1f1dSLionel Sambuc // If this does not refer to a negative capability in the same class,
1339*0a6a1f1dSLionel Sambuc // then stop here.
1340*0a6a1f1dSLionel Sambuc if (!Analyzer->inCurrentScope(Cp))
1341*0a6a1f1dSLionel Sambuc return;
1342*0a6a1f1dSLionel Sambuc
1343*0a6a1f1dSLionel Sambuc // Otherwise the negative requirement must be propagated to the caller.
1344*0a6a1f1dSLionel Sambuc LDat = FSet.findLock(Analyzer->FactMan, Cp);
1345*0a6a1f1dSLionel Sambuc if (!LDat) {
1346*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
1347*0a6a1f1dSLionel Sambuc LK_Shared, Loc);
1348*0a6a1f1dSLionel Sambuc }
1349*0a6a1f1dSLionel Sambuc return;
1350*0a6a1f1dSLionel Sambuc }
1351*0a6a1f1dSLionel Sambuc
1352*0a6a1f1dSLionel Sambuc FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
1353f4a2713aSLionel Sambuc bool NoError = true;
1354f4a2713aSLionel Sambuc if (!LDat) {
1355f4a2713aSLionel Sambuc // No exact match found. Look for a partial match.
1356*0a6a1f1dSLionel Sambuc LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1357*0a6a1f1dSLionel Sambuc if (LDat) {
1358f4a2713aSLionel Sambuc // Warn that there's no precise match.
1359*0a6a1f1dSLionel Sambuc std::string PartMatchStr = LDat->toString();
1360f4a2713aSLionel Sambuc StringRef PartMatchName(PartMatchStr);
1361*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1362*0a6a1f1dSLionel Sambuc LK, Loc, &PartMatchName);
1363f4a2713aSLionel Sambuc } else {
1364f4a2713aSLionel Sambuc // Warn that there's no match at all.
1365*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1366*0a6a1f1dSLionel Sambuc LK, Loc);
1367f4a2713aSLionel Sambuc }
1368f4a2713aSLionel Sambuc NoError = false;
1369f4a2713aSLionel Sambuc }
1370f4a2713aSLionel Sambuc // Make sure the mutex we found is the right kind.
1371*0a6a1f1dSLionel Sambuc if (NoError && LDat && !LDat->isAtLeast(LK)) {
1372*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1373*0a6a1f1dSLionel Sambuc LK, Loc);
1374*0a6a1f1dSLionel Sambuc }
1375f4a2713aSLionel Sambuc }
1376f4a2713aSLionel Sambuc
1377f4a2713aSLionel Sambuc /// \brief Warn if the LSet contains the given lock.
warnIfMutexHeld(const NamedDecl * D,const Expr * Exp,Expr * MutexExp,StringRef DiagKind)1378f4a2713aSLionel Sambuc void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1379*0a6a1f1dSLionel Sambuc Expr *MutexExp, StringRef DiagKind) {
1380*0a6a1f1dSLionel Sambuc CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1381*0a6a1f1dSLionel Sambuc if (Cp.isInvalid()) {
1382*0a6a1f1dSLionel Sambuc warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1383*0a6a1f1dSLionel Sambuc return;
1384*0a6a1f1dSLionel Sambuc } else if (Cp.shouldIgnore()) {
1385f4a2713aSLionel Sambuc return;
1386f4a2713aSLionel Sambuc }
1387f4a2713aSLionel Sambuc
1388*0a6a1f1dSLionel Sambuc FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
1389f4a2713aSLionel Sambuc if (LDat) {
1390*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleFunExcludesLock(
1391*0a6a1f1dSLionel Sambuc DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1392f4a2713aSLionel Sambuc }
1393f4a2713aSLionel Sambuc }
1394f4a2713aSLionel Sambuc
1395f4a2713aSLionel Sambuc /// \brief Checks guarded_by and pt_guarded_by attributes.
1396f4a2713aSLionel Sambuc /// Whenever we identify an access (read or write) to a DeclRefExpr that is
1397f4a2713aSLionel Sambuc /// marked with guarded_by, we must ensure the appropriate mutexes are held.
1398f4a2713aSLionel Sambuc /// Similarly, we check if the access is to an expression that dereferences
1399f4a2713aSLionel Sambuc /// a pointer marked with pt_guarded_by.
checkAccess(const Expr * Exp,AccessKind AK,ProtectedOperationKind POK)1400*0a6a1f1dSLionel Sambuc void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1401*0a6a1f1dSLionel Sambuc ProtectedOperationKind POK) {
1402f4a2713aSLionel Sambuc Exp = Exp->IgnoreParenCasts();
1403f4a2713aSLionel Sambuc
1404*0a6a1f1dSLionel Sambuc SourceLocation Loc = Exp->getExprLoc();
1405*0a6a1f1dSLionel Sambuc
1406*0a6a1f1dSLionel Sambuc // Local variables of reference type cannot be re-assigned;
1407*0a6a1f1dSLionel Sambuc // map them to their initializer.
1408*0a6a1f1dSLionel Sambuc while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1409*0a6a1f1dSLionel Sambuc const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1410*0a6a1f1dSLionel Sambuc if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1411*0a6a1f1dSLionel Sambuc if (const auto *E = VD->getInit()) {
1412*0a6a1f1dSLionel Sambuc Exp = E;
1413*0a6a1f1dSLionel Sambuc continue;
1414*0a6a1f1dSLionel Sambuc }
1415*0a6a1f1dSLionel Sambuc }
1416*0a6a1f1dSLionel Sambuc break;
1417*0a6a1f1dSLionel Sambuc }
1418*0a6a1f1dSLionel Sambuc
1419f4a2713aSLionel Sambuc if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1420f4a2713aSLionel Sambuc // For dereferences
1421f4a2713aSLionel Sambuc if (UO->getOpcode() == clang::UO_Deref)
1422*0a6a1f1dSLionel Sambuc checkPtAccess(UO->getSubExpr(), AK, POK);
1423f4a2713aSLionel Sambuc return;
1424f4a2713aSLionel Sambuc }
1425f4a2713aSLionel Sambuc
1426f4a2713aSLionel Sambuc if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1427*0a6a1f1dSLionel Sambuc checkPtAccess(AE->getLHS(), AK, POK);
1428f4a2713aSLionel Sambuc return;
1429f4a2713aSLionel Sambuc }
1430f4a2713aSLionel Sambuc
1431f4a2713aSLionel Sambuc if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1432f4a2713aSLionel Sambuc if (ME->isArrow())
1433*0a6a1f1dSLionel Sambuc checkPtAccess(ME->getBase(), AK, POK);
1434f4a2713aSLionel Sambuc else
1435*0a6a1f1dSLionel Sambuc checkAccess(ME->getBase(), AK, POK);
1436f4a2713aSLionel Sambuc }
1437f4a2713aSLionel Sambuc
1438f4a2713aSLionel Sambuc const ValueDecl *D = getValueDecl(Exp);
1439f4a2713aSLionel Sambuc if (!D || !D->hasAttrs())
1440f4a2713aSLionel Sambuc return;
1441f4a2713aSLionel Sambuc
1442*0a6a1f1dSLionel Sambuc if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
1443*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
1444f4a2713aSLionel Sambuc }
1445f4a2713aSLionel Sambuc
1446*0a6a1f1dSLionel Sambuc for (const auto *I : D->specific_attrs<GuardedByAttr>())
1447*0a6a1f1dSLionel Sambuc warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
1448*0a6a1f1dSLionel Sambuc ClassifyDiagnostic(I), Loc);
1449*0a6a1f1dSLionel Sambuc }
1450*0a6a1f1dSLionel Sambuc
1451*0a6a1f1dSLionel Sambuc
1452f4a2713aSLionel Sambuc /// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1453*0a6a1f1dSLionel Sambuc /// POK is the same operationKind that was passed to checkAccess.
checkPtAccess(const Expr * Exp,AccessKind AK,ProtectedOperationKind POK)1454*0a6a1f1dSLionel Sambuc void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1455*0a6a1f1dSLionel Sambuc ProtectedOperationKind POK) {
1456f4a2713aSLionel Sambuc while (true) {
1457f4a2713aSLionel Sambuc if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1458f4a2713aSLionel Sambuc Exp = PE->getSubExpr();
1459f4a2713aSLionel Sambuc continue;
1460f4a2713aSLionel Sambuc }
1461f4a2713aSLionel Sambuc if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1462f4a2713aSLionel Sambuc if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1463f4a2713aSLionel Sambuc // If it's an actual array, and not a pointer, then it's elements
1464f4a2713aSLionel Sambuc // are protected by GUARDED_BY, not PT_GUARDED_BY;
1465*0a6a1f1dSLionel Sambuc checkAccess(CE->getSubExpr(), AK, POK);
1466f4a2713aSLionel Sambuc return;
1467f4a2713aSLionel Sambuc }
1468f4a2713aSLionel Sambuc Exp = CE->getSubExpr();
1469f4a2713aSLionel Sambuc continue;
1470f4a2713aSLionel Sambuc }
1471f4a2713aSLionel Sambuc break;
1472f4a2713aSLionel Sambuc }
1473*0a6a1f1dSLionel Sambuc
1474*0a6a1f1dSLionel Sambuc // Pass by reference warnings are under a different flag.
1475*0a6a1f1dSLionel Sambuc ProtectedOperationKind PtPOK = POK_VarDereference;
1476*0a6a1f1dSLionel Sambuc if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1477f4a2713aSLionel Sambuc
1478f4a2713aSLionel Sambuc const ValueDecl *D = getValueDecl(Exp);
1479f4a2713aSLionel Sambuc if (!D || !D->hasAttrs())
1480f4a2713aSLionel Sambuc return;
1481f4a2713aSLionel Sambuc
1482*0a6a1f1dSLionel Sambuc if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
1483*0a6a1f1dSLionel Sambuc Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
1484f4a2713aSLionel Sambuc Exp->getExprLoc());
1485f4a2713aSLionel Sambuc
1486*0a6a1f1dSLionel Sambuc for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1487*0a6a1f1dSLionel Sambuc warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
1488*0a6a1f1dSLionel Sambuc ClassifyDiagnostic(I), Exp->getExprLoc());
1489f4a2713aSLionel Sambuc }
1490f4a2713aSLionel Sambuc
1491f4a2713aSLionel Sambuc /// \brief Process a function call, method call, constructor call,
1492f4a2713aSLionel Sambuc /// or destructor call. This involves looking at the attributes on the
1493f4a2713aSLionel Sambuc /// corresponding function/method/constructor/destructor, issuing warnings,
1494f4a2713aSLionel Sambuc /// and updating the locksets accordingly.
1495f4a2713aSLionel Sambuc ///
1496f4a2713aSLionel Sambuc /// FIXME: For classes annotated with one of the guarded annotations, we need
1497f4a2713aSLionel Sambuc /// to treat const method calls as reads and non-const method calls as writes,
1498f4a2713aSLionel Sambuc /// and check that the appropriate locks are held. Non-const method calls with
1499f4a2713aSLionel Sambuc /// the same signature as const method calls can be also treated as reads.
1500f4a2713aSLionel Sambuc ///
handleCall(Expr * Exp,const NamedDecl * D,VarDecl * VD)1501f4a2713aSLionel Sambuc void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1502f4a2713aSLionel Sambuc SourceLocation Loc = Exp->getExprLoc();
1503f4a2713aSLionel Sambuc const AttrVec &ArgAttrs = D->getAttrs();
1504*0a6a1f1dSLionel Sambuc CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1505*0a6a1f1dSLionel Sambuc CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1506*0a6a1f1dSLionel Sambuc StringRef CapDiagKind = "mutex";
1507f4a2713aSLionel Sambuc
1508f4a2713aSLionel Sambuc for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
1509f4a2713aSLionel Sambuc Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1510f4a2713aSLionel Sambuc switch (At->getKind()) {
1511*0a6a1f1dSLionel Sambuc // When we encounter a lock function, we need to add the lock to our
1512*0a6a1f1dSLionel Sambuc // lockset.
1513*0a6a1f1dSLionel Sambuc case attr::AcquireCapability: {
1514*0a6a1f1dSLionel Sambuc auto *A = cast<AcquireCapabilityAttr>(At);
1515*0a6a1f1dSLionel Sambuc Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1516*0a6a1f1dSLionel Sambuc : ExclusiveLocksToAdd,
1517*0a6a1f1dSLionel Sambuc A, Exp, D, VD);
1518f4a2713aSLionel Sambuc
1519*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1520f4a2713aSLionel Sambuc break;
1521f4a2713aSLionel Sambuc }
1522f4a2713aSLionel Sambuc
1523f4a2713aSLionel Sambuc // An assert will add a lock to the lockset, but will not generate
1524f4a2713aSLionel Sambuc // a warning if it is already there, and will not generate a warning
1525f4a2713aSLionel Sambuc // if it is not removed.
1526f4a2713aSLionel Sambuc case attr::AssertExclusiveLock: {
1527f4a2713aSLionel Sambuc AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1528f4a2713aSLionel Sambuc
1529*0a6a1f1dSLionel Sambuc CapExprSet AssertLocks;
1530f4a2713aSLionel Sambuc Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1531*0a6a1f1dSLionel Sambuc for (const auto &AssertLock : AssertLocks)
1532*0a6a1f1dSLionel Sambuc Analyzer->addLock(FSet,
1533*0a6a1f1dSLionel Sambuc llvm::make_unique<LockableFactEntry>(
1534*0a6a1f1dSLionel Sambuc AssertLock, LK_Exclusive, Loc, false, true),
1535*0a6a1f1dSLionel Sambuc ClassifyDiagnostic(A));
1536f4a2713aSLionel Sambuc break;
1537f4a2713aSLionel Sambuc }
1538f4a2713aSLionel Sambuc case attr::AssertSharedLock: {
1539f4a2713aSLionel Sambuc AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1540f4a2713aSLionel Sambuc
1541*0a6a1f1dSLionel Sambuc CapExprSet AssertLocks;
1542f4a2713aSLionel Sambuc Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1543*0a6a1f1dSLionel Sambuc for (const auto &AssertLock : AssertLocks)
1544*0a6a1f1dSLionel Sambuc Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1545*0a6a1f1dSLionel Sambuc AssertLock, LK_Shared, Loc, false, true),
1546*0a6a1f1dSLionel Sambuc ClassifyDiagnostic(A));
1547f4a2713aSLionel Sambuc break;
1548f4a2713aSLionel Sambuc }
1549f4a2713aSLionel Sambuc
1550f4a2713aSLionel Sambuc // When we encounter an unlock function, we need to remove unlocked
1551f4a2713aSLionel Sambuc // mutexes from the lockset, and flag a warning if they are not there.
1552*0a6a1f1dSLionel Sambuc case attr::ReleaseCapability: {
1553*0a6a1f1dSLionel Sambuc auto *A = cast<ReleaseCapabilityAttr>(At);
1554*0a6a1f1dSLionel Sambuc if (A->isGeneric())
1555*0a6a1f1dSLionel Sambuc Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1556*0a6a1f1dSLionel Sambuc else if (A->isShared())
1557*0a6a1f1dSLionel Sambuc Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1558*0a6a1f1dSLionel Sambuc else
1559*0a6a1f1dSLionel Sambuc Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
1560*0a6a1f1dSLionel Sambuc
1561*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1562f4a2713aSLionel Sambuc break;
1563f4a2713aSLionel Sambuc }
1564f4a2713aSLionel Sambuc
1565*0a6a1f1dSLionel Sambuc case attr::RequiresCapability: {
1566*0a6a1f1dSLionel Sambuc RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
1567*0a6a1f1dSLionel Sambuc for (auto *Arg : A->args())
1568*0a6a1f1dSLionel Sambuc warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
1569*0a6a1f1dSLionel Sambuc POK_FunctionCall, ClassifyDiagnostic(A),
1570*0a6a1f1dSLionel Sambuc Exp->getExprLoc());
1571f4a2713aSLionel Sambuc break;
1572f4a2713aSLionel Sambuc }
1573f4a2713aSLionel Sambuc
1574f4a2713aSLionel Sambuc case attr::LocksExcluded: {
1575f4a2713aSLionel Sambuc LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1576*0a6a1f1dSLionel Sambuc for (auto *Arg : A->args())
1577*0a6a1f1dSLionel Sambuc warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
1578f4a2713aSLionel Sambuc break;
1579f4a2713aSLionel Sambuc }
1580f4a2713aSLionel Sambuc
1581*0a6a1f1dSLionel Sambuc // Ignore attributes unrelated to thread-safety
1582f4a2713aSLionel Sambuc default:
1583f4a2713aSLionel Sambuc break;
1584f4a2713aSLionel Sambuc }
1585f4a2713aSLionel Sambuc }
1586f4a2713aSLionel Sambuc
1587f4a2713aSLionel Sambuc // Figure out if we're calling the constructor of scoped lockable class
1588f4a2713aSLionel Sambuc bool isScopedVar = false;
1589f4a2713aSLionel Sambuc if (VD) {
1590f4a2713aSLionel Sambuc if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1591f4a2713aSLionel Sambuc const CXXRecordDecl* PD = CD->getParent();
1592*0a6a1f1dSLionel Sambuc if (PD && PD->hasAttr<ScopedLockableAttr>())
1593f4a2713aSLionel Sambuc isScopedVar = true;
1594f4a2713aSLionel Sambuc }
1595f4a2713aSLionel Sambuc }
1596f4a2713aSLionel Sambuc
1597f4a2713aSLionel Sambuc // Add locks.
1598*0a6a1f1dSLionel Sambuc for (const auto &M : ExclusiveLocksToAdd)
1599*0a6a1f1dSLionel Sambuc Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1600*0a6a1f1dSLionel Sambuc M, LK_Exclusive, Loc, isScopedVar),
1601*0a6a1f1dSLionel Sambuc CapDiagKind);
1602*0a6a1f1dSLionel Sambuc for (const auto &M : SharedLocksToAdd)
1603*0a6a1f1dSLionel Sambuc Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1604*0a6a1f1dSLionel Sambuc M, LK_Shared, Loc, isScopedVar),
1605*0a6a1f1dSLionel Sambuc CapDiagKind);
1606f4a2713aSLionel Sambuc
1607f4a2713aSLionel Sambuc if (isScopedVar) {
1608*0a6a1f1dSLionel Sambuc // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1609f4a2713aSLionel Sambuc SourceLocation MLoc = VD->getLocation();
1610f4a2713aSLionel Sambuc DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
1611*0a6a1f1dSLionel Sambuc // FIXME: does this store a pointer to DRE?
1612*0a6a1f1dSLionel Sambuc CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
1613f4a2713aSLionel Sambuc
1614*0a6a1f1dSLionel Sambuc CapExprSet UnderlyingMutexes(ExclusiveLocksToAdd);
1615*0a6a1f1dSLionel Sambuc std::copy(SharedLocksToAdd.begin(), SharedLocksToAdd.end(),
1616*0a6a1f1dSLionel Sambuc std::back_inserter(UnderlyingMutexes));
1617*0a6a1f1dSLionel Sambuc Analyzer->addLock(FSet,
1618*0a6a1f1dSLionel Sambuc llvm::make_unique<ScopedLockableFactEntry>(
1619*0a6a1f1dSLionel Sambuc Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1620*0a6a1f1dSLionel Sambuc CapDiagKind);
1621f4a2713aSLionel Sambuc }
1622f4a2713aSLionel Sambuc
1623f4a2713aSLionel Sambuc // Remove locks.
1624f4a2713aSLionel Sambuc // FIXME -- should only fully remove if the attribute refers to 'this'.
1625f4a2713aSLionel Sambuc bool Dtor = isa<CXXDestructorDecl>(D);
1626*0a6a1f1dSLionel Sambuc for (const auto &M : ExclusiveLocksToRemove)
1627*0a6a1f1dSLionel Sambuc Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1628*0a6a1f1dSLionel Sambuc for (const auto &M : SharedLocksToRemove)
1629*0a6a1f1dSLionel Sambuc Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1630*0a6a1f1dSLionel Sambuc for (const auto &M : GenericLocksToRemove)
1631*0a6a1f1dSLionel Sambuc Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1632f4a2713aSLionel Sambuc }
1633f4a2713aSLionel Sambuc
1634f4a2713aSLionel Sambuc
1635f4a2713aSLionel Sambuc /// \brief For unary operations which read and write a variable, we need to
1636f4a2713aSLionel Sambuc /// check whether we hold any required mutexes. Reads are checked in
1637f4a2713aSLionel Sambuc /// VisitCastExpr.
VisitUnaryOperator(UnaryOperator * UO)1638f4a2713aSLionel Sambuc void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1639f4a2713aSLionel Sambuc switch (UO->getOpcode()) {
1640f4a2713aSLionel Sambuc case clang::UO_PostDec:
1641f4a2713aSLionel Sambuc case clang::UO_PostInc:
1642f4a2713aSLionel Sambuc case clang::UO_PreDec:
1643f4a2713aSLionel Sambuc case clang::UO_PreInc: {
1644f4a2713aSLionel Sambuc checkAccess(UO->getSubExpr(), AK_Written);
1645f4a2713aSLionel Sambuc break;
1646f4a2713aSLionel Sambuc }
1647f4a2713aSLionel Sambuc default:
1648f4a2713aSLionel Sambuc break;
1649f4a2713aSLionel Sambuc }
1650f4a2713aSLionel Sambuc }
1651f4a2713aSLionel Sambuc
1652f4a2713aSLionel Sambuc /// For binary operations which assign to a variable (writes), we need to check
1653f4a2713aSLionel Sambuc /// whether we hold any required mutexes.
1654f4a2713aSLionel Sambuc /// FIXME: Deal with non-primitive types.
VisitBinaryOperator(BinaryOperator * BO)1655f4a2713aSLionel Sambuc void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1656f4a2713aSLionel Sambuc if (!BO->isAssignmentOp())
1657f4a2713aSLionel Sambuc return;
1658f4a2713aSLionel Sambuc
1659f4a2713aSLionel Sambuc // adjust the context
1660f4a2713aSLionel Sambuc LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1661f4a2713aSLionel Sambuc
1662f4a2713aSLionel Sambuc checkAccess(BO->getLHS(), AK_Written);
1663f4a2713aSLionel Sambuc }
1664f4a2713aSLionel Sambuc
1665f4a2713aSLionel Sambuc
1666f4a2713aSLionel Sambuc /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1667f4a2713aSLionel Sambuc /// need to ensure we hold any required mutexes.
1668f4a2713aSLionel Sambuc /// FIXME: Deal with non-primitive types.
VisitCastExpr(CastExpr * CE)1669f4a2713aSLionel Sambuc void BuildLockset::VisitCastExpr(CastExpr *CE) {
1670f4a2713aSLionel Sambuc if (CE->getCastKind() != CK_LValueToRValue)
1671f4a2713aSLionel Sambuc return;
1672f4a2713aSLionel Sambuc checkAccess(CE->getSubExpr(), AK_Read);
1673f4a2713aSLionel Sambuc }
1674f4a2713aSLionel Sambuc
1675f4a2713aSLionel Sambuc
VisitCallExpr(CallExpr * Exp)1676f4a2713aSLionel Sambuc void BuildLockset::VisitCallExpr(CallExpr *Exp) {
1677*0a6a1f1dSLionel Sambuc bool ExamineArgs = true;
1678*0a6a1f1dSLionel Sambuc bool OperatorFun = false;
1679*0a6a1f1dSLionel Sambuc
1680f4a2713aSLionel Sambuc if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1681f4a2713aSLionel Sambuc MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
1682f4a2713aSLionel Sambuc // ME can be null when calling a method pointer
1683f4a2713aSLionel Sambuc CXXMethodDecl *MD = CE->getMethodDecl();
1684f4a2713aSLionel Sambuc
1685f4a2713aSLionel Sambuc if (ME && MD) {
1686f4a2713aSLionel Sambuc if (ME->isArrow()) {
1687f4a2713aSLionel Sambuc if (MD->isConst()) {
1688f4a2713aSLionel Sambuc checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1689f4a2713aSLionel Sambuc } else { // FIXME -- should be AK_Written
1690f4a2713aSLionel Sambuc checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1691f4a2713aSLionel Sambuc }
1692f4a2713aSLionel Sambuc } else {
1693f4a2713aSLionel Sambuc if (MD->isConst())
1694f4a2713aSLionel Sambuc checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1695f4a2713aSLionel Sambuc else // FIXME -- should be AK_Written
1696f4a2713aSLionel Sambuc checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1697f4a2713aSLionel Sambuc }
1698f4a2713aSLionel Sambuc }
1699f4a2713aSLionel Sambuc } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
1700*0a6a1f1dSLionel Sambuc OperatorFun = true;
1701*0a6a1f1dSLionel Sambuc
1702*0a6a1f1dSLionel Sambuc auto OEop = OE->getOperator();
1703*0a6a1f1dSLionel Sambuc switch (OEop) {
1704f4a2713aSLionel Sambuc case OO_Equal: {
1705*0a6a1f1dSLionel Sambuc ExamineArgs = false;
1706f4a2713aSLionel Sambuc const Expr *Target = OE->getArg(0);
1707f4a2713aSLionel Sambuc const Expr *Source = OE->getArg(1);
1708f4a2713aSLionel Sambuc checkAccess(Target, AK_Written);
1709f4a2713aSLionel Sambuc checkAccess(Source, AK_Read);
1710f4a2713aSLionel Sambuc break;
1711f4a2713aSLionel Sambuc }
1712f4a2713aSLionel Sambuc case OO_Star:
1713f4a2713aSLionel Sambuc case OO_Arrow:
1714f4a2713aSLionel Sambuc case OO_Subscript: {
1715f4a2713aSLionel Sambuc const Expr *Obj = OE->getArg(0);
1716f4a2713aSLionel Sambuc checkAccess(Obj, AK_Read);
1717*0a6a1f1dSLionel Sambuc if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1718*0a6a1f1dSLionel Sambuc // Grrr. operator* can be multiplication...
1719f4a2713aSLionel Sambuc checkPtAccess(Obj, AK_Read);
1720f4a2713aSLionel Sambuc }
1721f4a2713aSLionel Sambuc break;
1722f4a2713aSLionel Sambuc }
1723f4a2713aSLionel Sambuc default: {
1724*0a6a1f1dSLionel Sambuc // TODO: get rid of this, and rely on pass-by-ref instead.
1725f4a2713aSLionel Sambuc const Expr *Obj = OE->getArg(0);
1726f4a2713aSLionel Sambuc checkAccess(Obj, AK_Read);
1727f4a2713aSLionel Sambuc break;
1728f4a2713aSLionel Sambuc }
1729f4a2713aSLionel Sambuc }
1730f4a2713aSLionel Sambuc }
1731*0a6a1f1dSLionel Sambuc
1732*0a6a1f1dSLionel Sambuc
1733*0a6a1f1dSLionel Sambuc if (ExamineArgs) {
1734*0a6a1f1dSLionel Sambuc if (FunctionDecl *FD = Exp->getDirectCallee()) {
1735*0a6a1f1dSLionel Sambuc unsigned Fn = FD->getNumParams();
1736*0a6a1f1dSLionel Sambuc unsigned Cn = Exp->getNumArgs();
1737*0a6a1f1dSLionel Sambuc unsigned Skip = 0;
1738*0a6a1f1dSLionel Sambuc
1739*0a6a1f1dSLionel Sambuc unsigned i = 0;
1740*0a6a1f1dSLionel Sambuc if (OperatorFun) {
1741*0a6a1f1dSLionel Sambuc if (isa<CXXMethodDecl>(FD)) {
1742*0a6a1f1dSLionel Sambuc // First arg in operator call is implicit self argument,
1743*0a6a1f1dSLionel Sambuc // and doesn't appear in the FunctionDecl.
1744*0a6a1f1dSLionel Sambuc Skip = 1;
1745*0a6a1f1dSLionel Sambuc Cn--;
1746*0a6a1f1dSLionel Sambuc } else {
1747*0a6a1f1dSLionel Sambuc // Ignore the first argument of operators; it's been checked above.
1748*0a6a1f1dSLionel Sambuc i = 1;
1749*0a6a1f1dSLionel Sambuc }
1750*0a6a1f1dSLionel Sambuc }
1751*0a6a1f1dSLionel Sambuc // Ignore default arguments
1752*0a6a1f1dSLionel Sambuc unsigned n = (Fn < Cn) ? Fn : Cn;
1753*0a6a1f1dSLionel Sambuc
1754*0a6a1f1dSLionel Sambuc for (; i < n; ++i) {
1755*0a6a1f1dSLionel Sambuc ParmVarDecl* Pvd = FD->getParamDecl(i);
1756*0a6a1f1dSLionel Sambuc Expr* Arg = Exp->getArg(i+Skip);
1757*0a6a1f1dSLionel Sambuc QualType Qt = Pvd->getType();
1758*0a6a1f1dSLionel Sambuc if (Qt->isReferenceType())
1759*0a6a1f1dSLionel Sambuc checkAccess(Arg, AK_Read, POK_PassByRef);
1760*0a6a1f1dSLionel Sambuc }
1761*0a6a1f1dSLionel Sambuc }
1762*0a6a1f1dSLionel Sambuc }
1763*0a6a1f1dSLionel Sambuc
1764f4a2713aSLionel Sambuc NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1765f4a2713aSLionel Sambuc if(!D || !D->hasAttrs())
1766f4a2713aSLionel Sambuc return;
1767f4a2713aSLionel Sambuc handleCall(Exp, D);
1768f4a2713aSLionel Sambuc }
1769f4a2713aSLionel Sambuc
VisitCXXConstructExpr(CXXConstructExpr * Exp)1770f4a2713aSLionel Sambuc void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
1771f4a2713aSLionel Sambuc const CXXConstructorDecl *D = Exp->getConstructor();
1772f4a2713aSLionel Sambuc if (D && D->isCopyConstructor()) {
1773f4a2713aSLionel Sambuc const Expr* Source = Exp->getArg(0);
1774f4a2713aSLionel Sambuc checkAccess(Source, AK_Read);
1775f4a2713aSLionel Sambuc }
1776f4a2713aSLionel Sambuc // FIXME -- only handles constructors in DeclStmt below.
1777f4a2713aSLionel Sambuc }
1778f4a2713aSLionel Sambuc
VisitDeclStmt(DeclStmt * S)1779f4a2713aSLionel Sambuc void BuildLockset::VisitDeclStmt(DeclStmt *S) {
1780f4a2713aSLionel Sambuc // adjust the context
1781f4a2713aSLionel Sambuc LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
1782f4a2713aSLionel Sambuc
1783*0a6a1f1dSLionel Sambuc for (auto *D : S->getDeclGroup()) {
1784f4a2713aSLionel Sambuc if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1785f4a2713aSLionel Sambuc Expr *E = VD->getInit();
1786f4a2713aSLionel Sambuc // handle constructors that involve temporaries
1787f4a2713aSLionel Sambuc if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1788f4a2713aSLionel Sambuc E = EWC->getSubExpr();
1789f4a2713aSLionel Sambuc
1790f4a2713aSLionel Sambuc if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1791f4a2713aSLionel Sambuc NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1792f4a2713aSLionel Sambuc if (!CtorD || !CtorD->hasAttrs())
1793f4a2713aSLionel Sambuc return;
1794f4a2713aSLionel Sambuc handleCall(CE, CtorD, VD);
1795f4a2713aSLionel Sambuc }
1796f4a2713aSLionel Sambuc }
1797f4a2713aSLionel Sambuc }
1798f4a2713aSLionel Sambuc }
1799f4a2713aSLionel Sambuc
1800f4a2713aSLionel Sambuc
1801f4a2713aSLionel Sambuc
1802f4a2713aSLionel Sambuc /// \brief Compute the intersection of two locksets and issue warnings for any
1803f4a2713aSLionel Sambuc /// locks in the symmetric difference.
1804f4a2713aSLionel Sambuc ///
1805f4a2713aSLionel Sambuc /// This function is used at a merge point in the CFG when comparing the lockset
1806f4a2713aSLionel Sambuc /// of each branch being merged. For example, given the following sequence:
1807f4a2713aSLionel Sambuc /// A; if () then B; else C; D; we need to check that the lockset after B and C
1808f4a2713aSLionel Sambuc /// are the same. In the event of a difference, we use the intersection of these
1809f4a2713aSLionel Sambuc /// two locksets at the start of D.
1810f4a2713aSLionel Sambuc ///
1811f4a2713aSLionel Sambuc /// \param FSet1 The first lockset.
1812f4a2713aSLionel Sambuc /// \param FSet2 The second lockset.
1813f4a2713aSLionel Sambuc /// \param JoinLoc The location of the join point for error reporting
1814f4a2713aSLionel Sambuc /// \param LEK1 The error message to report if a mutex is missing from LSet1
1815f4a2713aSLionel Sambuc /// \param LEK2 The error message to report if a mutex is missing from Lset2
intersectAndWarn(FactSet & FSet1,const FactSet & FSet2,SourceLocation JoinLoc,LockErrorKind LEK1,LockErrorKind LEK2,bool Modify)1816f4a2713aSLionel Sambuc void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
1817f4a2713aSLionel Sambuc const FactSet &FSet2,
1818f4a2713aSLionel Sambuc SourceLocation JoinLoc,
1819f4a2713aSLionel Sambuc LockErrorKind LEK1,
1820f4a2713aSLionel Sambuc LockErrorKind LEK2,
1821f4a2713aSLionel Sambuc bool Modify) {
1822f4a2713aSLionel Sambuc FactSet FSet1Orig = FSet1;
1823f4a2713aSLionel Sambuc
1824f4a2713aSLionel Sambuc // Find locks in FSet2 that conflict or are not in FSet1, and warn.
1825*0a6a1f1dSLionel Sambuc for (const auto &Fact : FSet2) {
1826*0a6a1f1dSLionel Sambuc const FactEntry *LDat1 = nullptr;
1827*0a6a1f1dSLionel Sambuc const FactEntry *LDat2 = &FactMan[Fact];
1828*0a6a1f1dSLionel Sambuc FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
1829*0a6a1f1dSLionel Sambuc if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
1830f4a2713aSLionel Sambuc
1831*0a6a1f1dSLionel Sambuc if (LDat1) {
1832*0a6a1f1dSLionel Sambuc if (LDat1->kind() != LDat2->kind()) {
1833*0a6a1f1dSLionel Sambuc Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
1834*0a6a1f1dSLionel Sambuc LDat2->loc(), LDat1->loc());
1835*0a6a1f1dSLionel Sambuc if (Modify && LDat1->kind() != LK_Exclusive) {
1836f4a2713aSLionel Sambuc // Take the exclusive lock, which is the one in FSet2.
1837*0a6a1f1dSLionel Sambuc *Iter1 = Fact;
1838f4a2713aSLionel Sambuc }
1839f4a2713aSLionel Sambuc }
1840*0a6a1f1dSLionel Sambuc else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
1841f4a2713aSLionel Sambuc // The non-asserted lock in FSet2 is the one we want to track.
1842*0a6a1f1dSLionel Sambuc *Iter1 = Fact;
1843f4a2713aSLionel Sambuc }
1844f4a2713aSLionel Sambuc } else {
1845*0a6a1f1dSLionel Sambuc LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
1846*0a6a1f1dSLionel Sambuc Handler);
1847f4a2713aSLionel Sambuc }
1848f4a2713aSLionel Sambuc }
1849f4a2713aSLionel Sambuc
1850f4a2713aSLionel Sambuc // Find locks in FSet1 that are not in FSet2, and remove them.
1851*0a6a1f1dSLionel Sambuc for (const auto &Fact : FSet1Orig) {
1852*0a6a1f1dSLionel Sambuc const FactEntry *LDat1 = &FactMan[Fact];
1853*0a6a1f1dSLionel Sambuc const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
1854f4a2713aSLionel Sambuc
1855*0a6a1f1dSLionel Sambuc if (!LDat2) {
1856*0a6a1f1dSLionel Sambuc LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
1857*0a6a1f1dSLionel Sambuc Handler);
1858f4a2713aSLionel Sambuc if (Modify)
1859*0a6a1f1dSLionel Sambuc FSet1.removeLock(FactMan, *LDat1);
1860f4a2713aSLionel Sambuc }
1861f4a2713aSLionel Sambuc }
1862f4a2713aSLionel Sambuc }
1863f4a2713aSLionel Sambuc
1864f4a2713aSLionel Sambuc
1865f4a2713aSLionel Sambuc // Return true if block B never continues to its successors.
neverReturns(const CFGBlock * B)1866f4a2713aSLionel Sambuc inline bool neverReturns(const CFGBlock* B) {
1867f4a2713aSLionel Sambuc if (B->hasNoReturnElement())
1868f4a2713aSLionel Sambuc return true;
1869f4a2713aSLionel Sambuc if (B->empty())
1870f4a2713aSLionel Sambuc return false;
1871f4a2713aSLionel Sambuc
1872f4a2713aSLionel Sambuc CFGElement Last = B->back();
1873f4a2713aSLionel Sambuc if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
1874f4a2713aSLionel Sambuc if (isa<CXXThrowExpr>(S->getStmt()))
1875f4a2713aSLionel Sambuc return true;
1876f4a2713aSLionel Sambuc }
1877f4a2713aSLionel Sambuc return false;
1878f4a2713aSLionel Sambuc }
1879f4a2713aSLionel Sambuc
1880f4a2713aSLionel Sambuc
1881f4a2713aSLionel Sambuc /// \brief Check a function's CFG for thread-safety violations.
1882f4a2713aSLionel Sambuc ///
1883f4a2713aSLionel Sambuc /// We traverse the blocks in the CFG, compute the set of mutexes that are held
1884f4a2713aSLionel Sambuc /// at the end of each block, and issue warnings for thread safety violations.
1885f4a2713aSLionel Sambuc /// Each block in the CFG is traversed exactly once.
runAnalysis(AnalysisDeclContext & AC)1886f4a2713aSLionel Sambuc void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
1887*0a6a1f1dSLionel Sambuc // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
1888*0a6a1f1dSLionel Sambuc // For now, we just use the walker to set things up.
1889*0a6a1f1dSLionel Sambuc threadSafety::CFGWalker walker;
1890*0a6a1f1dSLionel Sambuc if (!walker.init(AC))
1891*0a6a1f1dSLionel Sambuc return;
1892f4a2713aSLionel Sambuc
1893f4a2713aSLionel Sambuc // AC.dumpCFG(true);
1894*0a6a1f1dSLionel Sambuc // threadSafety::printSCFG(walker);
1895f4a2713aSLionel Sambuc
1896*0a6a1f1dSLionel Sambuc CFG *CFGraph = walker.getGraph();
1897*0a6a1f1dSLionel Sambuc const NamedDecl *D = walker.getDecl();
1898*0a6a1f1dSLionel Sambuc const FunctionDecl *CurrentFunction = dyn_cast<FunctionDecl>(D);
1899*0a6a1f1dSLionel Sambuc CurrentMethod = dyn_cast<CXXMethodDecl>(D);
1900*0a6a1f1dSLionel Sambuc
1901*0a6a1f1dSLionel Sambuc if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
1902f4a2713aSLionel Sambuc return;
1903*0a6a1f1dSLionel Sambuc
1904f4a2713aSLionel Sambuc // FIXME: Do something a bit more intelligent inside constructor and
1905f4a2713aSLionel Sambuc // destructor code. Constructors and destructors must assume unique access
1906f4a2713aSLionel Sambuc // to 'this', so checks on member variable access is disabled, but we should
1907f4a2713aSLionel Sambuc // still enable checks on other objects.
1908f4a2713aSLionel Sambuc if (isa<CXXConstructorDecl>(D))
1909f4a2713aSLionel Sambuc return; // Don't check inside constructors.
1910f4a2713aSLionel Sambuc if (isa<CXXDestructorDecl>(D))
1911f4a2713aSLionel Sambuc return; // Don't check inside destructors.
1912f4a2713aSLionel Sambuc
1913*0a6a1f1dSLionel Sambuc Handler.enterFunction(CurrentFunction);
1914*0a6a1f1dSLionel Sambuc
1915f4a2713aSLionel Sambuc BlockInfo.resize(CFGraph->getNumBlockIDs(),
1916f4a2713aSLionel Sambuc CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
1917f4a2713aSLionel Sambuc
1918f4a2713aSLionel Sambuc // We need to explore the CFG via a "topological" ordering.
1919f4a2713aSLionel Sambuc // That way, we will be guaranteed to have information about required
1920f4a2713aSLionel Sambuc // predecessor locksets when exploring a new block.
1921*0a6a1f1dSLionel Sambuc const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
1922f4a2713aSLionel Sambuc PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1923f4a2713aSLionel Sambuc
1924f4a2713aSLionel Sambuc // Mark entry block as reachable
1925f4a2713aSLionel Sambuc BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
1926f4a2713aSLionel Sambuc
1927f4a2713aSLionel Sambuc // Compute SSA names for local variables
1928f4a2713aSLionel Sambuc LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
1929f4a2713aSLionel Sambuc
1930f4a2713aSLionel Sambuc // Fill in source locations for all CFGBlocks.
1931f4a2713aSLionel Sambuc findBlockLocations(CFGraph, SortedGraph, BlockInfo);
1932f4a2713aSLionel Sambuc
1933*0a6a1f1dSLionel Sambuc CapExprSet ExclusiveLocksAcquired;
1934*0a6a1f1dSLionel Sambuc CapExprSet SharedLocksAcquired;
1935*0a6a1f1dSLionel Sambuc CapExprSet LocksReleased;
1936f4a2713aSLionel Sambuc
1937f4a2713aSLionel Sambuc // Add locks from exclusive_locks_required and shared_locks_required
1938f4a2713aSLionel Sambuc // to initial lockset. Also turn off checking for lock and unlock functions.
1939f4a2713aSLionel Sambuc // FIXME: is there a more intelligent way to check lock/unlock functions?
1940f4a2713aSLionel Sambuc if (!SortedGraph->empty() && D->hasAttrs()) {
1941f4a2713aSLionel Sambuc const CFGBlock *FirstBlock = *SortedGraph->begin();
1942f4a2713aSLionel Sambuc FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
1943f4a2713aSLionel Sambuc const AttrVec &ArgAttrs = D->getAttrs();
1944f4a2713aSLionel Sambuc
1945*0a6a1f1dSLionel Sambuc CapExprSet ExclusiveLocksToAdd;
1946*0a6a1f1dSLionel Sambuc CapExprSet SharedLocksToAdd;
1947*0a6a1f1dSLionel Sambuc StringRef CapDiagKind = "mutex";
1948f4a2713aSLionel Sambuc
1949f4a2713aSLionel Sambuc SourceLocation Loc = D->getLocation();
1950*0a6a1f1dSLionel Sambuc for (const auto *Attr : ArgAttrs) {
1951f4a2713aSLionel Sambuc Loc = Attr->getLocation();
1952*0a6a1f1dSLionel Sambuc if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
1953*0a6a1f1dSLionel Sambuc getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1954*0a6a1f1dSLionel Sambuc nullptr, D);
1955*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1956*0a6a1f1dSLionel Sambuc } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
1957f4a2713aSLionel Sambuc // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
1958f4a2713aSLionel Sambuc // We must ignore such methods.
1959f4a2713aSLionel Sambuc if (A->args_size() == 0)
1960f4a2713aSLionel Sambuc return;
1961f4a2713aSLionel Sambuc // FIXME -- deal with exclusive vs. shared unlock functions?
1962*0a6a1f1dSLionel Sambuc getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
1963*0a6a1f1dSLionel Sambuc getMutexIDs(LocksReleased, A, nullptr, D);
1964*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1965*0a6a1f1dSLionel Sambuc } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
1966f4a2713aSLionel Sambuc if (A->args_size() == 0)
1967f4a2713aSLionel Sambuc return;
1968*0a6a1f1dSLionel Sambuc getMutexIDs(A->isShared() ? SharedLocksAcquired
1969*0a6a1f1dSLionel Sambuc : ExclusiveLocksAcquired,
1970*0a6a1f1dSLionel Sambuc A, nullptr, D);
1971*0a6a1f1dSLionel Sambuc CapDiagKind = ClassifyDiagnostic(A);
1972f4a2713aSLionel Sambuc } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
1973f4a2713aSLionel Sambuc // Don't try to check trylock functions for now
1974f4a2713aSLionel Sambuc return;
1975f4a2713aSLionel Sambuc } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
1976f4a2713aSLionel Sambuc // Don't try to check trylock functions for now
1977f4a2713aSLionel Sambuc return;
1978f4a2713aSLionel Sambuc }
1979f4a2713aSLionel Sambuc }
1980f4a2713aSLionel Sambuc
1981f4a2713aSLionel Sambuc // FIXME -- Loc can be wrong here.
1982*0a6a1f1dSLionel Sambuc for (const auto &Mu : ExclusiveLocksToAdd)
1983*0a6a1f1dSLionel Sambuc addLock(InitialLockset,
1984*0a6a1f1dSLionel Sambuc llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc),
1985*0a6a1f1dSLionel Sambuc CapDiagKind, true);
1986*0a6a1f1dSLionel Sambuc for (const auto &Mu : SharedLocksToAdd)
1987*0a6a1f1dSLionel Sambuc addLock(InitialLockset,
1988*0a6a1f1dSLionel Sambuc llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc),
1989*0a6a1f1dSLionel Sambuc CapDiagKind, true);
1990f4a2713aSLionel Sambuc }
1991f4a2713aSLionel Sambuc
1992*0a6a1f1dSLionel Sambuc for (const auto *CurrBlock : *SortedGraph) {
1993f4a2713aSLionel Sambuc int CurrBlockID = CurrBlock->getBlockID();
1994f4a2713aSLionel Sambuc CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1995f4a2713aSLionel Sambuc
1996f4a2713aSLionel Sambuc // Use the default initial lockset in case there are no predecessors.
1997f4a2713aSLionel Sambuc VisitedBlocks.insert(CurrBlock);
1998f4a2713aSLionel Sambuc
1999f4a2713aSLionel Sambuc // Iterate through the predecessor blocks and warn if the lockset for all
2000f4a2713aSLionel Sambuc // predecessors is not the same. We take the entry lockset of the current
2001f4a2713aSLionel Sambuc // block to be the intersection of all previous locksets.
2002f4a2713aSLionel Sambuc // FIXME: By keeping the intersection, we may output more errors in future
2003f4a2713aSLionel Sambuc // for a lock which is not in the intersection, but was in the union. We
2004f4a2713aSLionel Sambuc // may want to also keep the union in future. As an example, let's say
2005f4a2713aSLionel Sambuc // the intersection contains Mutex L, and the union contains L and M.
2006f4a2713aSLionel Sambuc // Later we unlock M. At this point, we would output an error because we
2007f4a2713aSLionel Sambuc // never locked M; although the real error is probably that we forgot to
2008f4a2713aSLionel Sambuc // lock M on all code paths. Conversely, let's say that later we lock M.
2009f4a2713aSLionel Sambuc // In this case, we should compare against the intersection instead of the
2010f4a2713aSLionel Sambuc // union because the real error is probably that we forgot to unlock M on
2011f4a2713aSLionel Sambuc // all code paths.
2012f4a2713aSLionel Sambuc bool LocksetInitialized = false;
2013f4a2713aSLionel Sambuc SmallVector<CFGBlock *, 8> SpecialBlocks;
2014f4a2713aSLionel Sambuc for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2015f4a2713aSLionel Sambuc PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2016f4a2713aSLionel Sambuc
2017f4a2713aSLionel Sambuc // if *PI -> CurrBlock is a back edge
2018*0a6a1f1dSLionel Sambuc if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
2019f4a2713aSLionel Sambuc continue;
2020f4a2713aSLionel Sambuc
2021f4a2713aSLionel Sambuc int PrevBlockID = (*PI)->getBlockID();
2022f4a2713aSLionel Sambuc CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2023f4a2713aSLionel Sambuc
2024f4a2713aSLionel Sambuc // Ignore edges from blocks that can't return.
2025f4a2713aSLionel Sambuc if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
2026f4a2713aSLionel Sambuc continue;
2027f4a2713aSLionel Sambuc
2028f4a2713aSLionel Sambuc // Okay, we can reach this block from the entry.
2029f4a2713aSLionel Sambuc CurrBlockInfo->Reachable = true;
2030f4a2713aSLionel Sambuc
2031f4a2713aSLionel Sambuc // If the previous block ended in a 'continue' or 'break' statement, then
2032f4a2713aSLionel Sambuc // a difference in locksets is probably due to a bug in that block, rather
2033f4a2713aSLionel Sambuc // than in some other predecessor. In that case, keep the other
2034f4a2713aSLionel Sambuc // predecessor's lockset.
2035f4a2713aSLionel Sambuc if (const Stmt *Terminator = (*PI)->getTerminator()) {
2036f4a2713aSLionel Sambuc if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2037f4a2713aSLionel Sambuc SpecialBlocks.push_back(*PI);
2038f4a2713aSLionel Sambuc continue;
2039f4a2713aSLionel Sambuc }
2040f4a2713aSLionel Sambuc }
2041f4a2713aSLionel Sambuc
2042f4a2713aSLionel Sambuc FactSet PrevLockset;
2043f4a2713aSLionel Sambuc getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2044f4a2713aSLionel Sambuc
2045f4a2713aSLionel Sambuc if (!LocksetInitialized) {
2046f4a2713aSLionel Sambuc CurrBlockInfo->EntrySet = PrevLockset;
2047f4a2713aSLionel Sambuc LocksetInitialized = true;
2048f4a2713aSLionel Sambuc } else {
2049f4a2713aSLionel Sambuc intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2050f4a2713aSLionel Sambuc CurrBlockInfo->EntryLoc,
2051f4a2713aSLionel Sambuc LEK_LockedSomePredecessors);
2052f4a2713aSLionel Sambuc }
2053f4a2713aSLionel Sambuc }
2054f4a2713aSLionel Sambuc
2055f4a2713aSLionel Sambuc // Skip rest of block if it's not reachable.
2056f4a2713aSLionel Sambuc if (!CurrBlockInfo->Reachable)
2057f4a2713aSLionel Sambuc continue;
2058f4a2713aSLionel Sambuc
2059f4a2713aSLionel Sambuc // Process continue and break blocks. Assume that the lockset for the
2060f4a2713aSLionel Sambuc // resulting block is unaffected by any discrepancies in them.
2061*0a6a1f1dSLionel Sambuc for (const auto *PrevBlock : SpecialBlocks) {
2062f4a2713aSLionel Sambuc int PrevBlockID = PrevBlock->getBlockID();
2063f4a2713aSLionel Sambuc CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2064f4a2713aSLionel Sambuc
2065f4a2713aSLionel Sambuc if (!LocksetInitialized) {
2066f4a2713aSLionel Sambuc CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2067f4a2713aSLionel Sambuc LocksetInitialized = true;
2068f4a2713aSLionel Sambuc } else {
2069f4a2713aSLionel Sambuc // Determine whether this edge is a loop terminator for diagnostic
2070f4a2713aSLionel Sambuc // purposes. FIXME: A 'break' statement might be a loop terminator, but
2071f4a2713aSLionel Sambuc // it might also be part of a switch. Also, a subsequent destructor
2072f4a2713aSLionel Sambuc // might add to the lockset, in which case the real issue might be a
2073f4a2713aSLionel Sambuc // double lock on the other path.
2074f4a2713aSLionel Sambuc const Stmt *Terminator = PrevBlock->getTerminator();
2075f4a2713aSLionel Sambuc bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2076f4a2713aSLionel Sambuc
2077f4a2713aSLionel Sambuc FactSet PrevLockset;
2078f4a2713aSLionel Sambuc getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2079f4a2713aSLionel Sambuc PrevBlock, CurrBlock);
2080f4a2713aSLionel Sambuc
2081f4a2713aSLionel Sambuc // Do not update EntrySet.
2082f4a2713aSLionel Sambuc intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2083f4a2713aSLionel Sambuc PrevBlockInfo->ExitLoc,
2084f4a2713aSLionel Sambuc IsLoop ? LEK_LockedSomeLoopIterations
2085f4a2713aSLionel Sambuc : LEK_LockedSomePredecessors,
2086f4a2713aSLionel Sambuc false);
2087f4a2713aSLionel Sambuc }
2088f4a2713aSLionel Sambuc }
2089f4a2713aSLionel Sambuc
2090f4a2713aSLionel Sambuc BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2091f4a2713aSLionel Sambuc
2092f4a2713aSLionel Sambuc // Visit all the statements in the basic block.
2093f4a2713aSLionel Sambuc for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2094f4a2713aSLionel Sambuc BE = CurrBlock->end(); BI != BE; ++BI) {
2095f4a2713aSLionel Sambuc switch (BI->getKind()) {
2096f4a2713aSLionel Sambuc case CFGElement::Statement: {
2097f4a2713aSLionel Sambuc CFGStmt CS = BI->castAs<CFGStmt>();
2098f4a2713aSLionel Sambuc LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
2099f4a2713aSLionel Sambuc break;
2100f4a2713aSLionel Sambuc }
2101f4a2713aSLionel Sambuc // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2102f4a2713aSLionel Sambuc case CFGElement::AutomaticObjectDtor: {
2103f4a2713aSLionel Sambuc CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2104f4a2713aSLionel Sambuc CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2105f4a2713aSLionel Sambuc AD.getDestructorDecl(AC.getASTContext()));
2106f4a2713aSLionel Sambuc if (!DD->hasAttrs())
2107f4a2713aSLionel Sambuc break;
2108f4a2713aSLionel Sambuc
2109f4a2713aSLionel Sambuc // Create a dummy expression,
2110f4a2713aSLionel Sambuc VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
2111*0a6a1f1dSLionel Sambuc DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
2112*0a6a1f1dSLionel Sambuc VK_LValue, AD.getTriggerStmt()->getLocEnd());
2113f4a2713aSLionel Sambuc LocksetBuilder.handleCall(&DRE, DD);
2114f4a2713aSLionel Sambuc break;
2115f4a2713aSLionel Sambuc }
2116f4a2713aSLionel Sambuc default:
2117f4a2713aSLionel Sambuc break;
2118f4a2713aSLionel Sambuc }
2119f4a2713aSLionel Sambuc }
2120f4a2713aSLionel Sambuc CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2121f4a2713aSLionel Sambuc
2122f4a2713aSLionel Sambuc // For every back edge from CurrBlock (the end of the loop) to another block
2123f4a2713aSLionel Sambuc // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2124f4a2713aSLionel Sambuc // the one held at the beginning of FirstLoopBlock. We can look up the
2125f4a2713aSLionel Sambuc // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2126f4a2713aSLionel Sambuc for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2127f4a2713aSLionel Sambuc SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2128f4a2713aSLionel Sambuc
2129f4a2713aSLionel Sambuc // if CurrBlock -> *SI is *not* a back edge
2130*0a6a1f1dSLionel Sambuc if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
2131f4a2713aSLionel Sambuc continue;
2132f4a2713aSLionel Sambuc
2133f4a2713aSLionel Sambuc CFGBlock *FirstLoopBlock = *SI;
2134f4a2713aSLionel Sambuc CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2135f4a2713aSLionel Sambuc CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2136f4a2713aSLionel Sambuc intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2137f4a2713aSLionel Sambuc PreLoop->EntryLoc,
2138f4a2713aSLionel Sambuc LEK_LockedSomeLoopIterations,
2139f4a2713aSLionel Sambuc false);
2140f4a2713aSLionel Sambuc }
2141f4a2713aSLionel Sambuc }
2142f4a2713aSLionel Sambuc
2143f4a2713aSLionel Sambuc CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2144f4a2713aSLionel Sambuc CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
2145f4a2713aSLionel Sambuc
2146f4a2713aSLionel Sambuc // Skip the final check if the exit block is unreachable.
2147f4a2713aSLionel Sambuc if (!Final->Reachable)
2148f4a2713aSLionel Sambuc return;
2149f4a2713aSLionel Sambuc
2150f4a2713aSLionel Sambuc // By default, we expect all locks held on entry to be held on exit.
2151f4a2713aSLionel Sambuc FactSet ExpectedExitSet = Initial->EntrySet;
2152f4a2713aSLionel Sambuc
2153f4a2713aSLionel Sambuc // Adjust the expected exit set by adding or removing locks, as declared
2154f4a2713aSLionel Sambuc // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2155f4a2713aSLionel Sambuc // issue the appropriate warning.
2156f4a2713aSLionel Sambuc // FIXME: the location here is not quite right.
2157*0a6a1f1dSLionel Sambuc for (const auto &Lock : ExclusiveLocksAcquired)
2158*0a6a1f1dSLionel Sambuc ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2159*0a6a1f1dSLionel Sambuc Lock, LK_Exclusive, D->getLocation()));
2160*0a6a1f1dSLionel Sambuc for (const auto &Lock : SharedLocksAcquired)
2161*0a6a1f1dSLionel Sambuc ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2162*0a6a1f1dSLionel Sambuc Lock, LK_Shared, D->getLocation()));
2163*0a6a1f1dSLionel Sambuc for (const auto &Lock : LocksReleased)
2164*0a6a1f1dSLionel Sambuc ExpectedExitSet.removeLock(FactMan, Lock);
2165f4a2713aSLionel Sambuc
2166f4a2713aSLionel Sambuc // FIXME: Should we call this function for all blocks which exit the function?
2167f4a2713aSLionel Sambuc intersectAndWarn(ExpectedExitSet, Final->ExitSet,
2168f4a2713aSLionel Sambuc Final->ExitLoc,
2169f4a2713aSLionel Sambuc LEK_LockedAtEndOfFunction,
2170f4a2713aSLionel Sambuc LEK_NotLockedAtEndOfFunction,
2171f4a2713aSLionel Sambuc false);
2172*0a6a1f1dSLionel Sambuc
2173*0a6a1f1dSLionel Sambuc Handler.leaveFunction(CurrentFunction);
2174f4a2713aSLionel Sambuc }
2175f4a2713aSLionel Sambuc
2176f4a2713aSLionel Sambuc
2177f4a2713aSLionel Sambuc /// \brief Check a function's CFG for thread-safety violations.
2178f4a2713aSLionel Sambuc ///
2179f4a2713aSLionel Sambuc /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2180f4a2713aSLionel Sambuc /// at the end of each block, and issue warnings for thread safety violations.
2181f4a2713aSLionel Sambuc /// Each block in the CFG is traversed exactly once.
runThreadSafetyAnalysis(AnalysisDeclContext & AC,ThreadSafetyHandler & Handler)2182f4a2713aSLionel Sambuc void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2183f4a2713aSLionel Sambuc ThreadSafetyHandler &Handler) {
2184f4a2713aSLionel Sambuc ThreadSafetyAnalyzer Analyzer(Handler);
2185f4a2713aSLionel Sambuc Analyzer.runAnalysis(AC);
2186f4a2713aSLionel Sambuc }
2187f4a2713aSLionel Sambuc
2188f4a2713aSLionel Sambuc /// \brief Helper function that returns a LockKind required for the given level
2189f4a2713aSLionel Sambuc /// of access.
getLockKindFromAccessKind(AccessKind AK)2190f4a2713aSLionel Sambuc LockKind getLockKindFromAccessKind(AccessKind AK) {
2191f4a2713aSLionel Sambuc switch (AK) {
2192f4a2713aSLionel Sambuc case AK_Read :
2193f4a2713aSLionel Sambuc return LK_Shared;
2194f4a2713aSLionel Sambuc case AK_Written :
2195f4a2713aSLionel Sambuc return LK_Exclusive;
2196f4a2713aSLionel Sambuc }
2197f4a2713aSLionel Sambuc llvm_unreachable("Unknown AccessKind");
2198f4a2713aSLionel Sambuc }
2199f4a2713aSLionel Sambuc
2200*0a6a1f1dSLionel Sambuc }} // end namespace clang::threadSafety
2201