blob: be1f8b8eebe39bfb905530f9587b4201c3277a0b [file] [log] [blame]
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001//===- ThreadSafety.cpp ---------------------------------------------------===//
Caitlin Sadowski33208342011-09-09 16:11:56 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000013// See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
Aaron Ballmanfcd5b7e2013-06-26 19:17:19 +000014// for more information.
Caitlin Sadowski33208342011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
Mehdi Amini9670f842016-07-18 19:02:11 +000018#include "clang/Analysis/Analyses/ThreadSafety.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000020#include "clang/AST/Decl.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000021#include "clang/AST/DeclCXX.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000022#include "clang/AST/DeclGroup.h"
23#include "clang/AST/Expr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000024#include "clang/AST/ExprCXX.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000025#include "clang/AST/OperationKinds.h"
26#include "clang/AST/Stmt.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000027#include "clang/AST/StmtVisitor.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000028#include "clang/AST/Type.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000030#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000031#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000032#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000033#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
George Karpenkov50657f62017-09-06 21:45:03 +000034#include "clang/Analysis/AnalysisDeclContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Analysis/CFG.h"
Aaron Puchert7146b002018-10-03 11:58:19 +000036#include "clang/Basic/Builtins.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000037#include "clang/Basic/LLVM.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000038#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "clang/Basic/SourceLocation.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000040#include "clang/Basic/Specifiers.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/DenseMap.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000043#include "llvm/ADT/ImmutableMap.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000044#include "llvm/ADT/Optional.h"
45#include "llvm/ADT/STLExtras.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000046#include "llvm/ADT/SmallVector.h"
47#include "llvm/ADT/StringRef.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000048#include "llvm/Support/Allocator.h"
49#include "llvm/Support/Casting.h"
50#include "llvm/Support/ErrorHandling.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000051#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000052#include <algorithm>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000053#include <cassert>
54#include <functional>
55#include <iterator>
56#include <memory>
57#include <string>
58#include <type_traits>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000059#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000060#include <vector>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000061
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000062using namespace clang;
63using namespace threadSafety;
Caitlin Sadowski33208342011-09-09 16:11:56 +000064
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000065// Key method definition
Eugene Zelenkobbe25312018-03-16 21:22:42 +000066ThreadSafetyHandler::~ThreadSafetyHandler() = default;
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000067
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000068/// Issue a warning about an invalid lock expression
69static void warnInvalidLock(ThreadSafetyHandler &Handler,
70 const Expr *MutexExp, const NamedDecl *D,
71 const Expr *DeclExp, StringRef Kind) {
72 SourceLocation Loc;
73 if (DeclExp)
74 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000075
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000076 // FIXME: add a note about the attribute location in MutexExp or D
77 if (Loc.isValid())
78 Handler.handleInvalidLockExp(Kind, Loc);
79}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000080
Eugene Zelenkobbe25312018-03-16 21:22:42 +000081namespace {
82
Aaron Puchert78619432018-08-22 21:06:04 +000083/// A set of CapabilityExpr objects, which are compiled from thread safety
84/// attributes on a function.
DeLesley Hutchins42665222014-08-04 16:10:59 +000085class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000086public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000088 void push_back_nodup(const CapabilityExpr &CapE) {
89 iterator It = std::find_if(begin(), end(),
90 [=](const CapabilityExpr &CapE2) {
91 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000092 });
93 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +000094 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000095 }
96};
97
Ed Schoutenca988742014-09-03 06:00:11 +000098class FactManager;
99class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000101/// This is a helper class that stores a fact that is known at a
DeLesley Hutchins42665222014-08-04 16:10:59 +0000102/// particular point in program execution. Currently, a fact is a capability,
103/// along with additional information, such as where it was acquired, whether
104/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +0000105///
Aaron Ballman1b587592018-07-26 13:03:16 +0000106/// FIXME: this analysis does not currently support re-entrant locking.
DeLesley Hutchins42665222014-08-04 16:10:59 +0000107class FactEntry : public CapabilityExpr {
108private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000109 /// Exclusive or shared.
110 LockKind LKind;
111
112 /// Where it was acquired.
113 SourceLocation AcquireLoc;
114
115 /// True if the lock was asserted.
116 bool Asserted;
117
118 /// True if the lock was declared.
119 bool Declared;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000120
DeLesley Hutchins42665222014-08-04 16:10:59 +0000121public:
122 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000123 bool Asrt, bool Declrd = false)
124 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
125 Declared(Declrd) {}
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000126 virtual ~FactEntry() = default;
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000127
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000128 LockKind kind() const { return LKind; }
129 SourceLocation loc() const { return AcquireLoc; }
130 bool asserted() const { return Asserted; }
131 bool declared() const { return Declared; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000132
133 void setDeclared(bool D) { Declared = D; }
Ed Schoutenca988742014-09-03 06:00:11 +0000134
135 virtual void
136 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
137 SourceLocation JoinLoc, LockErrorKind LEK,
138 ThreadSafetyHandler &Handler) const = 0;
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000139 virtual void handleLock(FactSet &FSet, FactManager &FactMan,
140 const FactEntry &entry, ThreadSafetyHandler &Handler,
141 StringRef DiagKind) const = 0;
Ed Schoutenca988742014-09-03 06:00:11 +0000142 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
143 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
144 bool FullyRemove, ThreadSafetyHandler &Handler,
145 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000146
DeLesley Hutchins42665222014-08-04 16:10:59 +0000147 // Return true if LKind >= LK, where exclusive > shared
Aaron Puchert969f32d2018-09-21 23:08:30 +0000148 bool isAtLeast(LockKind LK) const {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000149 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000150 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000151};
152
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000153using FactID = unsigned short;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000154
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000155/// FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000156/// the analysis of a single routine.
157class FactManager {
158private:
Aaron Puchert969f32d2018-09-21 23:08:30 +0000159 std::vector<std::unique_ptr<const FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000160
161public:
Ed Schoutenca988742014-09-03 06:00:11 +0000162 FactID newFact(std::unique_ptr<FactEntry> Entry) {
163 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000164 return static_cast<unsigned short>(Facts.size() - 1);
165 }
166
Ed Schoutenca988742014-09-03 06:00:11 +0000167 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000168};
169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000170/// A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000171/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000172/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000173/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000174/// locks, so we can get away with doing a linear search for lookup. Note
175/// that a hashtable or map is inappropriate in this case, because lookups
176/// may involve partial pattern matches, rather than exact matches.
177class FactSet {
178private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000179 using FactVec = SmallVector<FactID, 4>;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000180
181 FactVec FactIDs;
182
183public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000184 using iterator = FactVec::iterator;
185 using const_iterator = FactVec::const_iterator;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000186
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000187 iterator begin() { return FactIDs.begin(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000188 const_iterator begin() const { return FactIDs.begin(); }
189
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000190 iterator end() { return FactIDs.end(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000191 const_iterator end() const { return FactIDs.end(); }
192
193 bool isEmpty() const { return FactIDs.size() == 0; }
194
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000195 // Return true if the set contains only negative facts
196 bool isEmpty(FactManager &FactMan) const {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000197 for (const auto FID : *this) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000198 if (!FactMan[FID].negative())
199 return false;
200 }
201 return true;
202 }
203
204 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
205
Ed Schoutenca988742014-09-03 06:00:11 +0000206 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
207 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000208 FactIDs.push_back(F);
209 return F;
210 }
211
DeLesley Hutchins42665222014-08-04 16:10:59 +0000212 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000213 unsigned n = FactIDs.size();
214 if (n == 0)
215 return false;
216
217 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000218 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000219 FactIDs[i] = FactIDs[n-1];
220 FactIDs.pop_back();
221 return true;
222 }
223 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000224 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000225 FactIDs.pop_back();
226 return true;
227 }
228 return false;
229 }
230
DeLesley Hutchins42665222014-08-04 16:10:59 +0000231 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000232 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000233 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000234 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000235 }
236
Aaron Puchert969f32d2018-09-21 23:08:30 +0000237 const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000238 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000239 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000240 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000241 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000242 }
243
Aaron Puchert969f32d2018-09-21 23:08:30 +0000244 const FactEntry *findLockUniv(FactManager &FM,
245 const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000246 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000247 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000248 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000249 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000250 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000251
Aaron Puchert969f32d2018-09-21 23:08:30 +0000252 const FactEntry *findPartialMatch(FactManager &FM,
253 const CapabilityExpr &CapE) const {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000254 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000255 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000256 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000257 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000258 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000259
260 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
261 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
262 return FM[ID].valueDecl() == Vd;
263 });
264 return I != end();
265 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000266};
267
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000268class ThreadSafetyAnalyzer;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000269
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000270} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000271
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000272namespace clang {
273namespace threadSafety {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000274
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000275class BeforeSet {
276private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000277 using BeforeVect = SmallVector<const ValueDecl *, 4>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000278
279 struct BeforeInfo {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000280 BeforeVect Vect;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000281 int Visited = 0;
282
283 BeforeInfo() = default;
284 BeforeInfo(BeforeInfo &&) = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000285 };
286
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000287 using BeforeMap =
288 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
289 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000290
291public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000292 BeforeSet() = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000293
294 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
295 ThreadSafetyAnalyzer& Analyzer);
296
Reid Kleckner19ff5602015-11-20 19:08:30 +0000297 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
298 ThreadSafetyAnalyzer &Analyzer);
299
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000300 void checkBeforeAfter(const ValueDecl* Vd,
301 const FactSet& FSet,
302 ThreadSafetyAnalyzer& Analyzer,
303 SourceLocation Loc, StringRef CapKind);
304
305private:
306 BeforeMap BMap;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000307 CycleMap CycMap;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000308};
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000309
310} // namespace threadSafety
311} // namespace clang
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000312
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000313namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000314
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000315class LocalVariableMap;
316
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000317using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
318
Richard Smith92286672012-02-03 04:45:26 +0000319/// A side (entry or exit) of a CFG node.
320enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000321
322/// CFGBlockInfo is a struct which contains all the information that is
323/// maintained for each block in the CFG. See LocalVariableMap for more
324/// information about the contexts.
325struct CFGBlockInfo {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000326 // Lockset held at entry to block
327 FactSet EntrySet;
328
329 // Lockset held at exit from block
330 FactSet ExitSet;
331
332 // Context held at entry to block
333 LocalVarContext EntryContext;
334
335 // Context held at exit from block
336 LocalVarContext ExitContext;
337
338 // Location of first statement in block
339 SourceLocation EntryLoc;
340
341 // Location of last statement in block.
342 SourceLocation ExitLoc;
343
344 // Used to replay contexts later
345 unsigned EntryIndex;
346
347 // Is this block reachable?
348 bool Reachable = false;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000349
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000350 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000351 return Side == CBS_Entry ? EntrySet : ExitSet;
352 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000353
Richard Smith92286672012-02-03 04:45:26 +0000354 SourceLocation getLocation(CFGBlockSide Side) const {
355 return Side == CBS_Entry ? EntryLoc : ExitLoc;
356 }
357
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000358private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000359 CFGBlockInfo(LocalVarContext EmptyCtx)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000360 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000361
362public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000363 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000364};
365
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000366// A LocalVariableMap maintains a map from local variables to their currently
367// valid definitions. It provides SSA-like functionality when traversing the
368// CFG. Like SSA, each definition or assignment to a variable is assigned a
369// unique name (an integer), which acts as the SSA name for that definition.
370// The total set of names is shared among all CFG basic blocks.
371// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
372// with their SSA-names. Instead, we compute a Context for each point in the
373// code, which maps local variables to the appropriate SSA-name. This map
374// changes with each assignment.
375//
376// The map is computed in a single pass over the CFG. Subsequent analyses can
377// then query the map to find the appropriate Context for a statement, and use
378// that Context to look up the definitions of variables.
379class LocalVariableMap {
380public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000381 using Context = LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000382
383 /// A VarDefinition consists of an expression, representing the value of the
384 /// variable, along with the context in which that expression should be
385 /// interpreted. A reference VarDefinition does not itself contain this
386 /// information, but instead contains a pointer to a previous VarDefinition.
387 struct VarDefinition {
388 public:
389 friend class LocalVariableMap;
390
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000391 // The original declaration for this variable.
392 const NamedDecl *Dec;
393
394 // The expression for this variable, OR
395 const Expr *Exp = nullptr;
396
397 // Reference to another VarDefinition
398 unsigned Ref = 0;
399
400 // The map with which Exp should be interpreted.
401 Context Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000402
403 bool isReference() { return !Exp; }
404
405 private:
406 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000407 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000408 : Dec(D), Exp(E), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000409
410 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000411 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000412 : Dec(D), Ref(R), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000413 };
414
415private:
416 Context::Factory ContextFactory;
417 std::vector<VarDefinition> VarDefinitions;
418 std::vector<unsigned> CtxIndices;
Aaron Puchertcd37c092018-08-23 21:53:04 +0000419 std::vector<std::pair<const Stmt *, Context>> SavedContexts;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000420
421public:
422 LocalVariableMap() {
423 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000424 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000425 }
426
427 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000428 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000429 const unsigned *i = Ctx.lookup(D);
430 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000431 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000432 assert(*i < VarDefinitions.size());
433 return &VarDefinitions[*i];
434 }
435
436 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000437 /// NULL if the expression is not statically known. If successful, also
438 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000439 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000440 const unsigned *P = Ctx.lookup(D);
441 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000442 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000443
444 unsigned i = *P;
445 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000446 if (VarDefinitions[i].Exp) {
447 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000448 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000449 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000450 i = VarDefinitions[i].Ref;
451 }
Craig Topper25542942014-05-20 04:30:07 +0000452 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000453 }
454
455 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
456
457 /// Return the next context after processing S. This function is used by
458 /// clients of the class to get the appropriate context when traversing the
459 /// CFG. It must be called for every assignment or DeclStmt.
Aaron Puchertcd37c092018-08-23 21:53:04 +0000460 Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000461 if (SavedContexts[CtxIndex+1].first == S) {
462 CtxIndex++;
463 Context Result = SavedContexts[CtxIndex].second;
464 return Result;
465 }
466 return C;
467 }
468
469 void dumpVarDefinitionName(unsigned i) {
470 if (i == 0) {
471 llvm::errs() << "Undefined";
472 return;
473 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000474 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000475 if (!Dec) {
476 llvm::errs() << "<<NULL>>";
477 return;
478 }
479 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000480 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000481 }
482
483 /// Dumps an ASCII representation of the variable map to llvm::errs()
484 void dump() {
485 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000486 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000487 unsigned Ref = VarDefinitions[i].Ref;
488
489 dumpVarDefinitionName(i);
490 llvm::errs() << " = ";
491 if (Exp) Exp->dump();
492 else {
493 dumpVarDefinitionName(Ref);
494 llvm::errs() << "\n";
495 }
496 }
497 }
498
499 /// Dumps an ASCII representation of a Context to llvm::errs()
500 void dumpContext(Context C) {
501 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000502 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000503 D->printName(llvm::errs());
504 const unsigned *i = C.lookup(D);
505 llvm::errs() << " -> ";
506 dumpVarDefinitionName(*i);
507 llvm::errs() << "\n";
508 }
509 }
510
511 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000512 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
513 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000514
515protected:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000516 friend class VarMapBuilder;
517
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000518 // Get the current context index
519 unsigned getContextIndex() { return SavedContexts.size()-1; }
520
521 // Save the current context for later replay
Aaron Puchertcd37c092018-08-23 21:53:04 +0000522 void saveContext(const Stmt *S, Context C) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000523 SavedContexts.push_back(std::make_pair(S, C));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000524 }
525
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.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000528 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000529 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));
533 return NewCtx;
534 }
535
536 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000537 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000538 unsigned newID = VarDefinitions.size();
539 Context NewCtx = ContextFactory.add(Ctx, D, newID);
540 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
541 return NewCtx;
542 }
543
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.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000546 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000547 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));
552 return NewCtx;
553 }
554 return Ctx;
555 }
556
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.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000559 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000560 Context NewCtx = Ctx;
561 if (NewCtx.contains(D)) {
562 NewCtx = ContextFactory.remove(NewCtx, D);
563 NewCtx = ContextFactory.add(NewCtx, D, 0);
564 }
565 return NewCtx;
566 }
567
568 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000569 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000570 Context NewCtx = Ctx;
571 if (NewCtx.contains(D)) {
572 NewCtx = ContextFactory.remove(NewCtx, D);
573 }
574 return NewCtx;
575 }
576
577 Context intersectContexts(Context C1, Context C2);
578 Context createReferenceContext(Context C);
579 void intersectBackEdge(Context C1, Context C2);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000580};
581
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000582} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000583
584// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000585CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
586 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000587}
588
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000589namespace {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000590
591/// Visitor which builds a LocalVariableMap
Aaron Puchertcd37c092018-08-23 21:53:04 +0000592class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000593public:
594 LocalVariableMap* VMap;
595 LocalVariableMap::Context Ctx;
596
597 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000598 : VMap(VM), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000599
Aaron Puchertcd37c092018-08-23 21:53:04 +0000600 void VisitDeclStmt(const DeclStmt *S);
601 void VisitBinaryOperator(const BinaryOperator *BO);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000602};
603
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000604} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000605
606// Add new local variables to the variable map
Aaron Puchertcd37c092018-08-23 21:53:04 +0000607void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000608 bool modifiedCtx = false;
Aaron Puchertcd37c092018-08-23 21:53:04 +0000609 const DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000610 for (const auto *D : DGrp) {
611 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
612 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000613
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);
618 modifiedCtx = true;
619 }
620 }
621 }
622 if (modifiedCtx)
623 VMap->saveContext(S, Ctx);
624}
625
626// Update local variable definitions in variable map
Aaron Puchertcd37c092018-08-23 21:53:04 +0000627void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000628 if (!BO->isAssignmentOp())
629 return;
630
631 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
632
633 // Update the variable map and current context.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000634 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
635 const ValueDecl *VDec = DRE->getDecl();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000636 if (Ctx.lookup(VDec)) {
637 if (BO->getOpcode() == BO_Assign)
638 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
639 else
640 // FIXME -- handle compound assignment operators
641 Ctx = VMap->clearDefinition(VDec, Ctx);
642 VMap->saveContext(BO, Ctx);
643 }
644 }
645}
646
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000647// 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.
650LocalVariableMap::Context
651LocalVariableMap::intersectContexts(Context C1, Context C2) {
652 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000653 for (const auto &P : C1) {
654 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000655 const unsigned *i2 = C2.lookup(Dec);
656 if (!i2) // variable doesn't exist on second path
657 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000658 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000659 Result = clearDefinition(Dec, Result);
660 }
661 return Result;
662}
663
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.)
667LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
668 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000669 for (const auto &P : C)
670 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000671 return Result;
672}
673
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.
677void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000678 for (const auto &P : C1) {
679 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000680 VarDefinition *VDef = &VarDefinitions[i1];
681 assert(VDef->isReference());
682
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000683 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000684 if (!i2 || (*i2 != i1))
685 VDef->Ref = 0; // Mark this variable as undefined
686 }
687}
688
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000689// 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.
695//
696// At join points in the CFG, the set is computed as the intersection of
697// the incoming sets along each edge, E.g.
698//
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, ... }
705//
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).
712//
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
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000718// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000719// node was actually required.) E.g.
720//
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, ... }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000726void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000727 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000728 std::vector<CFGBlockInfo> &BlockInfo) {
729 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
730
731 CtxIndices.resize(CFGraph->getNumBlockIDs());
732
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000733 for (const auto *CurrBlock : *SortedGraph) {
Aaron Puchert88d85362018-09-22 21:56:16 +0000734 unsigned CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000735 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
736
737 VisitedBlocks.insert(CurrBlock);
738
739 // Calculate the entry context for the current block
740 bool HasBackEdges = false;
741 bool CtxInit = true;
742 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
743 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
744 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000745 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000746 HasBackEdges = true;
747 continue;
748 }
749
Aaron Puchert88d85362018-09-22 21:56:16 +0000750 unsigned PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000751 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
752
753 if (CtxInit) {
754 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
755 CtxInit = false;
756 }
757 else {
758 CurrBlockInfo->EntryContext =
759 intersectContexts(CurrBlockInfo->EntryContext,
760 PrevBlockInfo->ExitContext);
761 }
762 }
763
764 // Duplicate the context if we have back-edges, so we can call
765 // intersectBackEdges later.
766 if (HasBackEdges)
767 CurrBlockInfo->EntryContext =
768 createReferenceContext(CurrBlockInfo->EntryContext);
769
770 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000771 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000772 CurrBlockInfo->EntryIndex = getContextIndex();
773
774 // Visit all the statements in the basic block.
775 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000776 for (const auto &BI : *CurrBlock) {
777 switch (BI.getKind()) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000778 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000779 CFGStmt CS = BI.castAs<CFGStmt>();
Aaron Puchertcd37c092018-08-23 21:53:04 +0000780 VMapBuilder.Visit(CS.getStmt());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000781 break;
782 }
783 default:
784 break;
785 }
786 }
787 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
788
789 // Mark variables on back edges as "unknown" if they've been changed.
790 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
791 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
792 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000793 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000794 continue;
795
796 CFGBlock *FirstLoopBlock = *SI;
797 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
798 Context LoopEnd = CurrBlockInfo->ExitContext;
799 intersectBackEdge(LoopBegin, LoopEnd);
800 }
801 }
802
803 // Put an extra entry at the end of the indexed context array
804 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000805 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000806}
807
Richard Smith92286672012-02-03 04:45:26 +0000808/// Find the appropriate source locations to use when producing diagnostics for
809/// each block in the CFG.
810static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000811 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000812 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000813 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000814 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
815
816 // Find the source location of the last statement in the block, if the
817 // block is not empty.
818 if (const Stmt *S = CurrBlock->getTerminator()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000819 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000820 } else {
821 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
822 BE = CurrBlock->rend(); BI != BE; ++BI) {
823 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000824 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000825 CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000826 break;
827 }
828 }
829 }
830
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000831 if (CurrBlockInfo->ExitLoc.isValid()) {
Richard Smith92286672012-02-03 04:45:26 +0000832 // This block contains at least one statement. Find the source location
833 // of the first statement in the block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000834 for (const auto &BI : *CurrBlock) {
Richard Smith92286672012-02-03 04:45:26 +0000835 // FIXME: Handle other CFGElement kinds.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000836 if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000837 CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000838 break;
839 }
840 }
841 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
842 CurrBlock != &CFGraph->getExit()) {
843 // The block is empty, and has a single predecessor. Use its exit
844 // location.
845 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
846 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
847 }
848 }
849}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000850
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000851namespace {
852
Ed Schoutenca988742014-09-03 06:00:11 +0000853class LockableFactEntry : public FactEntry {
854private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000855 /// managed by ScopedLockable object
856 bool Managed;
Ed Schoutenca988742014-09-03 06:00:11 +0000857
858public:
859 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
860 bool Mng = false, bool Asrt = false)
861 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
862
863 void
864 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
865 SourceLocation JoinLoc, LockErrorKind LEK,
866 ThreadSafetyHandler &Handler) const override {
867 if (!Managed && !asserted() && !negative() && !isUniversal()) {
868 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
869 LEK);
870 }
871 }
872
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000873 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
874 ThreadSafetyHandler &Handler,
875 StringRef DiagKind) const override {
876 Handler.handleDoubleLock(DiagKind, entry.toString(), entry.loc());
877 }
878
Ed Schoutenca988742014-09-03 06:00:11 +0000879 void handleUnlock(FactSet &FSet, FactManager &FactMan,
880 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
881 bool FullyRemove, ThreadSafetyHandler &Handler,
882 StringRef DiagKind) const override {
883 FSet.removeLock(FactMan, Cp);
884 if (!Cp.negative()) {
885 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
886 !Cp, LK_Exclusive, UnlockLoc));
887 }
888 }
889};
890
891class ScopedLockableFactEntry : public FactEntry {
892private:
893 SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
894
895public:
896 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
897 const CapExprSet &Excl, const CapExprSet &Shrd)
898 : FactEntry(CE, LK_Exclusive, Loc, false) {
899 for (const auto &M : Excl)
900 UnderlyingMutexes.push_back(M.sexpr());
901 for (const auto &M : Shrd)
902 UnderlyingMutexes.push_back(M.sexpr());
903 }
904
905 void
906 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
907 SourceLocation JoinLoc, LockErrorKind LEK,
908 ThreadSafetyHandler &Handler) const override {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000909 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
Ed Schoutenca988742014-09-03 06:00:11 +0000910 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
911 // If this scoped lock manages another mutex, and if the underlying
912 // mutex is still held, then warn about the underlying mutex.
913 Handler.handleMutexHeldEndOfScope(
914 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
915 }
916 }
917 }
918
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000919 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
920 ThreadSafetyHandler &Handler,
921 StringRef DiagKind) const override {
922 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
923 CapabilityExpr UnderCp(UnderlyingMutex, false);
924
925 // We're relocking the underlying mutexes. Warn on double locking.
Aaron Puchert68c7fcd2018-08-23 21:13:32 +0000926 if (FSet.findLock(FactMan, UnderCp)) {
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000927 Handler.handleDoubleLock(DiagKind, UnderCp.toString(), entry.loc());
Aaron Puchert68c7fcd2018-08-23 21:13:32 +0000928 } else {
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000929 FSet.removeLock(FactMan, !UnderCp);
930 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
931 UnderCp, entry.kind(), entry.loc()));
932 }
933 }
934 }
935
Ed Schoutenca988742014-09-03 06:00:11 +0000936 void handleUnlock(FactSet &FSet, FactManager &FactMan,
937 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
938 bool FullyRemove, ThreadSafetyHandler &Handler,
939 StringRef DiagKind) const override {
940 assert(!Cp.negative() && "Managing object cannot be negative.");
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000941 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
Ed Schoutenca988742014-09-03 06:00:11 +0000942 CapabilityExpr UnderCp(UnderlyingMutex, false);
943 auto UnderEntry = llvm::make_unique<LockableFactEntry>(
944 !UnderCp, LK_Exclusive, UnlockLoc);
945
946 if (FullyRemove) {
947 // We're destroying the managing object.
948 // Remove the underlying mutex if it exists; but don't warn.
949 if (FSet.findLock(FactMan, UnderCp)) {
950 FSet.removeLock(FactMan, UnderCp);
951 FSet.addLock(FactMan, std::move(UnderEntry));
952 }
953 } else {
954 // We're releasing the underlying mutex, but not destroying the
955 // managing object. Warn on dual release.
956 if (!FSet.findLock(FactMan, UnderCp)) {
957 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
958 UnlockLoc);
959 }
960 FSet.removeLock(FactMan, UnderCp);
961 FSet.addLock(FactMan, std::move(UnderEntry));
962 }
963 }
964 if (FullyRemove)
965 FSet.removeLock(FactMan, Cp);
966 }
967};
968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000969/// Class which implements the core thread safety analysis routines.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000970class ThreadSafetyAnalyzer {
971 friend class BuildLockset;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000972 friend class threadSafety::BeforeSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000973
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000974 llvm::BumpPtrAllocator Bpa;
975 threadSafety::til::MemRegionRef Arena;
976 threadSafety::SExprBuilder SxBuilder;
977
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000978 ThreadSafetyHandler &Handler;
979 const CXXMethodDecl *CurrentMethod;
980 LocalVariableMap LocalVarMap;
981 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000982 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000983
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000984 BeforeSet *GlobalBeforeSet;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000985
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000986public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000987 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000988 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000989
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000990 bool inCurrentScope(const CapabilityExpr &CapE);
991
Ed Schoutenca988742014-09-03 06:00:11 +0000992 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
993 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +0000994 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000995 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
996 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000997
998 template <typename AttrType>
Aaron Puchert68c7fcd2018-08-23 21:13:32 +0000999 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +00001000 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001001
1002 template <class AttrType>
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001003 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001004 const NamedDecl *D,
1005 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1006 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001007
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001008 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1009 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001010
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001011 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1012 const CFGBlock* PredBlock,
1013 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001014
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001015 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1016 SourceLocation JoinLoc,
1017 LockErrorKind LEK1, LockErrorKind LEK2,
1018 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001019
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001020 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1021 SourceLocation JoinLoc, LockErrorKind LEK1,
1022 bool Modify=true) {
1023 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001024 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001025
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001026 void runAnalysis(AnalysisDeclContext &AC);
1027};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001028
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001029} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001030
1031/// Process acquired_before and acquired_after attributes on Vd.
1032BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1033 ThreadSafetyAnalyzer& Analyzer) {
1034 // Create a new entry for Vd.
Reid Kleckner19ff5602015-11-20 19:08:30 +00001035 BeforeInfo *Info = nullptr;
1036 {
1037 // Keep InfoPtr in its own scope in case BMap is modified later and the
1038 // reference becomes invalid.
1039 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1040 if (!InfoPtr)
1041 InfoPtr.reset(new BeforeInfo());
1042 Info = InfoPtr.get();
1043 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001044
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001045 for (const auto *At : Vd->attrs()) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001046 switch (At->getKind()) {
1047 case attr::AcquiredBefore: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001048 const auto *A = cast<AcquiredBeforeAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001049
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001050 // Read exprs from the attribute, and add them to BeforeVect.
1051 for (const auto *Arg : A->args()) {
1052 CapabilityExpr Cp =
1053 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1054 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
Reid Kleckner19ff5602015-11-20 19:08:30 +00001055 Info->Vect.push_back(Cpvd);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001056 const auto It = BMap.find(Cpvd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001057 if (It == BMap.end())
1058 insertAttrExprs(Cpvd, Analyzer);
1059 }
1060 }
1061 break;
1062 }
1063 case attr::AcquiredAfter: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001064 const auto *A = cast<AcquiredAfterAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001065
1066 // Read exprs from the attribute, and add them to BeforeVect.
1067 for (const auto *Arg : A->args()) {
1068 CapabilityExpr Cp =
1069 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1070 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1071 // Get entry for mutex listed in attribute
Reid Kleckner19ff5602015-11-20 19:08:30 +00001072 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1073 ArgInfo->Vect.push_back(Vd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001074 }
1075 }
1076 break;
1077 }
1078 default:
1079 break;
1080 }
1081 }
1082
1083 return Info;
1084}
1085
Reid Kleckner19ff5602015-11-20 19:08:30 +00001086BeforeSet::BeforeInfo *
1087BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1088 ThreadSafetyAnalyzer &Analyzer) {
1089 auto It = BMap.find(Vd);
1090 BeforeInfo *Info = nullptr;
1091 if (It == BMap.end())
1092 Info = insertAttrExprs(Vd, Analyzer);
1093 else
1094 Info = It->second.get();
1095 assert(Info && "BMap contained nullptr?");
1096 return Info;
1097}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001098
1099/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1100void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1101 const FactSet& FSet,
1102 ThreadSafetyAnalyzer& Analyzer,
1103 SourceLocation Loc, StringRef CapKind) {
1104 SmallVector<BeforeInfo*, 8> InfoVect;
1105
1106 // Do a depth-first traversal of Vd.
1107 // Return true if there are cycles.
1108 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1109 if (!Vd)
1110 return false;
1111
Reid Kleckner19ff5602015-11-20 19:08:30 +00001112 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001113
1114 if (Info->Visited == 1)
1115 return true;
1116
1117 if (Info->Visited == 2)
1118 return false;
1119
Reid Kleckner19ff5602015-11-20 19:08:30 +00001120 if (Info->Vect.empty())
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001121 return false;
1122
1123 InfoVect.push_back(Info);
1124 Info->Visited = 1;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001125 for (const auto *Vdb : Info->Vect) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001126 // Exclude mutexes in our immediate before set.
1127 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1128 StringRef L1 = StartVd->getName();
1129 StringRef L2 = Vdb->getName();
1130 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1131 }
1132 // Transitively search other before sets, and warn on cycles.
1133 if (traverse(Vdb)) {
1134 if (CycMap.find(Vd) == CycMap.end()) {
1135 CycMap.insert(std::make_pair(Vd, true));
1136 StringRef L1 = Vd->getName();
1137 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1138 }
1139 }
1140 }
1141 Info->Visited = 2;
1142 return false;
1143 };
1144
1145 traverse(StartVd);
1146
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001147 for (auto *Info : InfoVect)
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001148 Info->Visited = 0;
1149}
1150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001151/// Gets the value decl pointer from DeclRefExprs or MemberExprs.
Aaron Ballmane0449042014-04-01 21:43:23 +00001152static const ValueDecl *getValueDecl(const Expr *Exp) {
1153 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1154 return getValueDecl(CE->getSubExpr());
1155
1156 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1157 return DR->getDecl();
1158
1159 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1160 return ME->getMemberDecl();
1161
1162 return nullptr;
1163}
1164
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001165namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001166
Aaron Ballmane0449042014-04-01 21:43:23 +00001167template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001168class has_arg_iterator_range {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001169 using yes = char[1];
1170 using no = char[2];
Aaron Ballmane0449042014-04-01 21:43:23 +00001171
1172 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001173 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001174
1175 template <typename>
1176 static no& test(...);
1177
1178public:
1179 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1180};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001181
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001182} // namespace
Aaron Ballmane0449042014-04-01 21:43:23 +00001183
1184static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1185 return A->getName();
1186}
1187
1188static StringRef ClassifyDiagnostic(QualType VDT) {
1189 // We need to look at the declaration of the type of the value to determine
1190 // which it is. The type should either be a record or a typedef, or a pointer
1191 // or reference thereof.
1192 if (const auto *RT = VDT->getAs<RecordType>()) {
1193 if (const auto *RD = RT->getDecl())
1194 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1195 return ClassifyDiagnostic(CA);
1196 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1197 if (const auto *TD = TT->getDecl())
1198 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1199 return ClassifyDiagnostic(CA);
1200 } else if (VDT->isPointerType() || VDT->isReferenceType())
1201 return ClassifyDiagnostic(VDT->getPointeeType());
1202
1203 return "mutex";
1204}
1205
1206static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1207 assert(VD && "No ValueDecl passed");
1208
1209 // The ValueDecl is the declaration of a mutex or role (hopefully).
1210 return ClassifyDiagnostic(VD->getType());
1211}
1212
1213template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001214static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001215 StringRef>::type
1216ClassifyDiagnostic(const AttrTy *A) {
1217 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1218 return ClassifyDiagnostic(VD);
1219 return "mutex";
1220}
1221
1222template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001223static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001224 StringRef>::type
1225ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001226 for (const auto *Arg : A->args()) {
1227 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001228 return ClassifyDiagnostic(VD);
1229 }
1230 return "mutex";
1231}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001232
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001233bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001234 if (!CurrentMethod)
1235 return false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001236 if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1237 const auto *VD = P->clangDecl();
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001238 if (VD)
1239 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1240 }
1241 return false;
1242}
1243
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001244/// Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001245/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001246void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1247 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001248 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001249 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001250 return;
1251
Ed Schoutenca988742014-09-03 06:00:11 +00001252 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001253 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001254 CapabilityExpr NegC = !*Entry;
Aaron Puchert969f32d2018-09-21 23:08:30 +00001255 const FactEntry *Nen = FSet.findLock(FactMan, NegC);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001256 if (Nen) {
1257 FSet.removeLock(FactMan, NegC);
1258 }
1259 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001260 if (inCurrentScope(*Entry) && !Entry->asserted())
1261 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1262 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001263 }
1264 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001265
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001266 // Check before/after constraints
1267 if (Handler.issueBetaWarnings() &&
1268 !Entry->asserted() && !Entry->declared()) {
1269 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1270 Entry->loc(), DiagKind);
1271 }
1272
DeLesley Hutchins42665222014-08-04 16:10:59 +00001273 // FIXME: Don't always warn when we have support for reentrant locks.
Aaron Puchert969f32d2018-09-21 23:08:30 +00001274 if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
Ed Schoutenca988742014-09-03 06:00:11 +00001275 if (!Entry->asserted())
Aaron Puchertc3e37b72018-08-22 22:14:53 +00001276 Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001277 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001278 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001279 }
1280}
1281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001282/// Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001283/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001284void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001285 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001286 bool FullyRemove, LockKind ReceivedKind,
1287 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001288 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001289 return;
1290
DeLesley Hutchins42665222014-08-04 16:10:59 +00001291 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001292 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001293 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001294 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001295 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001296
Aaron Ballmandf115d92014-03-21 14:48:48 +00001297 // Generic lock removal doesn't care about lock kind mismatches, but
1298 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001299 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1300 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1301 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001302 }
1303
Ed Schoutenca988742014-09-03 06:00:11 +00001304 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1305 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001306}
1307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001308/// Extract the list of mutexIDs from the attribute on an expression,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001309/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001310template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001311void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001312 const Expr *Exp, const NamedDecl *D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001313 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001314 if (Attr->args_size() == 0) {
1315 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001316 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1317 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001318 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1319 return;
1320 }
1321 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001322 if (!Cp.shouldIgnore())
1323 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001324 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001325 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001326
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001327 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001328 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1329 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001330 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001331 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001332 }
1333 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001334 if (!Cp.shouldIgnore())
1335 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001336 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001337}
1338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001339/// Extract the list of mutexIDs from a trylock attribute. If the
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001340/// trylock applies to the given edge, then push them onto Mtxs, discarding
1341/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001342template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001343void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001344 const Expr *Exp, const NamedDecl *D,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001345 const CFGBlock *PredBlock,
1346 const CFGBlock *CurrBlock,
1347 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001348 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001349 bool branch = false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001350 if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001351 branch = BLE->getValue();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001352 else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001353 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001354
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001355 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001356 if (Neg)
1357 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001358
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001359 // If we've taken the trylock branch, then add the lock
1360 int i = 0;
1361 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1362 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001363 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001364 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001365 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001366}
1367
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001368static bool getStaticBooleanValue(Expr *E, bool &TCond) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001369 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1370 TCond = false;
1371 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001372 } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001373 TCond = BLE->getValue();
1374 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001375 } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001376 TCond = ILE->getValue().getBoolValue();
1377 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001378 } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001379 return getStaticBooleanValue(CE->getSubExpr(), TCond);
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001380 return false;
1381}
1382
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001383// 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(...))
1386const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1387 LocalVarContext C,
1388 bool &Negate) {
1389 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001390 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001391
Aaron Puchert7146b002018-10-03 11:58:19 +00001392 if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
1393 if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
1394 return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001395 return CallExp;
Aaron Puchert7146b002018-10-03 11:58:19 +00001396 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001397 else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001398 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001399 else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001400 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001401 else if (const auto *EWC = dyn_cast<ExprWithCleanups>(Cond))
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001402 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001403 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001404 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1405 return getTrylockCallExpr(E, C, Negate);
1406 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001407 else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001408 if (UOP->getOpcode() == UO_LNot) {
1409 Negate = !Negate;
1410 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1411 }
Craig Topper25542942014-05-20 04:30:07 +00001412 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001413 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001414 else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001415 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1416 if (BOP->getOpcode() == BO_NE)
1417 Negate = !Negate;
1418
1419 bool TCond = false;
1420 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1421 if (!TCond) Negate = !Negate;
1422 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1423 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001424 TCond = false;
1425 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001426 if (!TCond) Negate = !Negate;
1427 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1428 }
Craig Topper25542942014-05-20 04:30:07 +00001429 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001430 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001431 if (BOP->getOpcode() == BO_LAnd) {
1432 // LHS must have been evaluated in a different block.
1433 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1434 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001435 if (BOP->getOpcode() == BO_LOr)
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001436 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
Craig Topper25542942014-05-20 04:30:07 +00001437 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001438 }
Craig Topper25542942014-05-20 04:30:07 +00001439 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001440}
1441
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001442/// Find the lockset that holds on the edge between PredBlock
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001443/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1444/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001445void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1446 const FactSet &ExitSet,
1447 const CFGBlock *PredBlock,
1448 const CFGBlock *CurrBlock) {
1449 Result = ExitSet;
1450
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001451 const Stmt *Cond = PredBlock->getTerminatorCondition();
1452 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001453 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001454
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001455 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001456 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1457 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001458 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001459
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001460 const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001461 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001462 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001463
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001464 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001465 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001466 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001467
DeLesley Hutchins42665222014-08-04 16:10:59 +00001468 CapExprSet ExclusiveLocksToAdd;
1469 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001470
1471 // If the condition is a call to a Trylock function, then grab the attributes
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001472 for (const auto *Attr : FunDecl->attrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001473 switch (Attr->getKind()) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00001474 case attr::TryAcquireCapability: {
1475 auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1476 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1477 Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1478 Negate);
1479 CapDiagKind = ClassifyDiagnostic(A);
1480 break;
1481 };
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001482 case attr::ExclusiveTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001483 const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001484 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1485 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001486 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001487 break;
1488 }
1489 case attr::SharedTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001490 const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001491 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001492 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001493 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001494 break;
1495 }
1496 default:
1497 break;
1498 }
1499 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001500
1501 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001502 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001503 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001504 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1505 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001506 CapDiagKind);
1507 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001508 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1509 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001510 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001511}
1512
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001513namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001515/// We use this class to visit different types of expressions in
Caitlin Sadowski33208342011-09-09 16:11:56 +00001516/// CFGBlocks, and build up the lockset.
1517/// An expression may cause us to add or remove locks from the lockset, or else
1518/// output error messages related to missing locks.
1519/// FIXME: In future, we may be able to not inherit from a visitor.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001520class BuildLockset : public ConstStmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001521 friend class ThreadSafetyAnalyzer;
1522
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001523 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001524 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001525 LocalVariableMap::Context LVarCtx;
1526 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001527
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001528 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001529 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001530 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001531 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001532 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1533 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001534
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001535 void checkAccess(const Expr *Exp, AccessKind AK,
1536 ProtectedOperationKind POK = POK_VarAccess);
1537 void checkPtAccess(const Expr *Exp, AccessKind AK,
1538 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001539
Aaron Puchertcd37c092018-08-23 21:53:04 +00001540 void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001541
Caitlin Sadowski33208342011-09-09 16:11:56 +00001542public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001543 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
Aaron Puchertcd37c092018-08-23 21:53:04 +00001544 : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001545 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001546
Aaron Puchertcd37c092018-08-23 21:53:04 +00001547 void VisitUnaryOperator(const UnaryOperator *UO);
1548 void VisitBinaryOperator(const BinaryOperator *BO);
1549 void VisitCastExpr(const CastExpr *CE);
1550 void VisitCallExpr(const CallExpr *Exp);
1551 void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1552 void VisitDeclStmt(const DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001553};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001554
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001555} // namespace
DeLesley Hutchins42665222014-08-04 16:10:59 +00001556
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001557/// Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001558/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001559void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001560 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001561 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001562 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001563 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001564
DeLesley Hutchins42665222014-08-04 16:10:59 +00001565 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1566 if (Cp.isInvalid()) {
1567 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001568 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001569 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001570 return;
1571 }
1572
DeLesley Hutchins42665222014-08-04 16:10:59 +00001573 if (Cp.negative()) {
1574 // Negative capabilities act like locks excluded
Aaron Puchert969f32d2018-09-21 23:08:30 +00001575 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001576 if (LDat) {
1577 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001578 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001579 return;
1580 }
1581
1582 // If this does not refer to a negative capability in the same class,
1583 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001584 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001585 return;
1586
1587 // Otherwise the negative requirement must be propagated to the caller.
1588 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1589 if (!LDat) {
1590 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001591 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001592 }
1593 return;
1594 }
1595
Aaron Puchert969f32d2018-09-21 23:08:30 +00001596 const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001597 bool NoError = true;
1598 if (!LDat) {
1599 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001600 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1601 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001602 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001603 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001604 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001605 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1606 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001607 } else {
1608 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001609 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1610 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001611 }
1612 NoError = false;
1613 }
1614 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001615 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001616 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1617 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001618 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001619}
1620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001621/// Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001622void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001623 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001624 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1625 if (Cp.isInvalid()) {
1626 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1627 return;
1628 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001629 return;
1630 }
1631
Aaron Puchert969f32d2018-09-21 23:08:30 +00001632 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001633 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001634 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001635 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1636 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001637}
1638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001639/// Checks guarded_by and pt_guarded_by attributes.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001640/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1641/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1642/// Similarly, we check if the access is to an expression that dereferences
1643/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001644void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1645 ProtectedOperationKind POK) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00001646 Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001647
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001648 SourceLocation Loc = Exp->getExprLoc();
1649
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001650 // Local variables of reference type cannot be re-assigned;
1651 // map them to their initializer.
1652 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1653 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1654 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1655 if (const auto *E = VD->getInit()) {
Aaron Ballman57deab72018-08-24 18:48:35 +00001656 // Guard against self-initialization. e.g., int &i = i;
1657 if (E == Exp)
1658 break;
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001659 Exp = E;
1660 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001661 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001662 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001663 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001664 }
1665
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001666 if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001667 // For dereferences
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001668 if (UO->getOpcode() == UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001669 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001670 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001671 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001672
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001673 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001674 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001675 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001676 }
1677
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001678 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001679 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001680 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001681 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001682 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001683 }
1684
Caitlin Sadowski33208342011-09-09 16:11:56 +00001685 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001686 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001687 return;
1688
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001689 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001690 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001691 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001692
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001693 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001694 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001695 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001696}
1697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001698/// Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001699/// POK is the same operationKind that was passed to checkAccess.
1700void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1701 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001702 while (true) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001703 if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001704 Exp = PE->getSubExpr();
1705 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001706 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001707 if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001708 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1709 // If it's an actual array, and not a pointer, then it's elements
1710 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001711 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001712 return;
1713 }
1714 Exp = CE->getSubExpr();
1715 continue;
1716 }
1717 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001718 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001719
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001720 // Pass by reference warnings are under a different flag.
1721 ProtectedOperationKind PtPOK = POK_VarDereference;
1722 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1723
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001724 const ValueDecl *D = getValueDecl(Exp);
1725 if (!D || !D->hasAttrs())
1726 return;
1727
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001728 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001729 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001730 Exp->getExprLoc());
1731
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001732 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001733 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001734 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001735}
1736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001737/// Process a function call, method call, constructor call,
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001738/// or destructor call. This involves looking at the attributes on the
1739/// corresponding function/method/constructor/destructor, issuing warnings,
1740/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001741///
1742/// FIXME: For classes annotated with one of the guarded annotations, we need
1743/// to treat const method calls as reads and non-const method calls as writes,
1744/// and check that the appropriate locks are held. Non-const method calls with
1745/// the same signature as const method calls can be also treated as reads.
1746///
Aaron Puchertcd37c092018-08-23 21:53:04 +00001747void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1748 VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001749 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001750 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1751 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001752 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
Aaron Ballmane0449042014-04-01 21:43:23 +00001753 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001754
Richard Smithe97654b2018-01-11 22:13:57 +00001755 // Figure out if we're constructing an object of scoped lockable class
Haojian Wu74e0f402018-08-13 12:50:30 +00001756 bool isScopedVar = false;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001757 if (VD) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001758 if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001759 const CXXRecordDecl* PD = CD->getParent();
1760 if (PD && PD->hasAttr<ScopedLockableAttr>())
Haojian Wu74e0f402018-08-13 12:50:30 +00001761 isScopedVar = true;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001762 }
1763 }
1764
Aaron Ballman1b587592018-07-26 13:03:16 +00001765 for(const Attr *At : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001766 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001767 // When we encounter a lock function, we need to add the lock to our
1768 // lockset.
1769 case attr::AcquireCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001770 const auto *A = cast<AcquireCapabilityAttr>(At);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001771 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1772 : ExclusiveLocksToAdd,
1773 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001774
1775 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001776 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001777 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001778
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001779 // An assert will add a lock to the lockset, but will not generate
1780 // a warning if it is already there, and will not generate a warning
1781 // if it is not removed.
1782 case attr::AssertExclusiveLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001783 const auto *A = cast<AssertExclusiveLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001784
DeLesley Hutchins42665222014-08-04 16:10:59 +00001785 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001786 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001787 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001788 Analyzer->addLock(FSet,
1789 llvm::make_unique<LockableFactEntry>(
1790 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001791 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001792 break;
1793 }
1794 case attr::AssertSharedLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001795 const auto *A = cast<AssertSharedLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001796
DeLesley Hutchins42665222014-08-04 16:10:59 +00001797 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001798 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001799 for (const auto &AssertLock : AssertLocks)
Josh Gaoec1369e2017-08-08 19:44:34 +00001800 Analyzer->addLock(FSet,
1801 llvm::make_unique<LockableFactEntry>(
1802 AssertLock, LK_Shared, Loc, false, true),
1803 ClassifyDiagnostic(A));
1804 break;
1805 }
1806
1807 case attr::AssertCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001808 const auto *A = cast<AssertCapabilityAttr>(At);
Josh Gaoec1369e2017-08-08 19:44:34 +00001809 CapExprSet AssertLocks;
1810 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1811 for (const auto &AssertLock : AssertLocks)
1812 Analyzer->addLock(FSet,
1813 llvm::make_unique<LockableFactEntry>(
1814 AssertLock,
1815 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1816 false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001817 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001818 break;
1819 }
1820
Caitlin Sadowski33208342011-09-09 16:11:56 +00001821 // When we encounter an unlock function, we need to remove unlocked
1822 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001823 case attr::ReleaseCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001824 const auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001825 if (A->isGeneric())
1826 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1827 else if (A->isShared())
1828 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1829 else
1830 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001831
1832 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001833 break;
1834 }
1835
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001836 case attr::RequiresCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001837 const auto *A = cast<RequiresCapabilityAttr>(At);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001838 for (auto *Arg : A->args()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001839 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001840 POK_FunctionCall, ClassifyDiagnostic(A),
1841 Exp->getExprLoc());
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001842 // use for adopting a lock
Haojian Wu74e0f402018-08-13 12:50:30 +00001843 if (isScopedVar) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001844 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1845 : ScopedExclusiveReqs,
1846 A, Exp, D, VD);
1847 }
1848 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001849 break;
1850 }
1851
1852 case attr::LocksExcluded: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001853 const auto *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001854 for (auto *Arg : A->args())
1855 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001856 break;
1857 }
1858
Alp Tokerd4733632013-12-05 04:47:09 +00001859 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001860 default:
1861 break;
1862 }
1863 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001864
Aaron Ballman1b587592018-07-26 13:03:16 +00001865 // Remove locks first to allow lock upgrading/downgrading.
1866 // FIXME -- should only fully remove if the attribute refers to 'this'.
1867 bool Dtor = isa<CXXDestructorDecl>(D);
1868 for (const auto &M : ExclusiveLocksToRemove)
1869 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1870 for (const auto &M : SharedLocksToRemove)
1871 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1872 for (const auto &M : GenericLocksToRemove)
1873 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1874
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001875 // Add locks.
Haojian Wu74e0f402018-08-13 12:50:30 +00001876 for (const auto &M : ExclusiveLocksToAdd)
1877 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1878 M, LK_Exclusive, Loc, isScopedVar),
1879 CapDiagKind);
1880 for (const auto &M : SharedLocksToAdd)
1881 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1882 M, LK_Shared, Loc, isScopedVar),
1883 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001884
Haojian Wu74e0f402018-08-13 12:50:30 +00001885 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001886 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001887 SourceLocation MLoc = VD->getLocation();
1888 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001889 // FIXME: does this store a pointer to DRE?
1890 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001891
1892 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1893 std::back_inserter(ExclusiveLocksToAdd));
1894 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1895 std::back_inserter(SharedLocksToAdd));
Ed Schoutenca988742014-09-03 06:00:11 +00001896 Analyzer->addLock(FSet,
1897 llvm::make_unique<ScopedLockableFactEntry>(
1898 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1899 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001900 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001901}
1902
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001903/// For unary operations which read and write a variable, we need to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001904/// check whether we hold any required mutexes. Reads are checked in
1905/// VisitCastExpr.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001906void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001907 switch (UO->getOpcode()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001908 case UO_PostDec:
1909 case UO_PostInc:
1910 case UO_PreDec:
1911 case UO_PreInc:
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001912 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001913 break;
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001914 default:
1915 break;
1916 }
1917}
1918
1919/// For binary operations which assign to a variable (writes), we need to check
1920/// whether we hold any required mutexes.
1921/// FIXME: Deal with non-primitive types.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001922void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001923 if (!BO->isAssignmentOp())
1924 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001925
1926 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001927 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001928
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001929 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001930}
1931
1932/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1933/// need to ensure we hold any required mutexes.
1934/// FIXME: Deal with non-primitive types.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001935void BuildLockset::VisitCastExpr(const CastExpr *CE) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001936 if (CE->getCastKind() != CK_LValueToRValue)
1937 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001938 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001939}
1940
Aaron Puchertcd37c092018-08-23 21:53:04 +00001941void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001942 bool ExamineArgs = true;
1943 bool OperatorFun = false;
1944
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001945 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1946 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001947 // ME can be null when calling a method pointer
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001948 const CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001949
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001950 if (ME && MD) {
1951 if (ME->isArrow()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001952 if (MD->isConst())
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001953 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001954 else // FIXME -- should be AK_Written
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001955 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001956 } else {
1957 if (MD->isConst())
1958 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1959 else // FIXME -- should be AK_Written
1960 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001961 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001962 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001963 } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001964 OperatorFun = true;
1965
1966 auto OEop = OE->getOperator();
1967 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001968 case OO_Equal: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001969 ExamineArgs = false;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001970 const Expr *Target = OE->getArg(0);
1971 const Expr *Source = OE->getArg(1);
1972 checkAccess(Target, AK_Written);
1973 checkAccess(Source, AK_Read);
1974 break;
1975 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001976 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001977 case OO_Arrow:
1978 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001979 const Expr *Obj = OE->getArg(0);
1980 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001981 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1982 // Grrr. operator* can be multiplication...
1983 checkPtAccess(Obj, AK_Read);
1984 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001985 break;
1986 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001987 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001988 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001989 const Expr *Obj = OE->getArg(0);
1990 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001991 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001992 }
1993 }
1994 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001995
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001996 if (ExamineArgs) {
Aaron Puchertcd37c092018-08-23 21:53:04 +00001997 if (const FunctionDecl *FD = Exp->getDirectCallee()) {
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001998 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
1999 // only turns off checking within the body of a function, but we also
2000 // use it to turn off checking in arguments to the function. This
2001 // could result in some false negatives, but the alternative is to
2002 // create yet another attribute.
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002003 if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
2004 unsigned Fn = FD->getNumParams();
2005 unsigned Cn = Exp->getNumArgs();
2006 unsigned Skip = 0;
2007
2008 unsigned i = 0;
2009 if (OperatorFun) {
2010 if (isa<CXXMethodDecl>(FD)) {
2011 // First arg in operator call is implicit self argument,
2012 // and doesn't appear in the FunctionDecl.
2013 Skip = 1;
2014 Cn--;
2015 } else {
2016 // Ignore the first argument of operators; it's been checked above.
2017 i = 1;
2018 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002019 }
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002020 // Ignore default arguments
2021 unsigned n = (Fn < Cn) ? Fn : Cn;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002022
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002023 for (; i < n; ++i) {
Aaron Puchertcd37c092018-08-23 21:53:04 +00002024 const ParmVarDecl *Pvd = FD->getParamDecl(i);
2025 const Expr *Arg = Exp->getArg(i + Skip);
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002026 QualType Qt = Pvd->getType();
2027 if (Qt->isReferenceType())
2028 checkAccess(Arg, AK_Read, POK_PassByRef);
2029 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002030 }
2031 }
2032 }
2033
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002034 auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002035 if(!D || !D->hasAttrs())
2036 return;
2037 handleCall(Exp, D);
2038}
2039
Aaron Puchertcd37c092018-08-23 21:53:04 +00002040void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002041 const CXXConstructorDecl *D = Exp->getConstructor();
2042 if (D && D->isCopyConstructor()) {
2043 const Expr* Source = Exp->getArg(0);
2044 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002045 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002046 // FIXME -- only handles constructors in DeclStmt below.
2047}
2048
Richard Smithe97654b2018-01-11 22:13:57 +00002049static CXXConstructorDecl *
2050findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2051 // Prefer a move constructor over a copy constructor. If there's more than
2052 // one copy constructor or more than one move constructor, we arbitrarily
2053 // pick the first declared such constructor rather than trying to guess which
2054 // one is more appropriate.
2055 CXXConstructorDecl *CopyCtor = nullptr;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002056 for (auto *Ctor : RD->ctors()) {
Richard Smithe97654b2018-01-11 22:13:57 +00002057 if (Ctor->isDeleted())
2058 continue;
2059 if (Ctor->isMoveConstructor())
2060 return Ctor;
2061 if (!CopyCtor && Ctor->isCopyConstructor())
2062 CopyCtor = Ctor;
2063 }
2064 return CopyCtor;
2065}
2066
2067static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2068 SourceLocation Loc) {
2069 ASTContext &Ctx = CD->getASTContext();
2070 return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2071 CD, true, Args, false, false, false, false,
2072 CXXConstructExpr::CK_Complete,
2073 SourceRange(Loc, Loc));
2074}
2075
Aaron Puchertcd37c092018-08-23 21:53:04 +00002076void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002077 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002078 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002079
Aaron Ballman9ee54d12014-05-14 20:42:13 +00002080 for (auto *D : S->getDeclGroup()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002081 if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002082 Expr *E = VD->getInit();
Richard Smithe97654b2018-01-11 22:13:57 +00002083 if (!E)
2084 continue;
2085 E = E->IgnoreParens();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002086
Richard Smithe97654b2018-01-11 22:13:57 +00002087 // handle constructors that involve temporaries
2088 if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2089 E = EWC->getSubExpr();
2090 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2091 E = BTE->getSubExpr();
2092
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002093 if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2094 const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002095 if (!CtorD || !CtorD->hasAttrs())
Richard Smithe97654b2018-01-11 22:13:57 +00002096 continue;
2097 handleCall(E, CtorD, VD);
2098 } else if (isa<CallExpr>(E) && E->isRValue()) {
2099 // If the object is initialized by a function call that returns a
2100 // scoped lockable by value, use the attributes on the copy or move
2101 // constructor to figure out what effect that should have on the
2102 // lockset.
2103 // FIXME: Is this really the best way to handle this situation?
2104 auto *RD = E->getType()->getAsCXXRecordDecl();
2105 if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2106 continue;
2107 CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2108 if (!CtorD || !CtorD->hasAttrs())
2109 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002110 handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002111 }
2112 }
2113 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002114}
2115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002116/// Compute the intersection of two locksets and issue warnings for any
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002117/// locks in the symmetric difference.
2118///
2119/// This function is used at a merge point in the CFG when comparing the lockset
2120/// of each branch being merged. For example, given the following sequence:
2121/// A; if () then B; else C; D; we need to check that the lockset after B and C
2122/// are the same. In the event of a difference, we use the intersection of these
2123/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002124///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002125/// \param FSet1 The first lockset.
2126/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002127/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002128/// \param LEK1 The error message to report if a mutex is missing from LSet1
2129/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002130void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2131 const FactSet &FSet2,
2132 SourceLocation JoinLoc,
2133 LockErrorKind LEK1,
2134 LockErrorKind LEK2,
2135 bool Modify) {
2136 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002137
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002138 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002139 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002140 const FactEntry *LDat1 = nullptr;
2141 const FactEntry *LDat2 = &FactMan[Fact];
2142 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2143 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002144
DeLesley Hutchins42665222014-08-04 16:10:59 +00002145 if (LDat1) {
2146 if (LDat1->kind() != LDat2->kind()) {
2147 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2148 LDat2->loc(), LDat1->loc());
2149 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002150 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002151 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002152 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002153 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00002154 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002155 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002156 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002157 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002158 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00002159 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2160 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002161 }
2162 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002163
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002164 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002165 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002166 const FactEntry *LDat1 = &FactMan[Fact];
2167 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002168
DeLesley Hutchins42665222014-08-04 16:10:59 +00002169 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00002170 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2171 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002172 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00002173 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002174 }
2175 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002176}
2177
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002178// Return true if block B never continues to its successors.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002179static bool neverReturns(const CFGBlock *B) {
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002180 if (B->hasNoReturnElement())
2181 return true;
2182 if (B->empty())
2183 return false;
2184
2185 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002186 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2187 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002188 return true;
2189 }
2190 return false;
2191}
2192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002193/// Check a function's CFG for thread-safety violations.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002194///
2195/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2196/// at the end of each block, and issue warnings for thread safety violations.
2197/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002198void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002199 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2200 // For now, we just use the walker to set things up.
2201 threadSafety::CFGWalker walker;
2202 if (!walker.init(AC))
2203 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002204
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002205 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002206 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002207
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002208 CFG *CFGraph = walker.getGraph();
2209 const NamedDecl *D = walker.getDecl();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002210 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00002211 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002212
Aaron Ballman9ead1242013-12-19 02:39:40 +00002213 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002214 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002215
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002216 // FIXME: Do something a bit more intelligent inside constructor and
2217 // destructor code. Constructors and destructors must assume unique access
2218 // to 'this', so checks on member variable access is disabled, but we should
2219 // still enable checks on other objects.
2220 if (isa<CXXConstructorDecl>(D))
2221 return; // Don't check inside constructors.
2222 if (isa<CXXDestructorDecl>(D))
2223 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002224
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002225 Handler.enterFunction(CurrentFunction);
2226
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002227 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002228 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002229
2230 // We need to explore the CFG via a "topological" ordering.
2231 // That way, we will be guaranteed to have information about required
2232 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002233 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002234 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002235
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002236 // Mark entry block as reachable
2237 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2238
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002239 // Compute SSA names for local variables
2240 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2241
Richard Smith92286672012-02-03 04:45:26 +00002242 // Fill in source locations for all CFGBlocks.
2243 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2244
DeLesley Hutchins42665222014-08-04 16:10:59 +00002245 CapExprSet ExclusiveLocksAcquired;
2246 CapExprSet SharedLocksAcquired;
2247 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002248
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002249 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002250 // to initial lockset. Also turn off checking for lock and unlock functions.
2251 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002252 if (!SortedGraph->empty() && D->hasAttrs()) {
2253 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002254 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002255
DeLesley Hutchins42665222014-08-04 16:10:59 +00002256 CapExprSet ExclusiveLocksToAdd;
2257 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002258 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002259
2260 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002261 for (const auto *Attr : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002262 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002263 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002264 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00002265 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002266 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002267 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002268 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2269 // We must ignore such methods.
2270 if (A->args_size() == 0)
2271 return;
Aaron Ballmaneaa18e62018-08-03 19:37:45 +00002272 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2273 nullptr, D);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002274 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002275 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002276 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002277 if (A->args_size() == 0)
2278 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002279 getMutexIDs(A->isShared() ? SharedLocksAcquired
2280 : ExclusiveLocksAcquired,
2281 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002282 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002283 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002284 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002285 return;
2286 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002287 // Don't try to check trylock functions for now.
2288 return;
2289 } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2290 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002291 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002292 }
2293 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002294
2295 // FIXME -- Loc can be wrong here.
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002296 for (const auto &Mu : ExclusiveLocksToAdd) {
2297 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2298 Entry->setDeclared(true);
2299 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2300 }
2301 for (const auto &Mu : SharedLocksToAdd) {
2302 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2303 Entry->setDeclared(true);
2304 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2305 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002306 }
2307
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002308 for (const auto *CurrBlock : *SortedGraph) {
Aaron Puchert88d85362018-09-22 21:56:16 +00002309 unsigned CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002310 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002311
2312 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002313 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002314
2315 // Iterate through the predecessor blocks and warn if the lockset for all
2316 // predecessors is not the same. We take the entry lockset of the current
2317 // block to be the intersection of all previous locksets.
2318 // FIXME: By keeping the intersection, we may output more errors in future
2319 // for a lock which is not in the intersection, but was in the union. We
2320 // may want to also keep the union in future. As an example, let's say
2321 // the intersection contains Mutex L, and the union contains L and M.
2322 // Later we unlock M. At this point, we would output an error because we
2323 // never locked M; although the real error is probably that we forgot to
2324 // lock M on all code paths. Conversely, let's say that later we lock M.
2325 // In this case, we should compare against the intersection instead of the
2326 // union because the real error is probably that we forgot to unlock M on
2327 // all code paths.
2328 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002329 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002330 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2331 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002332 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002333 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002334 continue;
2335
Aaron Puchert88d85362018-09-22 21:56:16 +00002336 unsigned PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002337 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2338
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002339 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002340 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002341 continue;
2342
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002343 // Okay, we can reach this block from the entry.
2344 CurrBlockInfo->Reachable = true;
2345
Richard Smith815b29d2012-02-03 03:30:07 +00002346 // If the previous block ended in a 'continue' or 'break' statement, then
2347 // a difference in locksets is probably due to a bug in that block, rather
2348 // than in some other predecessor. In that case, keep the other
2349 // predecessor's lockset.
2350 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2351 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2352 SpecialBlocks.push_back(*PI);
2353 continue;
2354 }
2355 }
2356
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002357 FactSet PrevLockset;
2358 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002359
Caitlin Sadowski33208342011-09-09 16:11:56 +00002360 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002361 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002362 LocksetInitialized = true;
2363 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002364 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2365 CurrBlockInfo->EntryLoc,
2366 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002367 }
2368 }
2369
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002370 // Skip rest of block if it's not reachable.
2371 if (!CurrBlockInfo->Reachable)
2372 continue;
2373
Richard Smith815b29d2012-02-03 03:30:07 +00002374 // Process continue and break blocks. Assume that the lockset for the
2375 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002376 for (const auto *PrevBlock : SpecialBlocks) {
Aaron Puchert88d85362018-09-22 21:56:16 +00002377 unsigned PrevBlockID = PrevBlock->getBlockID();
Richard Smith815b29d2012-02-03 03:30:07 +00002378 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2379
2380 if (!LocksetInitialized) {
2381 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2382 LocksetInitialized = true;
2383 } else {
2384 // Determine whether this edge is a loop terminator for diagnostic
2385 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2386 // it might also be part of a switch. Also, a subsequent destructor
2387 // might add to the lockset, in which case the real issue might be a
2388 // double lock on the other path.
2389 const Stmt *Terminator = PrevBlock->getTerminator();
2390 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2391
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002392 FactSet PrevLockset;
2393 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2394 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002395
Richard Smith815b29d2012-02-03 03:30:07 +00002396 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002397 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2398 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002399 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002400 : LEK_LockedSomePredecessors,
2401 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002402 }
2403 }
2404
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002405 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2406
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002407 // Visit all the statements in the basic block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002408 for (const auto &BI : *CurrBlock) {
2409 switch (BI.getKind()) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002410 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002411 CFGStmt CS = BI.castAs<CFGStmt>();
Aaron Puchertcd37c092018-08-23 21:53:04 +00002412 LocksetBuilder.Visit(CS.getStmt());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002413 break;
2414 }
2415 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2416 case CFGElement::AutomaticObjectDtor: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002417 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
Aaron Puchertcd37c092018-08-23 21:53:04 +00002418 const auto *DD = AD.getDestructorDecl(AC.getASTContext());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002419 if (!DD->hasAttrs())
2420 break;
2421
2422 // Create a dummy expression,
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002423 auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
Richard Trieua1877592015-03-16 21:49:43 +00002424 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002425 VK_LValue, AD.getTriggerStmt()->getEndLoc());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002426 LocksetBuilder.handleCall(&DRE, DD);
2427 break;
2428 }
2429 default:
2430 break;
2431 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002432 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002433 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002434
2435 // For every back edge from CurrBlock (the end of the loop) to another block
2436 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2437 // the one held at the beginning of FirstLoopBlock. We can look up the
2438 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2439 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2440 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002441 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002442 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002443 continue;
2444
2445 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002446 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2447 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2448 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2449 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002450 LEK_LockedSomeLoopIterations,
2451 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002452 }
2453 }
2454
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002455 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2456 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002457
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002458 // Skip the final check if the exit block is unreachable.
2459 if (!Final->Reachable)
2460 return;
2461
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002462 // By default, we expect all locks held on entry to be held on exit.
2463 FactSet ExpectedExitSet = Initial->EntrySet;
2464
2465 // Adjust the expected exit set by adding or removing locks, as declared
2466 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2467 // issue the appropriate warning.
2468 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002469 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002470 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2471 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002472 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002473 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2474 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002475 for (const auto &Lock : LocksReleased)
2476 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002477
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002478 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002479 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002480 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002481 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002482 LEK_NotLockedAtEndOfFunction,
2483 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002484
2485 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002486}
2487
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002488/// Check a function's CFG for thread-safety violations.
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002489///
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.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002493void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2494 ThreadSafetyHandler &Handler,
2495 BeforeSet **BSet) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002496 if (!*BSet)
2497 *BSet = new BeforeSet;
2498 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002499 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002500}
2501
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002502void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002504/// Helper function that returns a LockKind required for the given level
Caitlin Sadowski33208342011-09-09 16:11:56 +00002505/// of access.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002506LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002507 switch (AK) {
2508 case AK_Read :
2509 return LK_Shared;
2510 case AK_Written :
2511 return LK_Exclusive;
2512 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002513 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002514}