1 //===- ThreadSafety.cpp ---------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // A intra-procedural analysis for thread safety (e.g. deadlocks and race
10 // conditions), based off of an annotation system.
12 // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
13 // for more information.
15 //===----------------------------------------------------------------------===//
17 #include "clang/Analysis/Analyses/ThreadSafety.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/OperationKinds.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
29 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
30 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
31 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
32 #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
33 #include "clang/Analysis/AnalysisDeclContext.h"
34 #include "clang/Analysis/CFG.h"
35 #include "clang/Basic/Builtins.h"
36 #include "clang/Basic/LLVM.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/SourceLocation.h"
39 #include "clang/Basic/Specifiers.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/ImmutableMap.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/StringRef.h"
46 #include "llvm/Support/Allocator.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/raw_ostream.h"
57 #include <type_traits>
61 using namespace clang
;
62 using namespace threadSafety
;
64 // Key method definition
65 ThreadSafetyHandler::~ThreadSafetyHandler() = default;
67 /// Issue a warning about an invalid lock expression
68 static void warnInvalidLock(ThreadSafetyHandler
&Handler
,
69 const Expr
*MutexExp
, const NamedDecl
*D
,
70 const Expr
*DeclExp
, StringRef Kind
) {
73 Loc
= DeclExp
->getExprLoc();
75 // FIXME: add a note about the attribute location in MutexExp or D
77 Handler
.handleInvalidLockExp(Loc
);
82 /// A set of CapabilityExpr objects, which are compiled from thread safety
83 /// attributes on a function.
84 class CapExprSet
: public SmallVector
<CapabilityExpr
, 4> {
86 /// Push M onto list, but discard duplicates.
87 void push_back_nodup(const CapabilityExpr
&CapE
) {
88 if (llvm::none_of(*this, [=](const CapabilityExpr
&CapE2
) {
89 return CapE
.equals(CapE2
);
98 /// This is a helper class that stores a fact that is known at a
99 /// particular point in program execution. Currently, a fact is a capability,
100 /// along with additional information, such as where it was acquired, whether
101 /// it is exclusive or shared, etc.
103 /// FIXME: this analysis does not currently support re-entrant locking.
104 class FactEntry
: public CapabilityExpr
{
106 /// Where a fact comes from.
108 Acquired
, ///< The fact has been directly acquired.
109 Asserted
, ///< The fact has been asserted to be held.
110 Declared
, ///< The fact is assumed to be held by callers.
111 Managed
, ///< The fact has been acquired through a scoped capability.
115 /// Exclusive or shared.
118 // How it was acquired.
119 SourceKind Source
: 8;
121 /// Where it was acquired.
122 SourceLocation AcquireLoc
;
125 FactEntry(const CapabilityExpr
&CE
, LockKind LK
, SourceLocation Loc
,
127 : CapabilityExpr(CE
), LKind(LK
), Source(Src
), AcquireLoc(Loc
) {}
128 virtual ~FactEntry() = default;
130 LockKind
kind() const { return LKind
; }
131 SourceLocation
loc() const { return AcquireLoc
; }
133 bool asserted() const { return Source
== Asserted
; }
134 bool declared() const { return Source
== Declared
; }
135 bool managed() const { return Source
== Managed
; }
138 handleRemovalFromIntersection(const FactSet
&FSet
, FactManager
&FactMan
,
139 SourceLocation JoinLoc
, LockErrorKind LEK
,
140 ThreadSafetyHandler
&Handler
) const = 0;
141 virtual void handleLock(FactSet
&FSet
, FactManager
&FactMan
,
142 const FactEntry
&entry
,
143 ThreadSafetyHandler
&Handler
) const = 0;
144 virtual void handleUnlock(FactSet
&FSet
, FactManager
&FactMan
,
145 const CapabilityExpr
&Cp
, SourceLocation UnlockLoc
,
147 ThreadSafetyHandler
&Handler
) const = 0;
149 // Return true if LKind >= LK, where exclusive > shared
150 bool isAtLeast(LockKind LK
) const {
151 return (LKind
== LK_Exclusive
) || (LK
== LK_Shared
);
155 using FactID
= unsigned short;
157 /// FactManager manages the memory for all facts that are created during
158 /// the analysis of a single routine.
161 std::vector
<std::unique_ptr
<const FactEntry
>> Facts
;
164 FactID
newFact(std::unique_ptr
<FactEntry
> Entry
) {
165 Facts
.push_back(std::move(Entry
));
166 return static_cast<unsigned short>(Facts
.size() - 1);
169 const FactEntry
&operator[](FactID F
) const { return *Facts
[F
]; }
172 /// A FactSet is the set of facts that are known to be true at a
173 /// particular program point. FactSets must be small, because they are
174 /// frequently copied, and are thus implemented as a set of indices into a
175 /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
176 /// locks, so we can get away with doing a linear search for lookup. Note
177 /// that a hashtable or map is inappropriate in this case, because lookups
178 /// may involve partial pattern matches, rather than exact matches.
181 using FactVec
= SmallVector
<FactID
, 4>;
186 using iterator
= FactVec::iterator
;
187 using const_iterator
= FactVec::const_iterator
;
189 iterator
begin() { return FactIDs
.begin(); }
190 const_iterator
begin() const { return FactIDs
.begin(); }
192 iterator
end() { return FactIDs
.end(); }
193 const_iterator
end() const { return FactIDs
.end(); }
195 bool isEmpty() const { return FactIDs
.size() == 0; }
197 // Return true if the set contains only negative facts
198 bool isEmpty(FactManager
&FactMan
) const {
199 for (const auto FID
: *this) {
200 if (!FactMan
[FID
].negative())
206 void addLockByID(FactID ID
) { FactIDs
.push_back(ID
); }
208 FactID
addLock(FactManager
&FM
, std::unique_ptr
<FactEntry
> Entry
) {
209 FactID F
= FM
.newFact(std::move(Entry
));
210 FactIDs
.push_back(F
);
214 bool removeLock(FactManager
& FM
, const CapabilityExpr
&CapE
) {
215 unsigned n
= FactIDs
.size();
219 for (unsigned i
= 0; i
< n
-1; ++i
) {
220 if (FM
[FactIDs
[i
]].matches(CapE
)) {
221 FactIDs
[i
] = FactIDs
[n
-1];
226 if (FM
[FactIDs
[n
-1]].matches(CapE
)) {
233 iterator
findLockIter(FactManager
&FM
, const CapabilityExpr
&CapE
) {
234 return std::find_if(begin(), end(), [&](FactID ID
) {
235 return FM
[ID
].matches(CapE
);
239 const FactEntry
*findLock(FactManager
&FM
, const CapabilityExpr
&CapE
) const {
240 auto I
= std::find_if(begin(), end(), [&](FactID ID
) {
241 return FM
[ID
].matches(CapE
);
243 return I
!= end() ? &FM
[*I
] : nullptr;
246 const FactEntry
*findLockUniv(FactManager
&FM
,
247 const CapabilityExpr
&CapE
) const {
248 auto I
= std::find_if(begin(), end(), [&](FactID ID
) -> bool {
249 return FM
[ID
].matchesUniv(CapE
);
251 return I
!= end() ? &FM
[*I
] : nullptr;
254 const FactEntry
*findPartialMatch(FactManager
&FM
,
255 const CapabilityExpr
&CapE
) const {
256 auto I
= std::find_if(begin(), end(), [&](FactID ID
) -> bool {
257 return FM
[ID
].partiallyMatches(CapE
);
259 return I
!= end() ? &FM
[*I
] : nullptr;
262 bool containsMutexDecl(FactManager
&FM
, const ValueDecl
* Vd
) const {
263 auto I
= std::find_if(begin(), end(), [&](FactID ID
) -> bool {
264 return FM
[ID
].valueDecl() == Vd
;
270 class ThreadSafetyAnalyzer
;
275 namespace threadSafety
{
279 using BeforeVect
= SmallVector
<const ValueDecl
*, 4>;
285 BeforeInfo() = default;
286 BeforeInfo(BeforeInfo
&&) = default;
290 llvm::DenseMap
<const ValueDecl
*, std::unique_ptr
<BeforeInfo
>>;
291 using CycleMap
= llvm::DenseMap
<const ValueDecl
*, bool>;
294 BeforeSet() = default;
296 BeforeInfo
* insertAttrExprs(const ValueDecl
* Vd
,
297 ThreadSafetyAnalyzer
& Analyzer
);
299 BeforeInfo
*getBeforeInfoForDecl(const ValueDecl
*Vd
,
300 ThreadSafetyAnalyzer
&Analyzer
);
302 void checkBeforeAfter(const ValueDecl
* Vd
,
304 ThreadSafetyAnalyzer
& Analyzer
,
305 SourceLocation Loc
, StringRef CapKind
);
312 } // namespace threadSafety
317 class LocalVariableMap
;
319 using LocalVarContext
= llvm::ImmutableMap
<const NamedDecl
*, unsigned>;
321 /// A side (entry or exit) of a CFG node.
322 enum CFGBlockSide
{ CBS_Entry
, CBS_Exit
};
324 /// CFGBlockInfo is a struct which contains all the information that is
325 /// maintained for each block in the CFG. See LocalVariableMap for more
326 /// information about the contexts.
327 struct CFGBlockInfo
{
328 // Lockset held at entry to block
331 // Lockset held at exit from block
334 // Context held at entry to block
335 LocalVarContext EntryContext
;
337 // Context held at exit from block
338 LocalVarContext ExitContext
;
340 // Location of first statement in block
341 SourceLocation EntryLoc
;
343 // Location of last statement in block.
344 SourceLocation ExitLoc
;
346 // Used to replay contexts later
349 // Is this block reachable?
350 bool Reachable
= false;
352 const FactSet
&getSet(CFGBlockSide Side
) const {
353 return Side
== CBS_Entry
? EntrySet
: ExitSet
;
356 SourceLocation
getLocation(CFGBlockSide Side
) const {
357 return Side
== CBS_Entry
? EntryLoc
: ExitLoc
;
361 CFGBlockInfo(LocalVarContext EmptyCtx
)
362 : EntryContext(EmptyCtx
), ExitContext(EmptyCtx
) {}
365 static CFGBlockInfo
getEmptyBlockInfo(LocalVariableMap
&M
);
368 // A LocalVariableMap maintains a map from local variables to their currently
369 // valid definitions. It provides SSA-like functionality when traversing the
370 // CFG. Like SSA, each definition or assignment to a variable is assigned a
371 // unique name (an integer), which acts as the SSA name for that definition.
372 // The total set of names is shared among all CFG basic blocks.
373 // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
374 // with their SSA-names. Instead, we compute a Context for each point in the
375 // code, which maps local variables to the appropriate SSA-name. This map
376 // changes with each assignment.
378 // The map is computed in a single pass over the CFG. Subsequent analyses can
379 // then query the map to find the appropriate Context for a statement, and use
380 // that Context to look up the definitions of variables.
381 class LocalVariableMap
{
383 using Context
= LocalVarContext
;
385 /// A VarDefinition consists of an expression, representing the value of the
386 /// variable, along with the context in which that expression should be
387 /// interpreted. A reference VarDefinition does not itself contain this
388 /// information, but instead contains a pointer to a previous VarDefinition.
389 struct VarDefinition
{
391 friend class LocalVariableMap
;
393 // The original declaration for this variable.
394 const NamedDecl
*Dec
;
396 // The expression for this variable, OR
397 const Expr
*Exp
= nullptr;
399 // Reference to another VarDefinition
402 // The map with which Exp should be interpreted.
405 bool isReference() const { return !Exp
; }
408 // Create ordinary variable definition
409 VarDefinition(const NamedDecl
*D
, const Expr
*E
, Context C
)
410 : Dec(D
), Exp(E
), Ctx(C
) {}
412 // Create reference to previous definition
413 VarDefinition(const NamedDecl
*D
, unsigned R
, Context C
)
414 : Dec(D
), Ref(R
), Ctx(C
) {}
418 Context::Factory ContextFactory
;
419 std::vector
<VarDefinition
> VarDefinitions
;
420 std::vector
<std::pair
<const Stmt
*, Context
>> SavedContexts
;
424 // index 0 is a placeholder for undefined variables (aka phi-nodes).
425 VarDefinitions
.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
428 /// Look up a definition, within the given context.
429 const VarDefinition
* lookup(const NamedDecl
*D
, Context Ctx
) {
430 const unsigned *i
= Ctx
.lookup(D
);
433 assert(*i
< VarDefinitions
.size());
434 return &VarDefinitions
[*i
];
437 /// Look up the definition for D within the given context. Returns
438 /// NULL if the expression is not statically known. If successful, also
439 /// modifies Ctx to hold the context of the return Expr.
440 const Expr
* lookupExpr(const NamedDecl
*D
, Context
&Ctx
) {
441 const unsigned *P
= Ctx
.lookup(D
);
447 if (VarDefinitions
[i
].Exp
) {
448 Ctx
= VarDefinitions
[i
].Ctx
;
449 return VarDefinitions
[i
].Exp
;
451 i
= VarDefinitions
[i
].Ref
;
456 Context
getEmptyContext() { return ContextFactory
.getEmptyMap(); }
458 /// Return the next context after processing S. This function is used by
459 /// clients of the class to get the appropriate context when traversing the
460 /// CFG. It must be called for every assignment or DeclStmt.
461 Context
getNextContext(unsigned &CtxIndex
, const Stmt
*S
, Context C
) {
462 if (SavedContexts
[CtxIndex
+1].first
== S
) {
464 Context Result
= SavedContexts
[CtxIndex
].second
;
470 void dumpVarDefinitionName(unsigned i
) {
472 llvm::errs() << "Undefined";
475 const NamedDecl
*Dec
= VarDefinitions
[i
].Dec
;
477 llvm::errs() << "<<NULL>>";
480 Dec
->printName(llvm::errs());
481 llvm::errs() << "." << i
<< " " << ((const void*) Dec
);
484 /// Dumps an ASCII representation of the variable map to llvm::errs()
486 for (unsigned i
= 1, e
= VarDefinitions
.size(); i
< e
; ++i
) {
487 const Expr
*Exp
= VarDefinitions
[i
].Exp
;
488 unsigned Ref
= VarDefinitions
[i
].Ref
;
490 dumpVarDefinitionName(i
);
491 llvm::errs() << " = ";
492 if (Exp
) Exp
->dump();
494 dumpVarDefinitionName(Ref
);
495 llvm::errs() << "\n";
500 /// Dumps an ASCII representation of a Context to llvm::errs()
501 void dumpContext(Context C
) {
502 for (Context::iterator I
= C
.begin(), E
= C
.end(); I
!= E
; ++I
) {
503 const NamedDecl
*D
= I
.getKey();
504 D
->printName(llvm::errs());
505 llvm::errs() << " -> ";
506 dumpVarDefinitionName(I
.getData());
507 llvm::errs() << "\n";
511 /// Builds the variable map.
512 void traverseCFG(CFG
*CFGraph
, const PostOrderCFGView
*SortedGraph
,
513 std::vector
<CFGBlockInfo
> &BlockInfo
);
516 friend class VarMapBuilder
;
518 // Get the current context index
519 unsigned getContextIndex() { return SavedContexts
.size()-1; }
521 // Save the current context for later replay
522 void saveContext(const Stmt
*S
, Context C
) {
523 SavedContexts
.push_back(std::make_pair(S
, C
));
526 // Adds a new definition to the given context, and returns a new context.
527 // This method should be called when declaring a new variable.
528 Context
addDefinition(const NamedDecl
*D
, const Expr
*Exp
, Context Ctx
) {
529 assert(!Ctx
.contains(D
));
530 unsigned newID
= VarDefinitions
.size();
531 Context NewCtx
= ContextFactory
.add(Ctx
, D
, newID
);
532 VarDefinitions
.push_back(VarDefinition(D
, Exp
, Ctx
));
536 // Add a new reference to an existing definition.
537 Context
addReference(const NamedDecl
*D
, unsigned i
, Context Ctx
) {
538 unsigned newID
= VarDefinitions
.size();
539 Context NewCtx
= ContextFactory
.add(Ctx
, D
, newID
);
540 VarDefinitions
.push_back(VarDefinition(D
, i
, Ctx
));
544 // Updates a definition only if that definition is already in the map.
545 // This method should be called when assigning to an existing variable.
546 Context
updateDefinition(const NamedDecl
*D
, Expr
*Exp
, Context Ctx
) {
547 if (Ctx
.contains(D
)) {
548 unsigned newID
= VarDefinitions
.size();
549 Context NewCtx
= ContextFactory
.remove(Ctx
, D
);
550 NewCtx
= ContextFactory
.add(NewCtx
, D
, newID
);
551 VarDefinitions
.push_back(VarDefinition(D
, Exp
, Ctx
));
557 // Removes a definition from the context, but keeps the variable name
558 // as a valid variable. The index 0 is a placeholder for cleared definitions.
559 Context
clearDefinition(const NamedDecl
*D
, Context Ctx
) {
560 Context NewCtx
= Ctx
;
561 if (NewCtx
.contains(D
)) {
562 NewCtx
= ContextFactory
.remove(NewCtx
, D
);
563 NewCtx
= ContextFactory
.add(NewCtx
, D
, 0);
568 // Remove a definition entirely frmo the context.
569 Context
removeDefinition(const NamedDecl
*D
, Context Ctx
) {
570 Context NewCtx
= Ctx
;
571 if (NewCtx
.contains(D
)) {
572 NewCtx
= ContextFactory
.remove(NewCtx
, D
);
577 Context
intersectContexts(Context C1
, Context C2
);
578 Context
createReferenceContext(Context C
);
579 void intersectBackEdge(Context C1
, Context C2
);
584 // This has to be defined after LocalVariableMap.
585 CFGBlockInfo
CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap
&M
) {
586 return CFGBlockInfo(M
.getEmptyContext());
591 /// Visitor which builds a LocalVariableMap
592 class VarMapBuilder
: public ConstStmtVisitor
<VarMapBuilder
> {
594 LocalVariableMap
* VMap
;
595 LocalVariableMap::Context Ctx
;
597 VarMapBuilder(LocalVariableMap
*VM
, LocalVariableMap::Context C
)
598 : VMap(VM
), Ctx(C
) {}
600 void VisitDeclStmt(const DeclStmt
*S
);
601 void VisitBinaryOperator(const BinaryOperator
*BO
);
606 // Add new local variables to the variable map
607 void VarMapBuilder::VisitDeclStmt(const DeclStmt
*S
) {
608 bool modifiedCtx
= false;
609 const DeclGroupRef DGrp
= S
->getDeclGroup();
610 for (const auto *D
: DGrp
) {
611 if (const auto *VD
= dyn_cast_or_null
<VarDecl
>(D
)) {
612 const Expr
*E
= VD
->getInit();
614 // Add local variables with trivial type to the variable map
615 QualType T
= VD
->getType();
616 if (T
.isTrivialType(VD
->getASTContext())) {
617 Ctx
= VMap
->addDefinition(VD
, E
, Ctx
);
623 VMap
->saveContext(S
, Ctx
);
626 // Update local variable definitions in variable map
627 void VarMapBuilder::VisitBinaryOperator(const BinaryOperator
*BO
) {
628 if (!BO
->isAssignmentOp())
631 Expr
*LHSExp
= BO
->getLHS()->IgnoreParenCasts();
633 // Update the variable map and current context.
634 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSExp
)) {
635 const ValueDecl
*VDec
= DRE
->getDecl();
636 if (Ctx
.lookup(VDec
)) {
637 if (BO
->getOpcode() == BO_Assign
)
638 Ctx
= VMap
->updateDefinition(VDec
, BO
->getRHS(), Ctx
);
640 // FIXME -- handle compound assignment operators
641 Ctx
= VMap
->clearDefinition(VDec
, Ctx
);
642 VMap
->saveContext(BO
, Ctx
);
647 // Computes the intersection of two contexts. The intersection is the
648 // set of variables which have the same definition in both contexts;
649 // variables with different definitions are discarded.
650 LocalVariableMap::Context
651 LocalVariableMap::intersectContexts(Context C1
, Context C2
) {
653 for (const auto &P
: C1
) {
654 const NamedDecl
*Dec
= P
.first
;
655 const unsigned *i2
= C2
.lookup(Dec
);
656 if (!i2
) // variable doesn't exist on second path
657 Result
= removeDefinition(Dec
, Result
);
658 else if (*i2
!= P
.second
) // variable exists, but has different definition
659 Result
= clearDefinition(Dec
, Result
);
664 // For every variable in C, create a new variable that refers to the
665 // definition in C. Return a new context that contains these new variables.
666 // (We use this for a naive implementation of SSA on loop back-edges.)
667 LocalVariableMap::Context
LocalVariableMap::createReferenceContext(Context C
) {
668 Context Result
= getEmptyContext();
669 for (const auto &P
: C
)
670 Result
= addReference(P
.first
, P
.second
, Result
);
674 // This routine also takes the intersection of C1 and C2, but it does so by
675 // altering the VarDefinitions. C1 must be the result of an earlier call to
676 // createReferenceContext.
677 void LocalVariableMap::intersectBackEdge(Context C1
, Context C2
) {
678 for (const auto &P
: C1
) {
679 unsigned i1
= P
.second
;
680 VarDefinition
*VDef
= &VarDefinitions
[i1
];
681 assert(VDef
->isReference());
683 const unsigned *i2
= C2
.lookup(P
.first
);
684 if (!i2
|| (*i2
!= i1
))
685 VDef
->Ref
= 0; // Mark this variable as undefined
689 // Traverse the CFG in topological order, so all predecessors of a block
690 // (excluding back-edges) are visited before the block itself. At
691 // each point in the code, we calculate a Context, which holds the set of
692 // variable definitions which are visible at that point in execution.
693 // Visible variables are mapped to their definitions using an array that
694 // contains all definitions.
696 // At join points in the CFG, the set is computed as the intersection of
697 // the incoming sets along each edge, E.g.
699 // { Context | VarDefinitions }
700 // int x = 0; { x -> x1 | x1 = 0 }
701 // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
702 // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
703 // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
704 // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
706 // This is essentially a simpler and more naive version of the standard SSA
707 // algorithm. Those definitions that remain in the intersection are from blocks
708 // that strictly dominate the current block. We do not bother to insert proper
709 // phi nodes, because they are not used in our analysis; instead, wherever
710 // a phi node would be required, we simply remove that definition from the
711 // context (E.g. x above).
713 // The initial traversal does not capture back-edges, so those need to be
714 // handled on a separate pass. Whenever the first pass encounters an
715 // incoming back edge, it duplicates the context, creating new definitions
716 // that refer back to the originals. (These correspond to places where SSA
717 // might have to insert a phi node.) On the second pass, these definitions are
718 // set to NULL if the variable has changed on the back-edge (i.e. a phi
719 // node was actually required.) E.g.
721 // { Context | VarDefinitions }
722 // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
723 // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
724 // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
725 // ... { y -> y1 | x3 = 2, x2 = 1, ... }
726 void LocalVariableMap::traverseCFG(CFG
*CFGraph
,
727 const PostOrderCFGView
*SortedGraph
,
728 std::vector
<CFGBlockInfo
> &BlockInfo
) {
729 PostOrderCFGView::CFGBlockSet
VisitedBlocks(CFGraph
);
731 for (const auto *CurrBlock
: *SortedGraph
) {
732 unsigned CurrBlockID
= CurrBlock
->getBlockID();
733 CFGBlockInfo
*CurrBlockInfo
= &BlockInfo
[CurrBlockID
];
735 VisitedBlocks
.insert(CurrBlock
);
737 // Calculate the entry context for the current block
738 bool HasBackEdges
= false;
740 for (CFGBlock::const_pred_iterator PI
= CurrBlock
->pred_begin(),
741 PE
= CurrBlock
->pred_end(); PI
!= PE
; ++PI
) {
742 // if *PI -> CurrBlock is a back edge, so skip it
743 if (*PI
== nullptr || !VisitedBlocks
.alreadySet(*PI
)) {
748 unsigned PrevBlockID
= (*PI
)->getBlockID();
749 CFGBlockInfo
*PrevBlockInfo
= &BlockInfo
[PrevBlockID
];
752 CurrBlockInfo
->EntryContext
= PrevBlockInfo
->ExitContext
;
756 CurrBlockInfo
->EntryContext
=
757 intersectContexts(CurrBlockInfo
->EntryContext
,
758 PrevBlockInfo
->ExitContext
);
762 // Duplicate the context if we have back-edges, so we can call
763 // intersectBackEdges later.
765 CurrBlockInfo
->EntryContext
=
766 createReferenceContext(CurrBlockInfo
->EntryContext
);
768 // Create a starting context index for the current block
769 saveContext(nullptr, CurrBlockInfo
->EntryContext
);
770 CurrBlockInfo
->EntryIndex
= getContextIndex();
772 // Visit all the statements in the basic block.
773 VarMapBuilder
VMapBuilder(this, CurrBlockInfo
->EntryContext
);
774 for (const auto &BI
: *CurrBlock
) {
775 switch (BI
.getKind()) {
776 case CFGElement::Statement
: {
777 CFGStmt CS
= BI
.castAs
<CFGStmt
>();
778 VMapBuilder
.Visit(CS
.getStmt());
785 CurrBlockInfo
->ExitContext
= VMapBuilder
.Ctx
;
787 // Mark variables on back edges as "unknown" if they've been changed.
788 for (CFGBlock::const_succ_iterator SI
= CurrBlock
->succ_begin(),
789 SE
= CurrBlock
->succ_end(); SI
!= SE
; ++SI
) {
790 // if CurrBlock -> *SI is *not* a back edge
791 if (*SI
== nullptr || !VisitedBlocks
.alreadySet(*SI
))
794 CFGBlock
*FirstLoopBlock
= *SI
;
795 Context LoopBegin
= BlockInfo
[FirstLoopBlock
->getBlockID()].EntryContext
;
796 Context LoopEnd
= CurrBlockInfo
->ExitContext
;
797 intersectBackEdge(LoopBegin
, LoopEnd
);
801 // Put an extra entry at the end of the indexed context array
802 unsigned exitID
= CFGraph
->getExit().getBlockID();
803 saveContext(nullptr, BlockInfo
[exitID
].ExitContext
);
806 /// Find the appropriate source locations to use when producing diagnostics for
807 /// each block in the CFG.
808 static void findBlockLocations(CFG
*CFGraph
,
809 const PostOrderCFGView
*SortedGraph
,
810 std::vector
<CFGBlockInfo
> &BlockInfo
) {
811 for (const auto *CurrBlock
: *SortedGraph
) {
812 CFGBlockInfo
*CurrBlockInfo
= &BlockInfo
[CurrBlock
->getBlockID()];
814 // Find the source location of the last statement in the block, if the
815 // block is not empty.
816 if (const Stmt
*S
= CurrBlock
->getTerminatorStmt()) {
817 CurrBlockInfo
->EntryLoc
= CurrBlockInfo
->ExitLoc
= S
->getBeginLoc();
819 for (CFGBlock::const_reverse_iterator BI
= CurrBlock
->rbegin(),
820 BE
= CurrBlock
->rend(); BI
!= BE
; ++BI
) {
821 // FIXME: Handle other CFGElement kinds.
822 if (std::optional
<CFGStmt
> CS
= BI
->getAs
<CFGStmt
>()) {
823 CurrBlockInfo
->ExitLoc
= CS
->getStmt()->getBeginLoc();
829 if (CurrBlockInfo
->ExitLoc
.isValid()) {
830 // This block contains at least one statement. Find the source location
831 // of the first statement in the block.
832 for (const auto &BI
: *CurrBlock
) {
833 // FIXME: Handle other CFGElement kinds.
834 if (std::optional
<CFGStmt
> CS
= BI
.getAs
<CFGStmt
>()) {
835 CurrBlockInfo
->EntryLoc
= CS
->getStmt()->getBeginLoc();
839 } else if (CurrBlock
->pred_size() == 1 && *CurrBlock
->pred_begin() &&
840 CurrBlock
!= &CFGraph
->getExit()) {
841 // The block is empty, and has a single predecessor. Use its exit
843 CurrBlockInfo
->EntryLoc
= CurrBlockInfo
->ExitLoc
=
844 BlockInfo
[(*CurrBlock
->pred_begin())->getBlockID()].ExitLoc
;
845 } else if (CurrBlock
->succ_size() == 1 && *CurrBlock
->succ_begin()) {
846 // The block is empty, and has a single successor. Use its entry
848 CurrBlockInfo
->EntryLoc
= CurrBlockInfo
->ExitLoc
=
849 BlockInfo
[(*CurrBlock
->succ_begin())->getBlockID()].EntryLoc
;
856 class LockableFactEntry
: public FactEntry
{
858 LockableFactEntry(const CapabilityExpr
&CE
, LockKind LK
, SourceLocation Loc
,
859 SourceKind Src
= Acquired
)
860 : FactEntry(CE
, LK
, Loc
, Src
) {}
863 handleRemovalFromIntersection(const FactSet
&FSet
, FactManager
&FactMan
,
864 SourceLocation JoinLoc
, LockErrorKind LEK
,
865 ThreadSafetyHandler
&Handler
) const override
{
866 if (!asserted() && !negative() && !isUniversal()) {
867 Handler
.handleMutexHeldEndOfScope(getKind(), toString(), loc(), JoinLoc
,
872 void handleLock(FactSet
&FSet
, FactManager
&FactMan
, const FactEntry
&entry
,
873 ThreadSafetyHandler
&Handler
) const override
{
874 Handler
.handleDoubleLock(entry
.getKind(), entry
.toString(), loc(),
878 void handleUnlock(FactSet
&FSet
, FactManager
&FactMan
,
879 const CapabilityExpr
&Cp
, SourceLocation UnlockLoc
,
881 ThreadSafetyHandler
&Handler
) const override
{
882 FSet
.removeLock(FactMan
, Cp
);
883 if (!Cp
.negative()) {
884 FSet
.addLock(FactMan
, std::make_unique
<LockableFactEntry
>(
885 !Cp
, LK_Exclusive
, UnlockLoc
));
890 class ScopedLockableFactEntry
: public FactEntry
{
892 enum UnderlyingCapabilityKind
{
893 UCK_Acquired
, ///< Any kind of acquired capability.
894 UCK_ReleasedShared
, ///< Shared capability that was released.
895 UCK_ReleasedExclusive
, ///< Exclusive capability that was released.
898 struct UnderlyingCapability
{
900 UnderlyingCapabilityKind Kind
;
903 SmallVector
<UnderlyingCapability
, 2> UnderlyingMutexes
;
906 ScopedLockableFactEntry(const CapabilityExpr
&CE
, SourceLocation Loc
)
907 : FactEntry(CE
, LK_Exclusive
, Loc
, Acquired
) {}
909 void addLock(const CapabilityExpr
&M
) {
910 UnderlyingMutexes
.push_back(UnderlyingCapability
{M
, UCK_Acquired
});
913 void addExclusiveUnlock(const CapabilityExpr
&M
) {
914 UnderlyingMutexes
.push_back(UnderlyingCapability
{M
, UCK_ReleasedExclusive
});
917 void addSharedUnlock(const CapabilityExpr
&M
) {
918 UnderlyingMutexes
.push_back(UnderlyingCapability
{M
, UCK_ReleasedShared
});
922 handleRemovalFromIntersection(const FactSet
&FSet
, FactManager
&FactMan
,
923 SourceLocation JoinLoc
, LockErrorKind LEK
,
924 ThreadSafetyHandler
&Handler
) const override
{
925 for (const auto &UnderlyingMutex
: UnderlyingMutexes
) {
926 const auto *Entry
= FSet
.findLock(FactMan
, UnderlyingMutex
.Cap
);
927 if ((UnderlyingMutex
.Kind
== UCK_Acquired
&& Entry
) ||
928 (UnderlyingMutex
.Kind
!= UCK_Acquired
&& !Entry
)) {
929 // If this scoped lock manages another mutex, and if the underlying
930 // mutex is still/not held, then warn about the underlying mutex.
931 Handler
.handleMutexHeldEndOfScope(UnderlyingMutex
.Cap
.getKind(),
932 UnderlyingMutex
.Cap
.toString(), loc(),
938 void handleLock(FactSet
&FSet
, FactManager
&FactMan
, const FactEntry
&entry
,
939 ThreadSafetyHandler
&Handler
) const override
{
940 for (const auto &UnderlyingMutex
: UnderlyingMutexes
) {
941 if (UnderlyingMutex
.Kind
== UCK_Acquired
)
942 lock(FSet
, FactMan
, UnderlyingMutex
.Cap
, entry
.kind(), entry
.loc(),
945 unlock(FSet
, FactMan
, UnderlyingMutex
.Cap
, entry
.loc(), &Handler
);
949 void handleUnlock(FactSet
&FSet
, FactManager
&FactMan
,
950 const CapabilityExpr
&Cp
, SourceLocation UnlockLoc
,
952 ThreadSafetyHandler
&Handler
) const override
{
953 assert(!Cp
.negative() && "Managing object cannot be negative.");
954 for (const auto &UnderlyingMutex
: UnderlyingMutexes
) {
955 // Remove/lock the underlying mutex if it exists/is still unlocked; warn
956 // on double unlocking/locking if we're not destroying the scoped object.
957 ThreadSafetyHandler
*TSHandler
= FullyRemove
? nullptr : &Handler
;
958 if (UnderlyingMutex
.Kind
== UCK_Acquired
) {
959 unlock(FSet
, FactMan
, UnderlyingMutex
.Cap
, UnlockLoc
, TSHandler
);
961 LockKind kind
= UnderlyingMutex
.Kind
== UCK_ReleasedShared
964 lock(FSet
, FactMan
, UnderlyingMutex
.Cap
, kind
, UnlockLoc
, TSHandler
);
968 FSet
.removeLock(FactMan
, Cp
);
972 void lock(FactSet
&FSet
, FactManager
&FactMan
, const CapabilityExpr
&Cp
,
973 LockKind kind
, SourceLocation loc
,
974 ThreadSafetyHandler
*Handler
) const {
975 if (const FactEntry
*Fact
= FSet
.findLock(FactMan
, Cp
)) {
977 Handler
->handleDoubleLock(Cp
.getKind(), Cp
.toString(), Fact
->loc(),
980 FSet
.removeLock(FactMan
, !Cp
);
981 FSet
.addLock(FactMan
,
982 std::make_unique
<LockableFactEntry
>(Cp
, kind
, loc
, Managed
));
986 void unlock(FactSet
&FSet
, FactManager
&FactMan
, const CapabilityExpr
&Cp
,
987 SourceLocation loc
, ThreadSafetyHandler
*Handler
) const {
988 if (FSet
.findLock(FactMan
, Cp
)) {
989 FSet
.removeLock(FactMan
, Cp
);
990 FSet
.addLock(FactMan
, std::make_unique
<LockableFactEntry
>(
991 !Cp
, LK_Exclusive
, loc
));
992 } else if (Handler
) {
993 SourceLocation PrevLoc
;
994 if (const FactEntry
*Neg
= FSet
.findLock(FactMan
, !Cp
))
995 PrevLoc
= Neg
->loc();
996 Handler
->handleUnmatchedUnlock(Cp
.getKind(), Cp
.toString(), loc
, PrevLoc
);
1001 /// Class which implements the core thread safety analysis routines.
1002 class ThreadSafetyAnalyzer
{
1003 friend class BuildLockset
;
1004 friend class threadSafety::BeforeSet
;
1006 llvm::BumpPtrAllocator Bpa
;
1007 threadSafety::til::MemRegionRef Arena
;
1008 threadSafety::SExprBuilder SxBuilder
;
1010 ThreadSafetyHandler
&Handler
;
1011 const CXXMethodDecl
*CurrentMethod
= nullptr;
1012 LocalVariableMap LocalVarMap
;
1013 FactManager FactMan
;
1014 std::vector
<CFGBlockInfo
> BlockInfo
;
1016 BeforeSet
*GlobalBeforeSet
;
1019 ThreadSafetyAnalyzer(ThreadSafetyHandler
&H
, BeforeSet
* Bset
)
1020 : Arena(&Bpa
), SxBuilder(Arena
), Handler(H
), GlobalBeforeSet(Bset
) {}
1022 bool inCurrentScope(const CapabilityExpr
&CapE
);
1024 void addLock(FactSet
&FSet
, std::unique_ptr
<FactEntry
> Entry
,
1025 bool ReqAttr
= false);
1026 void removeLock(FactSet
&FSet
, const CapabilityExpr
&CapE
,
1027 SourceLocation UnlockLoc
, bool FullyRemove
, LockKind Kind
);
1029 template <typename AttrType
>
1030 void getMutexIDs(CapExprSet
&Mtxs
, AttrType
*Attr
, const Expr
*Exp
,
1031 const NamedDecl
*D
, til::SExpr
*Self
= nullptr);
1033 template <class AttrType
>
1034 void getMutexIDs(CapExprSet
&Mtxs
, AttrType
*Attr
, const Expr
*Exp
,
1036 const CFGBlock
*PredBlock
, const CFGBlock
*CurrBlock
,
1037 Expr
*BrE
, bool Neg
);
1039 const CallExpr
* getTrylockCallExpr(const Stmt
*Cond
, LocalVarContext C
,
1042 void getEdgeLockset(FactSet
&Result
, const FactSet
&ExitSet
,
1043 const CFGBlock
* PredBlock
,
1044 const CFGBlock
*CurrBlock
);
1046 bool join(const FactEntry
&a
, const FactEntry
&b
, bool CanModify
);
1048 void intersectAndWarn(FactSet
&EntrySet
, const FactSet
&ExitSet
,
1049 SourceLocation JoinLoc
, LockErrorKind EntryLEK
,
1050 LockErrorKind ExitLEK
);
1052 void intersectAndWarn(FactSet
&EntrySet
, const FactSet
&ExitSet
,
1053 SourceLocation JoinLoc
, LockErrorKind LEK
) {
1054 intersectAndWarn(EntrySet
, ExitSet
, JoinLoc
, LEK
, LEK
);
1057 void runAnalysis(AnalysisDeclContext
&AC
);
1062 /// Process acquired_before and acquired_after attributes on Vd.
1063 BeforeSet::BeforeInfo
* BeforeSet::insertAttrExprs(const ValueDecl
* Vd
,
1064 ThreadSafetyAnalyzer
& Analyzer
) {
1065 // Create a new entry for Vd.
1066 BeforeInfo
*Info
= nullptr;
1068 // Keep InfoPtr in its own scope in case BMap is modified later and the
1069 // reference becomes invalid.
1070 std::unique_ptr
<BeforeInfo
> &InfoPtr
= BMap
[Vd
];
1072 InfoPtr
.reset(new BeforeInfo());
1073 Info
= InfoPtr
.get();
1076 for (const auto *At
: Vd
->attrs()) {
1077 switch (At
->getKind()) {
1078 case attr::AcquiredBefore
: {
1079 const auto *A
= cast
<AcquiredBeforeAttr
>(At
);
1081 // Read exprs from the attribute, and add them to BeforeVect.
1082 for (const auto *Arg
: A
->args()) {
1084 Analyzer
.SxBuilder
.translateAttrExpr(Arg
, nullptr);
1085 if (const ValueDecl
*Cpvd
= Cp
.valueDecl()) {
1086 Info
->Vect
.push_back(Cpvd
);
1087 const auto It
= BMap
.find(Cpvd
);
1088 if (It
== BMap
.end())
1089 insertAttrExprs(Cpvd
, Analyzer
);
1094 case attr::AcquiredAfter
: {
1095 const auto *A
= cast
<AcquiredAfterAttr
>(At
);
1097 // Read exprs from the attribute, and add them to BeforeVect.
1098 for (const auto *Arg
: A
->args()) {
1100 Analyzer
.SxBuilder
.translateAttrExpr(Arg
, nullptr);
1101 if (const ValueDecl
*ArgVd
= Cp
.valueDecl()) {
1102 // Get entry for mutex listed in attribute
1103 BeforeInfo
*ArgInfo
= getBeforeInfoForDecl(ArgVd
, Analyzer
);
1104 ArgInfo
->Vect
.push_back(Vd
);
1117 BeforeSet::BeforeInfo
*
1118 BeforeSet::getBeforeInfoForDecl(const ValueDecl
*Vd
,
1119 ThreadSafetyAnalyzer
&Analyzer
) {
1120 auto It
= BMap
.find(Vd
);
1121 BeforeInfo
*Info
= nullptr;
1122 if (It
== BMap
.end())
1123 Info
= insertAttrExprs(Vd
, Analyzer
);
1125 Info
= It
->second
.get();
1126 assert(Info
&& "BMap contained nullptr?");
1130 /// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1131 void BeforeSet::checkBeforeAfter(const ValueDecl
* StartVd
,
1132 const FactSet
& FSet
,
1133 ThreadSafetyAnalyzer
& Analyzer
,
1134 SourceLocation Loc
, StringRef CapKind
) {
1135 SmallVector
<BeforeInfo
*, 8> InfoVect
;
1137 // Do a depth-first traversal of Vd.
1138 // Return true if there are cycles.
1139 std::function
<bool (const ValueDecl
*)> traverse
= [&](const ValueDecl
* Vd
) {
1143 BeforeSet::BeforeInfo
*Info
= getBeforeInfoForDecl(Vd
, Analyzer
);
1145 if (Info
->Visited
== 1)
1148 if (Info
->Visited
== 2)
1151 if (Info
->Vect
.empty())
1154 InfoVect
.push_back(Info
);
1156 for (const auto *Vdb
: Info
->Vect
) {
1157 // Exclude mutexes in our immediate before set.
1158 if (FSet
.containsMutexDecl(Analyzer
.FactMan
, Vdb
)) {
1159 StringRef L1
= StartVd
->getName();
1160 StringRef L2
= Vdb
->getName();
1161 Analyzer
.Handler
.handleLockAcquiredBefore(CapKind
, L1
, L2
, Loc
);
1163 // Transitively search other before sets, and warn on cycles.
1164 if (traverse(Vdb
)) {
1165 if (!CycMap
.contains(Vd
)) {
1166 CycMap
.insert(std::make_pair(Vd
, true));
1167 StringRef L1
= Vd
->getName();
1168 Analyzer
.Handler
.handleBeforeAfterCycle(L1
, Vd
->getLocation());
1178 for (auto *Info
: InfoVect
)
1182 /// Gets the value decl pointer from DeclRefExprs or MemberExprs.
1183 static const ValueDecl
*getValueDecl(const Expr
*Exp
) {
1184 if (const auto *CE
= dyn_cast
<ImplicitCastExpr
>(Exp
))
1185 return getValueDecl(CE
->getSubExpr());
1187 if (const auto *DR
= dyn_cast
<DeclRefExpr
>(Exp
))
1188 return DR
->getDecl();
1190 if (const auto *ME
= dyn_cast
<MemberExpr
>(Exp
))
1191 return ME
->getMemberDecl();
1198 template <typename Ty
>
1199 class has_arg_iterator_range
{
1200 using yes
= char[1];
1203 template <typename Inner
>
1204 static yes
& test(Inner
*I
, decltype(I
->args()) * = nullptr);
1207 static no
& test(...);
1210 static const bool value
= sizeof(test
<Ty
>(nullptr)) == sizeof(yes
);
1215 bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr
&CapE
) {
1216 const threadSafety::til::SExpr
*SExp
= CapE
.sexpr();
1217 assert(SExp
&& "Null expressions should be ignored");
1219 if (const auto *LP
= dyn_cast
<til::LiteralPtr
>(SExp
)) {
1220 const ValueDecl
*VD
= LP
->clangDecl();
1221 // Variables defined in a function are always inaccessible.
1222 if (!VD
|| !VD
->isDefinedOutsideFunctionOrMethod())
1224 // For now we consider static class members to be inaccessible.
1225 if (isa
<CXXRecordDecl
>(VD
->getDeclContext()))
1227 // Global variables are always in scope.
1231 // Members are in scope from methods of the same class.
1232 if (const auto *P
= dyn_cast
<til::Project
>(SExp
)) {
1235 const ValueDecl
*VD
= P
->clangDecl();
1236 return VD
->getDeclContext() == CurrentMethod
->getDeclContext();
1242 /// Add a new lock to the lockset, warning if the lock is already there.
1243 /// \param ReqAttr -- true if this is part of an initial Requires attribute.
1244 void ThreadSafetyAnalyzer::addLock(FactSet
&FSet
,
1245 std::unique_ptr
<FactEntry
> Entry
,
1247 if (Entry
->shouldIgnore())
1250 if (!ReqAttr
&& !Entry
->negative()) {
1251 // look for the negative capability, and remove it from the fact set.
1252 CapabilityExpr NegC
= !*Entry
;
1253 const FactEntry
*Nen
= FSet
.findLock(FactMan
, NegC
);
1255 FSet
.removeLock(FactMan
, NegC
);
1258 if (inCurrentScope(*Entry
) && !Entry
->asserted())
1259 Handler
.handleNegativeNotHeld(Entry
->getKind(), Entry
->toString(),
1260 NegC
.toString(), Entry
->loc());
1264 // Check before/after constraints
1265 if (Handler
.issueBetaWarnings() &&
1266 !Entry
->asserted() && !Entry
->declared()) {
1267 GlobalBeforeSet
->checkBeforeAfter(Entry
->valueDecl(), FSet
, *this,
1268 Entry
->loc(), Entry
->getKind());
1271 // FIXME: Don't always warn when we have support for reentrant locks.
1272 if (const FactEntry
*Cp
= FSet
.findLock(FactMan
, *Entry
)) {
1273 if (!Entry
->asserted())
1274 Cp
->handleLock(FSet
, FactMan
, *Entry
, Handler
);
1276 FSet
.addLock(FactMan
, std::move(Entry
));
1280 /// Remove a lock from the lockset, warning if the lock is not there.
1281 /// \param UnlockLoc The source location of the unlock (only used in error msg)
1282 void ThreadSafetyAnalyzer::removeLock(FactSet
&FSet
, const CapabilityExpr
&Cp
,
1283 SourceLocation UnlockLoc
,
1284 bool FullyRemove
, LockKind ReceivedKind
) {
1285 if (Cp
.shouldIgnore())
1288 const FactEntry
*LDat
= FSet
.findLock(FactMan
, Cp
);
1290 SourceLocation PrevLoc
;
1291 if (const FactEntry
*Neg
= FSet
.findLock(FactMan
, !Cp
))
1292 PrevLoc
= Neg
->loc();
1293 Handler
.handleUnmatchedUnlock(Cp
.getKind(), Cp
.toString(), UnlockLoc
,
1298 // Generic lock removal doesn't care about lock kind mismatches, but
1299 // otherwise diagnose when the lock kinds are mismatched.
1300 if (ReceivedKind
!= LK_Generic
&& LDat
->kind() != ReceivedKind
) {
1301 Handler
.handleIncorrectUnlockKind(Cp
.getKind(), Cp
.toString(), LDat
->kind(),
1302 ReceivedKind
, LDat
->loc(), UnlockLoc
);
1305 LDat
->handleUnlock(FSet
, FactMan
, Cp
, UnlockLoc
, FullyRemove
, Handler
);
1308 /// Extract the list of mutexIDs from the attribute on an expression,
1309 /// and push them onto Mtxs, discarding any duplicates.
1310 template <typename AttrType
>
1311 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet
&Mtxs
, AttrType
*Attr
,
1312 const Expr
*Exp
, const NamedDecl
*D
,
1314 if (Attr
->args_size() == 0) {
1315 // The mutex held is the "this" object.
1316 CapabilityExpr Cp
= SxBuilder
.translateAttrExpr(nullptr, D
, Exp
, Self
);
1317 if (Cp
.isInvalid()) {
1318 warnInvalidLock(Handler
, nullptr, D
, Exp
, Cp
.getKind());
1322 if (!Cp
.shouldIgnore())
1323 Mtxs
.push_back_nodup(Cp
);
1327 for (const auto *Arg
: Attr
->args()) {
1328 CapabilityExpr Cp
= SxBuilder
.translateAttrExpr(Arg
, D
, Exp
, Self
);
1329 if (Cp
.isInvalid()) {
1330 warnInvalidLock(Handler
, nullptr, D
, Exp
, Cp
.getKind());
1334 if (!Cp
.shouldIgnore())
1335 Mtxs
.push_back_nodup(Cp
);
1339 /// Extract the list of mutexIDs from a trylock attribute. If the
1340 /// trylock applies to the given edge, then push them onto Mtxs, discarding
1342 template <class AttrType
>
1343 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet
&Mtxs
, AttrType
*Attr
,
1344 const Expr
*Exp
, const NamedDecl
*D
,
1345 const CFGBlock
*PredBlock
,
1346 const CFGBlock
*CurrBlock
,
1347 Expr
*BrE
, bool Neg
) {
1348 // Find out which branch has the lock
1349 bool branch
= false;
1350 if (const auto *BLE
= dyn_cast_or_null
<CXXBoolLiteralExpr
>(BrE
))
1351 branch
= BLE
->getValue();
1352 else if (const auto *ILE
= dyn_cast_or_null
<IntegerLiteral
>(BrE
))
1353 branch
= ILE
->getValue().getBoolValue();
1355 int branchnum
= branch
? 0 : 1;
1357 branchnum
= !branchnum
;
1359 // If we've taken the trylock branch, then add the lock
1361 for (CFGBlock::const_succ_iterator SI
= PredBlock
->succ_begin(),
1362 SE
= PredBlock
->succ_end(); SI
!= SE
&& i
< 2; ++SI
, ++i
) {
1363 if (*SI
== CurrBlock
&& i
== branchnum
)
1364 getMutexIDs(Mtxs
, Attr
, Exp
, D
);
1368 static bool getStaticBooleanValue(Expr
*E
, bool &TCond
) {
1369 if (isa
<CXXNullPtrLiteralExpr
>(E
) || isa
<GNUNullExpr
>(E
)) {
1372 } else if (const auto *BLE
= dyn_cast
<CXXBoolLiteralExpr
>(E
)) {
1373 TCond
= BLE
->getValue();
1375 } else if (const auto *ILE
= dyn_cast
<IntegerLiteral
>(E
)) {
1376 TCond
= ILE
->getValue().getBoolValue();
1378 } else if (auto *CE
= dyn_cast
<ImplicitCastExpr
>(E
))
1379 return getStaticBooleanValue(CE
->getSubExpr(), TCond
);
1383 // If Cond can be traced back to a function call, return the call expression.
1384 // The negate variable should be called with false, and will be set to true
1385 // if the function call is negated, e.g. if (!mu.tryLock(...))
1386 const CallExpr
* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt
*Cond
,
1392 if (const auto *CallExp
= dyn_cast
<CallExpr
>(Cond
)) {
1393 if (CallExp
->getBuiltinCallee() == Builtin::BI__builtin_expect
)
1394 return getTrylockCallExpr(CallExp
->getArg(0), C
, Negate
);
1397 else if (const auto *PE
= dyn_cast
<ParenExpr
>(Cond
))
1398 return getTrylockCallExpr(PE
->getSubExpr(), C
, Negate
);
1399 else if (const auto *CE
= dyn_cast
<ImplicitCastExpr
>(Cond
))
1400 return getTrylockCallExpr(CE
->getSubExpr(), C
, Negate
);
1401 else if (const auto *FE
= dyn_cast
<FullExpr
>(Cond
))
1402 return getTrylockCallExpr(FE
->getSubExpr(), C
, Negate
);
1403 else if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(Cond
)) {
1404 const Expr
*E
= LocalVarMap
.lookupExpr(DRE
->getDecl(), C
);
1405 return getTrylockCallExpr(E
, C
, Negate
);
1407 else if (const auto *UOP
= dyn_cast
<UnaryOperator
>(Cond
)) {
1408 if (UOP
->getOpcode() == UO_LNot
) {
1410 return getTrylockCallExpr(UOP
->getSubExpr(), C
, Negate
);
1414 else if (const auto *BOP
= dyn_cast
<BinaryOperator
>(Cond
)) {
1415 if (BOP
->getOpcode() == BO_EQ
|| BOP
->getOpcode() == BO_NE
) {
1416 if (BOP
->getOpcode() == BO_NE
)
1420 if (getStaticBooleanValue(BOP
->getRHS(), TCond
)) {
1421 if (!TCond
) Negate
= !Negate
;
1422 return getTrylockCallExpr(BOP
->getLHS(), C
, Negate
);
1425 if (getStaticBooleanValue(BOP
->getLHS(), TCond
)) {
1426 if (!TCond
) Negate
= !Negate
;
1427 return getTrylockCallExpr(BOP
->getRHS(), C
, Negate
);
1431 if (BOP
->getOpcode() == BO_LAnd
) {
1432 // LHS must have been evaluated in a different block.
1433 return getTrylockCallExpr(BOP
->getRHS(), C
, Negate
);
1435 if (BOP
->getOpcode() == BO_LOr
)
1436 return getTrylockCallExpr(BOP
->getRHS(), C
, Negate
);
1438 } else if (const auto *COP
= dyn_cast
<ConditionalOperator
>(Cond
)) {
1440 if (getStaticBooleanValue(COP
->getTrueExpr(), TCond
) &&
1441 getStaticBooleanValue(COP
->getFalseExpr(), FCond
)) {
1442 if (TCond
&& !FCond
)
1443 return getTrylockCallExpr(COP
->getCond(), C
, Negate
);
1444 if (!TCond
&& FCond
) {
1446 return getTrylockCallExpr(COP
->getCond(), C
, Negate
);
1453 /// Find the lockset that holds on the edge between PredBlock
1454 /// and CurrBlock. The edge set is the exit set of PredBlock (passed
1455 /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1456 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet
& Result
,
1457 const FactSet
&ExitSet
,
1458 const CFGBlock
*PredBlock
,
1459 const CFGBlock
*CurrBlock
) {
1462 const Stmt
*Cond
= PredBlock
->getTerminatorCondition();
1463 // We don't acquire try-locks on ?: branches, only when its result is used.
1464 if (!Cond
|| isa
<ConditionalOperator
>(PredBlock
->getTerminatorStmt()))
1467 bool Negate
= false;
1468 const CFGBlockInfo
*PredBlockInfo
= &BlockInfo
[PredBlock
->getBlockID()];
1469 const LocalVarContext
&LVarCtx
= PredBlockInfo
->ExitContext
;
1471 const auto *Exp
= getTrylockCallExpr(Cond
, LVarCtx
, Negate
);
1475 auto *FunDecl
= dyn_cast_or_null
<NamedDecl
>(Exp
->getCalleeDecl());
1476 if(!FunDecl
|| !FunDecl
->hasAttrs())
1479 CapExprSet ExclusiveLocksToAdd
;
1480 CapExprSet SharedLocksToAdd
;
1482 // If the condition is a call to a Trylock function, then grab the attributes
1483 for (const auto *Attr
: FunDecl
->attrs()) {
1484 switch (Attr
->getKind()) {
1485 case attr::TryAcquireCapability
: {
1486 auto *A
= cast
<TryAcquireCapabilityAttr
>(Attr
);
1487 getMutexIDs(A
->isShared() ? SharedLocksToAdd
: ExclusiveLocksToAdd
, A
,
1488 Exp
, FunDecl
, PredBlock
, CurrBlock
, A
->getSuccessValue(),
1492 case attr::ExclusiveTrylockFunction
: {
1493 const auto *A
= cast
<ExclusiveTrylockFunctionAttr
>(Attr
);
1494 getMutexIDs(ExclusiveLocksToAdd
, A
, Exp
, FunDecl
, PredBlock
, CurrBlock
,
1495 A
->getSuccessValue(), Negate
);
1498 case attr::SharedTrylockFunction
: {
1499 const auto *A
= cast
<SharedTrylockFunctionAttr
>(Attr
);
1500 getMutexIDs(SharedLocksToAdd
, A
, Exp
, FunDecl
, PredBlock
, CurrBlock
,
1501 A
->getSuccessValue(), Negate
);
1509 // Add and remove locks.
1510 SourceLocation Loc
= Exp
->getExprLoc();
1511 for (const auto &ExclusiveLockToAdd
: ExclusiveLocksToAdd
)
1512 addLock(Result
, std::make_unique
<LockableFactEntry
>(ExclusiveLockToAdd
,
1513 LK_Exclusive
, Loc
));
1514 for (const auto &SharedLockToAdd
: SharedLocksToAdd
)
1515 addLock(Result
, std::make_unique
<LockableFactEntry
>(SharedLockToAdd
,
1521 /// We use this class to visit different types of expressions in
1522 /// CFGBlocks, and build up the lockset.
1523 /// An expression may cause us to add or remove locks from the lockset, or else
1524 /// output error messages related to missing locks.
1525 /// FIXME: In future, we may be able to not inherit from a visitor.
1526 class BuildLockset
: public ConstStmtVisitor
<BuildLockset
> {
1527 friend class ThreadSafetyAnalyzer
;
1529 ThreadSafetyAnalyzer
*Analyzer
;
1531 /// Maps constructed objects to `this` placeholder prior to initialization.
1532 llvm::SmallDenseMap
<const Expr
*, til::LiteralPtr
*> ConstructedObjects
;
1533 LocalVariableMap::Context LVarCtx
;
1537 void warnIfMutexNotHeld(const NamedDecl
*D
, const Expr
*Exp
, AccessKind AK
,
1538 Expr
*MutexExp
, ProtectedOperationKind POK
,
1539 til::LiteralPtr
*Self
, SourceLocation Loc
);
1540 void warnIfMutexHeld(const NamedDecl
*D
, const Expr
*Exp
, Expr
*MutexExp
,
1541 til::LiteralPtr
*Self
, SourceLocation Loc
);
1543 void checkAccess(const Expr
*Exp
, AccessKind AK
,
1544 ProtectedOperationKind POK
= POK_VarAccess
);
1545 void checkPtAccess(const Expr
*Exp
, AccessKind AK
,
1546 ProtectedOperationKind POK
= POK_VarAccess
);
1548 void handleCall(const Expr
*Exp
, const NamedDecl
*D
,
1549 til::LiteralPtr
*Self
= nullptr,
1550 SourceLocation Loc
= SourceLocation());
1551 void examineArguments(const FunctionDecl
*FD
,
1552 CallExpr::const_arg_iterator ArgBegin
,
1553 CallExpr::const_arg_iterator ArgEnd
,
1554 bool SkipFirstParam
= false);
1557 BuildLockset(ThreadSafetyAnalyzer
*Anlzr
, CFGBlockInfo
&Info
)
1558 : ConstStmtVisitor
<BuildLockset
>(), Analyzer(Anlzr
), FSet(Info
.EntrySet
),
1559 LVarCtx(Info
.EntryContext
), CtxIndex(Info
.EntryIndex
) {}
1561 void VisitUnaryOperator(const UnaryOperator
*UO
);
1562 void VisitBinaryOperator(const BinaryOperator
*BO
);
1563 void VisitCastExpr(const CastExpr
*CE
);
1564 void VisitCallExpr(const CallExpr
*Exp
);
1565 void VisitCXXConstructExpr(const CXXConstructExpr
*Exp
);
1566 void VisitDeclStmt(const DeclStmt
*S
);
1567 void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr
*Exp
);
1572 /// Warn if the LSet does not contain a lock sufficient to protect access
1573 /// of at least the passed in AccessKind.
1574 void BuildLockset::warnIfMutexNotHeld(const NamedDecl
*D
, const Expr
*Exp
,
1575 AccessKind AK
, Expr
*MutexExp
,
1576 ProtectedOperationKind POK
,
1577 til::LiteralPtr
*Self
,
1578 SourceLocation Loc
) {
1579 LockKind LK
= getLockKindFromAccessKind(AK
);
1582 Analyzer
->SxBuilder
.translateAttrExpr(MutexExp
, D
, Exp
, Self
);
1583 if (Cp
.isInvalid()) {
1584 warnInvalidLock(Analyzer
->Handler
, MutexExp
, D
, Exp
, Cp
.getKind());
1586 } else if (Cp
.shouldIgnore()) {
1590 if (Cp
.negative()) {
1591 // Negative capabilities act like locks excluded
1592 const FactEntry
*LDat
= FSet
.findLock(Analyzer
->FactMan
, !Cp
);
1594 Analyzer
->Handler
.handleFunExcludesLock(
1595 Cp
.getKind(), D
->getNameAsString(), (!Cp
).toString(), Loc
);
1599 // If this does not refer to a negative capability in the same class,
1601 if (!Analyzer
->inCurrentScope(Cp
))
1604 // Otherwise the negative requirement must be propagated to the caller.
1605 LDat
= FSet
.findLock(Analyzer
->FactMan
, Cp
);
1607 Analyzer
->Handler
.handleNegativeNotHeld(D
, Cp
.toString(), Loc
);
1612 const FactEntry
*LDat
= FSet
.findLockUniv(Analyzer
->FactMan
, Cp
);
1613 bool NoError
= true;
1615 // No exact match found. Look for a partial match.
1616 LDat
= FSet
.findPartialMatch(Analyzer
->FactMan
, Cp
);
1618 // Warn that there's no precise match.
1619 std::string PartMatchStr
= LDat
->toString();
1620 StringRef
PartMatchName(PartMatchStr
);
1621 Analyzer
->Handler
.handleMutexNotHeld(Cp
.getKind(), D
, POK
, Cp
.toString(),
1622 LK
, Loc
, &PartMatchName
);
1624 // Warn that there's no match at all.
1625 Analyzer
->Handler
.handleMutexNotHeld(Cp
.getKind(), D
, POK
, Cp
.toString(),
1630 // Make sure the mutex we found is the right kind.
1631 if (NoError
&& LDat
&& !LDat
->isAtLeast(LK
)) {
1632 Analyzer
->Handler
.handleMutexNotHeld(Cp
.getKind(), D
, POK
, Cp
.toString(),
1637 /// Warn if the LSet contains the given lock.
1638 void BuildLockset::warnIfMutexHeld(const NamedDecl
*D
, const Expr
*Exp
,
1639 Expr
*MutexExp
, til::LiteralPtr
*Self
,
1640 SourceLocation Loc
) {
1642 Analyzer
->SxBuilder
.translateAttrExpr(MutexExp
, D
, Exp
, Self
);
1643 if (Cp
.isInvalid()) {
1644 warnInvalidLock(Analyzer
->Handler
, MutexExp
, D
, Exp
, Cp
.getKind());
1646 } else if (Cp
.shouldIgnore()) {
1650 const FactEntry
*LDat
= FSet
.findLock(Analyzer
->FactMan
, Cp
);
1652 Analyzer
->Handler
.handleFunExcludesLock(Cp
.getKind(), D
->getNameAsString(),
1653 Cp
.toString(), Loc
);
1657 /// Checks guarded_by and pt_guarded_by attributes.
1658 /// Whenever we identify an access (read or write) to a DeclRefExpr that is
1659 /// marked with guarded_by, we must ensure the appropriate mutexes are held.
1660 /// Similarly, we check if the access is to an expression that dereferences
1661 /// a pointer marked with pt_guarded_by.
1662 void BuildLockset::checkAccess(const Expr
*Exp
, AccessKind AK
,
1663 ProtectedOperationKind POK
) {
1664 Exp
= Exp
->IgnoreImplicit()->IgnoreParenCasts();
1666 SourceLocation Loc
= Exp
->getExprLoc();
1668 // Local variables of reference type cannot be re-assigned;
1669 // map them to their initializer.
1670 while (const auto *DRE
= dyn_cast
<DeclRefExpr
>(Exp
)) {
1671 const auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl()->getCanonicalDecl());
1672 if (VD
&& VD
->isLocalVarDecl() && VD
->getType()->isReferenceType()) {
1673 if (const auto *E
= VD
->getInit()) {
1674 // Guard against self-initialization. e.g., int &i = i;
1684 if (const auto *UO
= dyn_cast
<UnaryOperator
>(Exp
)) {
1686 if (UO
->getOpcode() == UO_Deref
)
1687 checkPtAccess(UO
->getSubExpr(), AK
, POK
);
1691 if (const auto *BO
= dyn_cast
<BinaryOperator
>(Exp
)) {
1692 switch (BO
->getOpcode()) {
1693 case BO_PtrMemD
: // .*
1694 return checkAccess(BO
->getLHS(), AK
, POK
);
1695 case BO_PtrMemI
: // ->*
1696 return checkPtAccess(BO
->getLHS(), AK
, POK
);
1702 if (const auto *AE
= dyn_cast
<ArraySubscriptExpr
>(Exp
)) {
1703 checkPtAccess(AE
->getLHS(), AK
, POK
);
1707 if (const auto *ME
= dyn_cast
<MemberExpr
>(Exp
)) {
1709 checkPtAccess(ME
->getBase(), AK
, POK
);
1711 checkAccess(ME
->getBase(), AK
, POK
);
1714 const ValueDecl
*D
= getValueDecl(Exp
);
1715 if (!D
|| !D
->hasAttrs())
1718 if (D
->hasAttr
<GuardedVarAttr
>() && FSet
.isEmpty(Analyzer
->FactMan
)) {
1719 Analyzer
->Handler
.handleNoMutexHeld(D
, POK
, AK
, Loc
);
1722 for (const auto *I
: D
->specific_attrs
<GuardedByAttr
>())
1723 warnIfMutexNotHeld(D
, Exp
, AK
, I
->getArg(), POK
, nullptr, Loc
);
1726 /// Checks pt_guarded_by and pt_guarded_var attributes.
1727 /// POK is the same operationKind that was passed to checkAccess.
1728 void BuildLockset::checkPtAccess(const Expr
*Exp
, AccessKind AK
,
1729 ProtectedOperationKind POK
) {
1731 if (const auto *PE
= dyn_cast
<ParenExpr
>(Exp
)) {
1732 Exp
= PE
->getSubExpr();
1735 if (const auto *CE
= dyn_cast
<CastExpr
>(Exp
)) {
1736 if (CE
->getCastKind() == CK_ArrayToPointerDecay
) {
1737 // If it's an actual array, and not a pointer, then it's elements
1738 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1739 checkAccess(CE
->getSubExpr(), AK
, POK
);
1742 Exp
= CE
->getSubExpr();
1748 // Pass by reference warnings are under a different flag.
1749 ProtectedOperationKind PtPOK
= POK_VarDereference
;
1750 if (POK
== POK_PassByRef
) PtPOK
= POK_PtPassByRef
;
1752 const ValueDecl
*D
= getValueDecl(Exp
);
1753 if (!D
|| !D
->hasAttrs())
1756 if (D
->hasAttr
<PtGuardedVarAttr
>() && FSet
.isEmpty(Analyzer
->FactMan
))
1757 Analyzer
->Handler
.handleNoMutexHeld(D
, PtPOK
, AK
, Exp
->getExprLoc());
1759 for (auto const *I
: D
->specific_attrs
<PtGuardedByAttr
>())
1760 warnIfMutexNotHeld(D
, Exp
, AK
, I
->getArg(), PtPOK
, nullptr,
1764 /// Process a function call, method call, constructor call,
1765 /// or destructor call. This involves looking at the attributes on the
1766 /// corresponding function/method/constructor/destructor, issuing warnings,
1767 /// and updating the locksets accordingly.
1769 /// FIXME: For classes annotated with one of the guarded annotations, we need
1770 /// to treat const method calls as reads and non-const method calls as writes,
1771 /// and check that the appropriate locks are held. Non-const method calls with
1772 /// the same signature as const method calls can be also treated as reads.
1774 /// \param Exp The call expression.
1775 /// \param D The callee declaration.
1776 /// \param Self If \p Exp = nullptr, the implicit this argument.
1777 /// \param Loc If \p Exp = nullptr, the location.
1778 void BuildLockset::handleCall(const Expr
*Exp
, const NamedDecl
*D
,
1779 til::LiteralPtr
*Self
, SourceLocation Loc
) {
1780 CapExprSet ExclusiveLocksToAdd
, SharedLocksToAdd
;
1781 CapExprSet ExclusiveLocksToRemove
, SharedLocksToRemove
, GenericLocksToRemove
;
1782 CapExprSet ScopedReqsAndExcludes
;
1784 // Figure out if we're constructing an object of scoped lockable class
1788 const auto *TagT
= Exp
->getType()->getAs
<TagType
>();
1789 if (TagT
&& Exp
->isPRValue()) {
1790 std::pair
<til::LiteralPtr
*, StringRef
> Placeholder
=
1791 Analyzer
->SxBuilder
.createThisPlaceholder(Exp
);
1792 [[maybe_unused
]] auto inserted
=
1793 ConstructedObjects
.insert({Exp
, Placeholder
.first
});
1794 assert(inserted
.second
&& "Are we visiting the same expression again?");
1795 if (isa
<CXXConstructExpr
>(Exp
))
1796 Self
= Placeholder
.first
;
1797 if (TagT
->getDecl()->hasAttr
<ScopedLockableAttr
>())
1798 Scp
= CapabilityExpr(Placeholder
.first
, Placeholder
.second
, false);
1801 assert(Loc
.isInvalid());
1802 Loc
= Exp
->getExprLoc();
1805 for(const Attr
*At
: D
->attrs()) {
1806 switch (At
->getKind()) {
1807 // When we encounter a lock function, we need to add the lock to our
1809 case attr::AcquireCapability
: {
1810 const auto *A
= cast
<AcquireCapabilityAttr
>(At
);
1811 Analyzer
->getMutexIDs(A
->isShared() ? SharedLocksToAdd
1812 : ExclusiveLocksToAdd
,
1817 // An assert will add a lock to the lockset, but will not generate
1818 // a warning if it is already there, and will not generate a warning
1819 // if it is not removed.
1820 case attr::AssertExclusiveLock
: {
1821 const auto *A
= cast
<AssertExclusiveLockAttr
>(At
);
1823 CapExprSet AssertLocks
;
1824 Analyzer
->getMutexIDs(AssertLocks
, A
, Exp
, D
, Self
);
1825 for (const auto &AssertLock
: AssertLocks
)
1827 FSet
, std::make_unique
<LockableFactEntry
>(
1828 AssertLock
, LK_Exclusive
, Loc
, FactEntry::Asserted
));
1831 case attr::AssertSharedLock
: {
1832 const auto *A
= cast
<AssertSharedLockAttr
>(At
);
1834 CapExprSet AssertLocks
;
1835 Analyzer
->getMutexIDs(AssertLocks
, A
, Exp
, D
, Self
);
1836 for (const auto &AssertLock
: AssertLocks
)
1838 FSet
, std::make_unique
<LockableFactEntry
>(
1839 AssertLock
, LK_Shared
, Loc
, FactEntry::Asserted
));
1843 case attr::AssertCapability
: {
1844 const auto *A
= cast
<AssertCapabilityAttr
>(At
);
1845 CapExprSet AssertLocks
;
1846 Analyzer
->getMutexIDs(AssertLocks
, A
, Exp
, D
, Self
);
1847 for (const auto &AssertLock
: AssertLocks
)
1848 Analyzer
->addLock(FSet
, std::make_unique
<LockableFactEntry
>(
1850 A
->isShared() ? LK_Shared
: LK_Exclusive
,
1851 Loc
, FactEntry::Asserted
));
1855 // When we encounter an unlock function, we need to remove unlocked
1856 // mutexes from the lockset, and flag a warning if they are not there.
1857 case attr::ReleaseCapability
: {
1858 const auto *A
= cast
<ReleaseCapabilityAttr
>(At
);
1860 Analyzer
->getMutexIDs(GenericLocksToRemove
, A
, Exp
, D
, Self
);
1861 else if (A
->isShared())
1862 Analyzer
->getMutexIDs(SharedLocksToRemove
, A
, Exp
, D
, Self
);
1864 Analyzer
->getMutexIDs(ExclusiveLocksToRemove
, A
, Exp
, D
, Self
);
1868 case attr::RequiresCapability
: {
1869 const auto *A
= cast
<RequiresCapabilityAttr
>(At
);
1870 for (auto *Arg
: A
->args()) {
1871 warnIfMutexNotHeld(D
, Exp
, A
->isShared() ? AK_Read
: AK_Written
, Arg
,
1872 POK_FunctionCall
, Self
, Loc
);
1873 // use for adopting a lock
1874 if (!Scp
.shouldIgnore())
1875 Analyzer
->getMutexIDs(ScopedReqsAndExcludes
, A
, Exp
, D
, Self
);
1880 case attr::LocksExcluded
: {
1881 const auto *A
= cast
<LocksExcludedAttr
>(At
);
1882 for (auto *Arg
: A
->args()) {
1883 warnIfMutexHeld(D
, Exp
, Arg
, Self
, Loc
);
1884 // use for deferring a lock
1885 if (!Scp
.shouldIgnore())
1886 Analyzer
->getMutexIDs(ScopedReqsAndExcludes
, A
, Exp
, D
, Self
);
1891 // Ignore attributes unrelated to thread-safety
1897 // Remove locks first to allow lock upgrading/downgrading.
1898 // FIXME -- should only fully remove if the attribute refers to 'this'.
1899 bool Dtor
= isa
<CXXDestructorDecl
>(D
);
1900 for (const auto &M
: ExclusiveLocksToRemove
)
1901 Analyzer
->removeLock(FSet
, M
, Loc
, Dtor
, LK_Exclusive
);
1902 for (const auto &M
: SharedLocksToRemove
)
1903 Analyzer
->removeLock(FSet
, M
, Loc
, Dtor
, LK_Shared
);
1904 for (const auto &M
: GenericLocksToRemove
)
1905 Analyzer
->removeLock(FSet
, M
, Loc
, Dtor
, LK_Generic
);
1908 FactEntry::SourceKind Source
=
1909 !Scp
.shouldIgnore() ? FactEntry::Managed
: FactEntry::Acquired
;
1910 for (const auto &M
: ExclusiveLocksToAdd
)
1911 Analyzer
->addLock(FSet
, std::make_unique
<LockableFactEntry
>(M
, LK_Exclusive
,
1913 for (const auto &M
: SharedLocksToAdd
)
1915 FSet
, std::make_unique
<LockableFactEntry
>(M
, LK_Shared
, Loc
, Source
));
1917 if (!Scp
.shouldIgnore()) {
1918 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1919 auto ScopedEntry
= std::make_unique
<ScopedLockableFactEntry
>(Scp
, Loc
);
1920 for (const auto &M
: ExclusiveLocksToAdd
)
1921 ScopedEntry
->addLock(M
);
1922 for (const auto &M
: SharedLocksToAdd
)
1923 ScopedEntry
->addLock(M
);
1924 for (const auto &M
: ScopedReqsAndExcludes
)
1925 ScopedEntry
->addLock(M
);
1926 for (const auto &M
: ExclusiveLocksToRemove
)
1927 ScopedEntry
->addExclusiveUnlock(M
);
1928 for (const auto &M
: SharedLocksToRemove
)
1929 ScopedEntry
->addSharedUnlock(M
);
1930 Analyzer
->addLock(FSet
, std::move(ScopedEntry
));
1934 /// For unary operations which read and write a variable, we need to
1935 /// check whether we hold any required mutexes. Reads are checked in
1937 void BuildLockset::VisitUnaryOperator(const UnaryOperator
*UO
) {
1938 switch (UO
->getOpcode()) {
1943 checkAccess(UO
->getSubExpr(), AK_Written
);
1950 /// For binary operations which assign to a variable (writes), we need to check
1951 /// whether we hold any required mutexes.
1952 /// FIXME: Deal with non-primitive types.
1953 void BuildLockset::VisitBinaryOperator(const BinaryOperator
*BO
) {
1954 if (!BO
->isAssignmentOp())
1957 // adjust the context
1958 LVarCtx
= Analyzer
->LocalVarMap
.getNextContext(CtxIndex
, BO
, LVarCtx
);
1960 checkAccess(BO
->getLHS(), AK_Written
);
1963 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1964 /// need to ensure we hold any required mutexes.
1965 /// FIXME: Deal with non-primitive types.
1966 void BuildLockset::VisitCastExpr(const CastExpr
*CE
) {
1967 if (CE
->getCastKind() != CK_LValueToRValue
)
1969 checkAccess(CE
->getSubExpr(), AK_Read
);
1972 void BuildLockset::examineArguments(const FunctionDecl
*FD
,
1973 CallExpr::const_arg_iterator ArgBegin
,
1974 CallExpr::const_arg_iterator ArgEnd
,
1975 bool SkipFirstParam
) {
1976 // Currently we can't do anything if we don't know the function declaration.
1980 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
1981 // only turns off checking within the body of a function, but we also
1982 // use it to turn off checking in arguments to the function. This
1983 // could result in some false negatives, but the alternative is to
1984 // create yet another attribute.
1985 if (FD
->hasAttr
<NoThreadSafetyAnalysisAttr
>())
1988 const ArrayRef
<ParmVarDecl
*> Params
= FD
->parameters();
1989 auto Param
= Params
.begin();
1993 // There can be default arguments, so we stop when one iterator is at end().
1994 for (auto Arg
= ArgBegin
; Param
!= Params
.end() && Arg
!= ArgEnd
;
1996 QualType Qt
= (*Param
)->getType();
1997 if (Qt
->isReferenceType())
1998 checkAccess(*Arg
, AK_Read
, POK_PassByRef
);
2002 void BuildLockset::VisitCallExpr(const CallExpr
*Exp
) {
2003 if (const auto *CE
= dyn_cast
<CXXMemberCallExpr
>(Exp
)) {
2004 const auto *ME
= dyn_cast
<MemberExpr
>(CE
->getCallee());
2005 // ME can be null when calling a method pointer
2006 const CXXMethodDecl
*MD
= CE
->getMethodDecl();
2009 if (ME
->isArrow()) {
2010 // Should perhaps be AK_Written if !MD->isConst().
2011 checkPtAccess(CE
->getImplicitObjectArgument(), AK_Read
);
2013 // Should perhaps be AK_Written if !MD->isConst().
2014 checkAccess(CE
->getImplicitObjectArgument(), AK_Read
);
2018 examineArguments(CE
->getDirectCallee(), CE
->arg_begin(), CE
->arg_end());
2019 } else if (const auto *OE
= dyn_cast
<CXXOperatorCallExpr
>(Exp
)) {
2020 OverloadedOperatorKind OEop
= OE
->getOperator();
2027 case OO_PercentEqual
:
2031 case OO_LessLessEqual
:
2032 case OO_GreaterGreaterEqual
:
2033 checkAccess(OE
->getArg(1), AK_Read
);
2037 checkAccess(OE
->getArg(0), AK_Written
);
2043 if (!(OEop
== OO_Star
&& OE
->getNumArgs() > 1)) {
2044 // Grrr. operator* can be multiplication...
2045 checkPtAccess(OE
->getArg(0), AK_Read
);
2049 // TODO: get rid of this, and rely on pass-by-ref instead.
2050 const Expr
*Obj
= OE
->getArg(0);
2051 checkAccess(Obj
, AK_Read
);
2052 // Check the remaining arguments. For method operators, the first
2053 // argument is the implicit self argument, and doesn't appear in the
2054 // FunctionDecl, but for non-methods it does.
2055 const FunctionDecl
*FD
= OE
->getDirectCallee();
2056 examineArguments(FD
, std::next(OE
->arg_begin()), OE
->arg_end(),
2057 /*SkipFirstParam*/ !isa
<CXXMethodDecl
>(FD
));
2062 examineArguments(Exp
->getDirectCallee(), Exp
->arg_begin(), Exp
->arg_end());
2065 auto *D
= dyn_cast_or_null
<NamedDecl
>(Exp
->getCalleeDecl());
2066 if(!D
|| !D
->hasAttrs())
2071 void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr
*Exp
) {
2072 const CXXConstructorDecl
*D
= Exp
->getConstructor();
2073 if (D
&& D
->isCopyConstructor()) {
2074 const Expr
* Source
= Exp
->getArg(0);
2075 checkAccess(Source
, AK_Read
);
2077 examineArguments(D
, Exp
->arg_begin(), Exp
->arg_end());
2079 if (D
&& D
->hasAttrs())
2083 static const Expr
*UnpackConstruction(const Expr
*E
) {
2084 if (auto *CE
= dyn_cast
<CastExpr
>(E
))
2085 if (CE
->getCastKind() == CK_NoOp
)
2086 E
= CE
->getSubExpr()->IgnoreParens();
2087 if (auto *CE
= dyn_cast
<CastExpr
>(E
))
2088 if (CE
->getCastKind() == CK_ConstructorConversion
||
2089 CE
->getCastKind() == CK_UserDefinedConversion
)
2090 E
= CE
->getSubExpr();
2091 if (auto *BTE
= dyn_cast
<CXXBindTemporaryExpr
>(E
))
2092 E
= BTE
->getSubExpr();
2096 void BuildLockset::VisitDeclStmt(const DeclStmt
*S
) {
2097 // adjust the context
2098 LVarCtx
= Analyzer
->LocalVarMap
.getNextContext(CtxIndex
, S
, LVarCtx
);
2100 for (auto *D
: S
->getDeclGroup()) {
2101 if (auto *VD
= dyn_cast_or_null
<VarDecl
>(D
)) {
2102 const Expr
*E
= VD
->getInit();
2105 E
= E
->IgnoreParens();
2107 // handle constructors that involve temporaries
2108 if (auto *EWC
= dyn_cast
<ExprWithCleanups
>(E
))
2109 E
= EWC
->getSubExpr()->IgnoreParens();
2110 E
= UnpackConstruction(E
);
2112 if (auto Object
= ConstructedObjects
.find(E
);
2113 Object
!= ConstructedObjects
.end()) {
2114 Object
->second
->setClangDecl(VD
);
2115 ConstructedObjects
.erase(Object
);
2121 void BuildLockset::VisitMaterializeTemporaryExpr(
2122 const MaterializeTemporaryExpr
*Exp
) {
2123 if (const ValueDecl
*ExtD
= Exp
->getExtendingDecl()) {
2125 ConstructedObjects
.find(UnpackConstruction(Exp
->getSubExpr()));
2126 Object
!= ConstructedObjects
.end()) {
2127 Object
->second
->setClangDecl(ExtD
);
2128 ConstructedObjects
.erase(Object
);
2133 /// Given two facts merging on a join point, possibly warn and decide whether to
2134 /// keep or replace.
2136 /// \param CanModify Whether we can replace \p A by \p B.
2137 /// \return false if we should keep \p A, true if we should take \p B.
2138 bool ThreadSafetyAnalyzer::join(const FactEntry
&A
, const FactEntry
&B
,
2140 if (A
.kind() != B
.kind()) {
2141 // For managed capabilities, the destructor should unlock in the right mode
2142 // anyway. For asserted capabilities no unlocking is needed.
2143 if ((A
.managed() || A
.asserted()) && (B
.managed() || B
.asserted())) {
2144 // The shared capability subsumes the exclusive capability, if possible.
2145 bool ShouldTakeB
= B
.kind() == LK_Shared
;
2146 if (CanModify
|| !ShouldTakeB
)
2149 Handler
.handleExclusiveAndShared(B
.getKind(), B
.toString(), B
.loc(),
2151 // Take the exclusive capability to reduce further warnings.
2152 return CanModify
&& B
.kind() == LK_Exclusive
;
2154 // The non-asserted capability is the one we want to track.
2155 return CanModify
&& A
.asserted() && !B
.asserted();
2159 /// Compute the intersection of two locksets and issue warnings for any
2160 /// locks in the symmetric difference.
2162 /// This function is used at a merge point in the CFG when comparing the lockset
2163 /// of each branch being merged. For example, given the following sequence:
2164 /// A; if () then B; else C; D; we need to check that the lockset after B and C
2165 /// are the same. In the event of a difference, we use the intersection of these
2166 /// two locksets at the start of D.
2168 /// \param EntrySet A lockset for entry into a (possibly new) block.
2169 /// \param ExitSet The lockset on exiting a preceding block.
2170 /// \param JoinLoc The location of the join point for error reporting
2171 /// \param EntryLEK The warning if a mutex is missing from \p EntrySet.
2172 /// \param ExitLEK The warning if a mutex is missing from \p ExitSet.
2173 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet
&EntrySet
,
2174 const FactSet
&ExitSet
,
2175 SourceLocation JoinLoc
,
2176 LockErrorKind EntryLEK
,
2177 LockErrorKind ExitLEK
) {
2178 FactSet EntrySetOrig
= EntrySet
;
2180 // Find locks in ExitSet that conflict or are not in EntrySet, and warn.
2181 for (const auto &Fact
: ExitSet
) {
2182 const FactEntry
&ExitFact
= FactMan
[Fact
];
2184 FactSet::iterator EntryIt
= EntrySet
.findLockIter(FactMan
, ExitFact
);
2185 if (EntryIt
!= EntrySet
.end()) {
2186 if (join(FactMan
[*EntryIt
], ExitFact
,
2187 EntryLEK
!= LEK_LockedSomeLoopIterations
))
2189 } else if (!ExitFact
.managed()) {
2190 ExitFact
.handleRemovalFromIntersection(ExitSet
, FactMan
, JoinLoc
,
2195 // Find locks in EntrySet that are not in ExitSet, and remove them.
2196 for (const auto &Fact
: EntrySetOrig
) {
2197 const FactEntry
*EntryFact
= &FactMan
[Fact
];
2198 const FactEntry
*ExitFact
= ExitSet
.findLock(FactMan
, *EntryFact
);
2201 if (!EntryFact
->managed() || ExitLEK
== LEK_LockedSomeLoopIterations
)
2202 EntryFact
->handleRemovalFromIntersection(EntrySetOrig
, FactMan
, JoinLoc
,
2204 if (ExitLEK
== LEK_LockedSomePredecessors
)
2205 EntrySet
.removeLock(FactMan
, *EntryFact
);
2210 // Return true if block B never continues to its successors.
2211 static bool neverReturns(const CFGBlock
*B
) {
2212 if (B
->hasNoReturnElement())
2217 CFGElement Last
= B
->back();
2218 if (std::optional
<CFGStmt
> S
= Last
.getAs
<CFGStmt
>()) {
2219 if (isa
<CXXThrowExpr
>(S
->getStmt()))
2225 /// Check a function's CFG for thread-safety violations.
2227 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2228 /// at the end of each block, and issue warnings for thread safety violations.
2229 /// Each block in the CFG is traversed exactly once.
2230 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext
&AC
) {
2231 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2232 // For now, we just use the walker to set things up.
2233 threadSafety::CFGWalker walker
;
2234 if (!walker
.init(AC
))
2237 // AC.dumpCFG(true);
2238 // threadSafety::printSCFG(walker);
2240 CFG
*CFGraph
= walker
.getGraph();
2241 const NamedDecl
*D
= walker
.getDecl();
2242 const auto *CurrentFunction
= dyn_cast
<FunctionDecl
>(D
);
2243 CurrentMethod
= dyn_cast
<CXXMethodDecl
>(D
);
2245 if (D
->hasAttr
<NoThreadSafetyAnalysisAttr
>())
2248 // FIXME: Do something a bit more intelligent inside constructor and
2249 // destructor code. Constructors and destructors must assume unique access
2250 // to 'this', so checks on member variable access is disabled, but we should
2251 // still enable checks on other objects.
2252 if (isa
<CXXConstructorDecl
>(D
))
2253 return; // Don't check inside constructors.
2254 if (isa
<CXXDestructorDecl
>(D
))
2255 return; // Don't check inside destructors.
2257 Handler
.enterFunction(CurrentFunction
);
2259 BlockInfo
.resize(CFGraph
->getNumBlockIDs(),
2260 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap
));
2262 // We need to explore the CFG via a "topological" ordering.
2263 // That way, we will be guaranteed to have information about required
2264 // predecessor locksets when exploring a new block.
2265 const PostOrderCFGView
*SortedGraph
= walker
.getSortedGraph();
2266 PostOrderCFGView::CFGBlockSet
VisitedBlocks(CFGraph
);
2268 // Mark entry block as reachable
2269 BlockInfo
[CFGraph
->getEntry().getBlockID()].Reachable
= true;
2271 // Compute SSA names for local variables
2272 LocalVarMap
.traverseCFG(CFGraph
, SortedGraph
, BlockInfo
);
2274 // Fill in source locations for all CFGBlocks.
2275 findBlockLocations(CFGraph
, SortedGraph
, BlockInfo
);
2277 CapExprSet ExclusiveLocksAcquired
;
2278 CapExprSet SharedLocksAcquired
;
2279 CapExprSet LocksReleased
;
2281 // Add locks from exclusive_locks_required and shared_locks_required
2282 // to initial lockset. Also turn off checking for lock and unlock functions.
2283 // FIXME: is there a more intelligent way to check lock/unlock functions?
2284 if (!SortedGraph
->empty() && D
->hasAttrs()) {
2285 const CFGBlock
*FirstBlock
= *SortedGraph
->begin();
2286 FactSet
&InitialLockset
= BlockInfo
[FirstBlock
->getBlockID()].EntrySet
;
2288 CapExprSet ExclusiveLocksToAdd
;
2289 CapExprSet SharedLocksToAdd
;
2291 SourceLocation Loc
= D
->getLocation();
2292 for (const auto *Attr
: D
->attrs()) {
2293 Loc
= Attr
->getLocation();
2294 if (const auto *A
= dyn_cast
<RequiresCapabilityAttr
>(Attr
)) {
2295 getMutexIDs(A
->isShared() ? SharedLocksToAdd
: ExclusiveLocksToAdd
, A
,
2297 } else if (const auto *A
= dyn_cast
<ReleaseCapabilityAttr
>(Attr
)) {
2298 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2299 // We must ignore such methods.
2300 if (A
->args_size() == 0)
2302 getMutexIDs(A
->isShared() ? SharedLocksToAdd
: ExclusiveLocksToAdd
, A
,
2304 getMutexIDs(LocksReleased
, A
, nullptr, D
);
2305 } else if (const auto *A
= dyn_cast
<AcquireCapabilityAttr
>(Attr
)) {
2306 if (A
->args_size() == 0)
2308 getMutexIDs(A
->isShared() ? SharedLocksAcquired
2309 : ExclusiveLocksAcquired
,
2311 } else if (isa
<ExclusiveTrylockFunctionAttr
>(Attr
)) {
2312 // Don't try to check trylock functions for now.
2314 } else if (isa
<SharedTrylockFunctionAttr
>(Attr
)) {
2315 // Don't try to check trylock functions for now.
2317 } else if (isa
<TryAcquireCapabilityAttr
>(Attr
)) {
2318 // Don't try to check trylock functions for now.
2323 // FIXME -- Loc can be wrong here.
2324 for (const auto &Mu
: ExclusiveLocksToAdd
) {
2325 auto Entry
= std::make_unique
<LockableFactEntry
>(Mu
, LK_Exclusive
, Loc
,
2326 FactEntry::Declared
);
2327 addLock(InitialLockset
, std::move(Entry
), true);
2329 for (const auto &Mu
: SharedLocksToAdd
) {
2330 auto Entry
= std::make_unique
<LockableFactEntry
>(Mu
, LK_Shared
, Loc
,
2331 FactEntry::Declared
);
2332 addLock(InitialLockset
, std::move(Entry
), true);
2336 for (const auto *CurrBlock
: *SortedGraph
) {
2337 unsigned CurrBlockID
= CurrBlock
->getBlockID();
2338 CFGBlockInfo
*CurrBlockInfo
= &BlockInfo
[CurrBlockID
];
2340 // Use the default initial lockset in case there are no predecessors.
2341 VisitedBlocks
.insert(CurrBlock
);
2343 // Iterate through the predecessor blocks and warn if the lockset for all
2344 // predecessors is not the same. We take the entry lockset of the current
2345 // block to be the intersection of all previous locksets.
2346 // FIXME: By keeping the intersection, we may output more errors in future
2347 // for a lock which is not in the intersection, but was in the union. We
2348 // may want to also keep the union in future. As an example, let's say
2349 // the intersection contains Mutex L, and the union contains L and M.
2350 // Later we unlock M. At this point, we would output an error because we
2351 // never locked M; although the real error is probably that we forgot to
2352 // lock M on all code paths. Conversely, let's say that later we lock M.
2353 // In this case, we should compare against the intersection instead of the
2354 // union because the real error is probably that we forgot to unlock M on
2356 bool LocksetInitialized
= false;
2357 for (CFGBlock::const_pred_iterator PI
= CurrBlock
->pred_begin(),
2358 PE
= CurrBlock
->pred_end(); PI
!= PE
; ++PI
) {
2359 // if *PI -> CurrBlock is a back edge
2360 if (*PI
== nullptr || !VisitedBlocks
.alreadySet(*PI
))
2363 unsigned PrevBlockID
= (*PI
)->getBlockID();
2364 CFGBlockInfo
*PrevBlockInfo
= &BlockInfo
[PrevBlockID
];
2366 // Ignore edges from blocks that can't return.
2367 if (neverReturns(*PI
) || !PrevBlockInfo
->Reachable
)
2370 // Okay, we can reach this block from the entry.
2371 CurrBlockInfo
->Reachable
= true;
2373 FactSet PrevLockset
;
2374 getEdgeLockset(PrevLockset
, PrevBlockInfo
->ExitSet
, *PI
, CurrBlock
);
2376 if (!LocksetInitialized
) {
2377 CurrBlockInfo
->EntrySet
= PrevLockset
;
2378 LocksetInitialized
= true;
2380 // Surprisingly 'continue' doesn't always produce back edges, because
2381 // the CFG has empty "transition" blocks where they meet with the end
2382 // of the regular loop body. We still want to diagnose them as loop.
2384 CurrBlockInfo
->EntrySet
, PrevLockset
, CurrBlockInfo
->EntryLoc
,
2385 isa_and_nonnull
<ContinueStmt
>((*PI
)->getTerminatorStmt())
2386 ? LEK_LockedSomeLoopIterations
2387 : LEK_LockedSomePredecessors
);
2391 // Skip rest of block if it's not reachable.
2392 if (!CurrBlockInfo
->Reachable
)
2395 BuildLockset
LocksetBuilder(this, *CurrBlockInfo
);
2397 // Visit all the statements in the basic block.
2398 for (const auto &BI
: *CurrBlock
) {
2399 switch (BI
.getKind()) {
2400 case CFGElement::Statement
: {
2401 CFGStmt CS
= BI
.castAs
<CFGStmt
>();
2402 LocksetBuilder
.Visit(CS
.getStmt());
2405 // Ignore BaseDtor and MemberDtor for now.
2406 case CFGElement::AutomaticObjectDtor
: {
2407 CFGAutomaticObjDtor AD
= BI
.castAs
<CFGAutomaticObjDtor
>();
2408 const auto *DD
= AD
.getDestructorDecl(AC
.getASTContext());
2409 if (!DD
->hasAttrs())
2412 LocksetBuilder
.handleCall(nullptr, DD
,
2413 SxBuilder
.createVariable(AD
.getVarDecl()),
2414 AD
.getTriggerStmt()->getEndLoc());
2417 case CFGElement::TemporaryDtor
: {
2418 auto TD
= BI
.castAs
<CFGTemporaryDtor
>();
2420 // Clean up constructed object even if there are no attributes to
2421 // keep the number of objects in limbo as small as possible.
2422 if (auto Object
= LocksetBuilder
.ConstructedObjects
.find(
2423 TD
.getBindTemporaryExpr()->getSubExpr());
2424 Object
!= LocksetBuilder
.ConstructedObjects
.end()) {
2425 const auto *DD
= TD
.getDestructorDecl(AC
.getASTContext());
2427 // TODO: the location here isn't quite correct.
2428 LocksetBuilder
.handleCall(nullptr, DD
, Object
->second
,
2429 TD
.getBindTemporaryExpr()->getEndLoc());
2430 LocksetBuilder
.ConstructedObjects
.erase(Object
);
2438 CurrBlockInfo
->ExitSet
= LocksetBuilder
.FSet
;
2440 // For every back edge from CurrBlock (the end of the loop) to another block
2441 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2442 // the one held at the beginning of FirstLoopBlock. We can look up the
2443 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2444 for (CFGBlock::const_succ_iterator SI
= CurrBlock
->succ_begin(),
2445 SE
= CurrBlock
->succ_end(); SI
!= SE
; ++SI
) {
2446 // if CurrBlock -> *SI is *not* a back edge
2447 if (*SI
== nullptr || !VisitedBlocks
.alreadySet(*SI
))
2450 CFGBlock
*FirstLoopBlock
= *SI
;
2451 CFGBlockInfo
*PreLoop
= &BlockInfo
[FirstLoopBlock
->getBlockID()];
2452 CFGBlockInfo
*LoopEnd
= &BlockInfo
[CurrBlockID
];
2453 intersectAndWarn(PreLoop
->EntrySet
, LoopEnd
->ExitSet
, PreLoop
->EntryLoc
,
2454 LEK_LockedSomeLoopIterations
);
2458 CFGBlockInfo
*Initial
= &BlockInfo
[CFGraph
->getEntry().getBlockID()];
2459 CFGBlockInfo
*Final
= &BlockInfo
[CFGraph
->getExit().getBlockID()];
2461 // Skip the final check if the exit block is unreachable.
2462 if (!Final
->Reachable
)
2465 // By default, we expect all locks held on entry to be held on exit.
2466 FactSet ExpectedExitSet
= Initial
->EntrySet
;
2468 // Adjust the expected exit set by adding or removing locks, as declared
2469 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2470 // issue the appropriate warning.
2471 // FIXME: the location here is not quite right.
2472 for (const auto &Lock
: ExclusiveLocksAcquired
)
2473 ExpectedExitSet
.addLock(FactMan
, std::make_unique
<LockableFactEntry
>(
2474 Lock
, LK_Exclusive
, D
->getLocation()));
2475 for (const auto &Lock
: SharedLocksAcquired
)
2476 ExpectedExitSet
.addLock(FactMan
, std::make_unique
<LockableFactEntry
>(
2477 Lock
, LK_Shared
, D
->getLocation()));
2478 for (const auto &Lock
: LocksReleased
)
2479 ExpectedExitSet
.removeLock(FactMan
, Lock
);
2481 // FIXME: Should we call this function for all blocks which exit the function?
2482 intersectAndWarn(ExpectedExitSet
, Final
->ExitSet
, Final
->ExitLoc
,
2483 LEK_LockedAtEndOfFunction
, LEK_NotLockedAtEndOfFunction
);
2485 Handler
.leaveFunction(CurrentFunction
);
2488 /// Check a function's CFG for thread-safety violations.
2490 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2491 /// at the end of each block, and issue warnings for thread safety violations.
2492 /// Each block in the CFG is traversed exactly once.
2493 void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext
&AC
,
2494 ThreadSafetyHandler
&Handler
,
2497 *BSet
= new BeforeSet
;
2498 ThreadSafetyAnalyzer
Analyzer(Handler
, *BSet
);
2499 Analyzer
.runAnalysis(AC
);
2502 void threadSafety::threadSafetyCleanup(BeforeSet
*Cache
) { delete Cache
; }
2504 /// Helper function that returns a LockKind required for the given level
2506 LockKind
threadSafety::getLockKindFromAccessKind(AccessKind AK
) {
2511 return LK_Exclusive
;
2513 llvm_unreachable("Unknown AccessKind");