blob: e11ba12501f088ea85d3865919bc04949cd99c53 [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"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000036#include "clang/Basic/LLVM.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000037#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/Basic/SourceLocation.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000039#include "clang/Basic/Specifiers.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseMap.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000042#include "llvm/ADT/ImmutableMap.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000043#include "llvm/ADT/Optional.h"
44#include "llvm/ADT/STLExtras.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000045#include "llvm/ADT/SmallVector.h"
46#include "llvm/ADT/StringRef.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000047#include "llvm/Support/Allocator.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/ErrorHandling.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000050#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000051#include <algorithm>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000052#include <cassert>
53#include <functional>
54#include <iterator>
55#include <memory>
56#include <string>
57#include <type_traits>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000058#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000059#include <vector>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000060
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000061using namespace clang;
62using namespace threadSafety;
Caitlin Sadowski33208342011-09-09 16:11:56 +000063
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000064// Key method definition
Eugene Zelenkobbe25312018-03-16 21:22:42 +000065ThreadSafetyHandler::~ThreadSafetyHandler() = default;
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000066
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000067namespace {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000068
Eugene Zelenkobbe25312018-03-16 21:22:42 +000069class TILPrinter :
70 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
71
72} // namespace
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000073
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000074/// Issue a warning about an invalid lock expression
75static void warnInvalidLock(ThreadSafetyHandler &Handler,
76 const Expr *MutexExp, const NamedDecl *D,
77 const Expr *DeclExp, StringRef Kind) {
78 SourceLocation Loc;
79 if (DeclExp)
80 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000081
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000082 // FIXME: add a note about the attribute location in MutexExp or D
83 if (Loc.isValid())
84 Handler.handleInvalidLockExp(Kind, Loc);
85}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000086
Eugene Zelenkobbe25312018-03-16 21:22:42 +000087namespace {
88
Aaron Puchert78619432018-08-22 21:06:04 +000089/// A set of CapabilityExpr objects, which are compiled from thread safety
90/// attributes on a function.
DeLesley Hutchins42665222014-08-04 16:10:59 +000091class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000092public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000093 /// Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000094 void push_back_nodup(const CapabilityExpr &CapE) {
95 iterator It = std::find_if(begin(), end(),
96 [=](const CapabilityExpr &CapE2) {
97 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000098 });
99 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +0000100 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000101 }
102};
103
Ed Schoutenca988742014-09-03 06:00:11 +0000104class FactManager;
105class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000107/// This is a helper class that stores a fact that is known at a
DeLesley Hutchins42665222014-08-04 16:10:59 +0000108/// particular point in program execution. Currently, a fact is a capability,
109/// along with additional information, such as where it was acquired, whether
110/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +0000111///
Aaron Ballman1b587592018-07-26 13:03:16 +0000112/// FIXME: this analysis does not currently support re-entrant locking.
DeLesley Hutchins42665222014-08-04 16:10:59 +0000113class FactEntry : public CapabilityExpr {
114private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000115 /// Exclusive or shared.
116 LockKind LKind;
117
118 /// Where it was acquired.
119 SourceLocation AcquireLoc;
120
121 /// True if the lock was asserted.
122 bool Asserted;
123
124 /// True if the lock was declared.
125 bool Declared;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000126
DeLesley Hutchins42665222014-08-04 16:10:59 +0000127public:
128 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000129 bool Asrt, bool Declrd = false)
130 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
131 Declared(Declrd) {}
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000132 virtual ~FactEntry() = default;
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000133
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000134 LockKind kind() const { return LKind; }
135 SourceLocation loc() const { return AcquireLoc; }
136 bool asserted() const { return Asserted; }
137 bool declared() const { return Declared; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000138
139 void setDeclared(bool D) { Declared = D; }
Ed Schoutenca988742014-09-03 06:00:11 +0000140
141 virtual void
142 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
143 SourceLocation JoinLoc, LockErrorKind LEK,
144 ThreadSafetyHandler &Handler) const = 0;
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000145 virtual void handleLock(FactSet &FSet, FactManager &FactMan,
146 const FactEntry &entry, ThreadSafetyHandler &Handler,
147 StringRef DiagKind) const = 0;
Ed Schoutenca988742014-09-03 06:00:11 +0000148 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
149 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
150 bool FullyRemove, ThreadSafetyHandler &Handler,
151 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000152
DeLesley Hutchins42665222014-08-04 16:10:59 +0000153 // Return true if LKind >= LK, where exclusive > shared
Aaron Puchert969f32d2018-09-21 23:08:30 +0000154 bool isAtLeast(LockKind LK) const {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000155 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000156 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000157};
158
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000159using FactID = unsigned short;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000161/// FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000162/// the analysis of a single routine.
163class FactManager {
164private:
Aaron Puchert969f32d2018-09-21 23:08:30 +0000165 std::vector<std::unique_ptr<const FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000166
167public:
Ed Schoutenca988742014-09-03 06:00:11 +0000168 FactID newFact(std::unique_ptr<FactEntry> Entry) {
169 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000170 return static_cast<unsigned short>(Facts.size() - 1);
171 }
172
Ed Schoutenca988742014-09-03 06:00:11 +0000173 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000174};
175
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000176/// A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000177/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000178/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000179/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000180/// locks, so we can get away with doing a linear search for lookup. Note
181/// that a hashtable or map is inappropriate in this case, because lookups
182/// may involve partial pattern matches, rather than exact matches.
183class FactSet {
184private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000185 using FactVec = SmallVector<FactID, 4>;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000186
187 FactVec FactIDs;
188
189public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000190 using iterator = FactVec::iterator;
191 using const_iterator = FactVec::const_iterator;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000192
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000193 iterator begin() { return FactIDs.begin(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000194 const_iterator begin() const { return FactIDs.begin(); }
195
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000196 iterator end() { return FactIDs.end(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000197 const_iterator end() const { return FactIDs.end(); }
198
199 bool isEmpty() const { return FactIDs.size() == 0; }
200
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000201 // Return true if the set contains only negative facts
202 bool isEmpty(FactManager &FactMan) const {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000203 for (const auto FID : *this) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000204 if (!FactMan[FID].negative())
205 return false;
206 }
207 return true;
208 }
209
210 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
211
Ed Schoutenca988742014-09-03 06:00:11 +0000212 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
213 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000214 FactIDs.push_back(F);
215 return F;
216 }
217
DeLesley Hutchins42665222014-08-04 16:10:59 +0000218 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000219 unsigned n = FactIDs.size();
220 if (n == 0)
221 return false;
222
223 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000224 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000225 FactIDs[i] = FactIDs[n-1];
226 FactIDs.pop_back();
227 return true;
228 }
229 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000230 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000231 FactIDs.pop_back();
232 return true;
233 }
234 return false;
235 }
236
DeLesley Hutchins42665222014-08-04 16:10:59 +0000237 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000238 return 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 Hutchins3b2c66b2013-05-20 17:57:55 +0000241 }
242
Aaron Puchert969f32d2018-09-21 23:08:30 +0000243 const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000244 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000245 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000246 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000247 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000248 }
249
Aaron Puchert969f32d2018-09-21 23:08:30 +0000250 const FactEntry *findLockUniv(FactManager &FM,
251 const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000252 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000253 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000254 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000255 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000256 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000257
Aaron Puchert969f32d2018-09-21 23:08:30 +0000258 const FactEntry *findPartialMatch(FactManager &FM,
259 const CapabilityExpr &CapE) const {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000260 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000261 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000262 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000263 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000264 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000265
266 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
267 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
268 return FM[ID].valueDecl() == Vd;
269 });
270 return I != end();
271 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000272};
273
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000274class ThreadSafetyAnalyzer;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000275
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000276} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000277
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000278namespace clang {
279namespace threadSafety {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000280
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000281class BeforeSet {
282private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000283 using BeforeVect = SmallVector<const ValueDecl *, 4>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000284
285 struct BeforeInfo {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000286 BeforeVect Vect;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000287 int Visited = 0;
288
289 BeforeInfo() = default;
290 BeforeInfo(BeforeInfo &&) = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000291 };
292
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000293 using BeforeMap =
294 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
295 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000296
297public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000298 BeforeSet() = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000299
300 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
301 ThreadSafetyAnalyzer& Analyzer);
302
Reid Kleckner19ff5602015-11-20 19:08:30 +0000303 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
304 ThreadSafetyAnalyzer &Analyzer);
305
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000306 void checkBeforeAfter(const ValueDecl* Vd,
307 const FactSet& FSet,
308 ThreadSafetyAnalyzer& Analyzer,
309 SourceLocation Loc, StringRef CapKind);
310
311private:
312 BeforeMap BMap;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000313 CycleMap CycMap;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000314};
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000315
316} // namespace threadSafety
317} // namespace clang
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000318
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000319namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000320
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000321class LocalVariableMap;
322
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000323using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
324
Richard Smith92286672012-02-03 04:45:26 +0000325/// A side (entry or exit) of a CFG node.
326enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000327
328/// CFGBlockInfo is a struct which contains all the information that is
329/// maintained for each block in the CFG. See LocalVariableMap for more
330/// information about the contexts.
331struct CFGBlockInfo {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000332 // Lockset held at entry to block
333 FactSet EntrySet;
334
335 // Lockset held at exit from block
336 FactSet ExitSet;
337
338 // Context held at entry to block
339 LocalVarContext EntryContext;
340
341 // Context held at exit from block
342 LocalVarContext ExitContext;
343
344 // Location of first statement in block
345 SourceLocation EntryLoc;
346
347 // Location of last statement in block.
348 SourceLocation ExitLoc;
349
350 // Used to replay contexts later
351 unsigned EntryIndex;
352
353 // Is this block reachable?
354 bool Reachable = false;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000355
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000356 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000357 return Side == CBS_Entry ? EntrySet : ExitSet;
358 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000359
Richard Smith92286672012-02-03 04:45:26 +0000360 SourceLocation getLocation(CFGBlockSide Side) const {
361 return Side == CBS_Entry ? EntryLoc : ExitLoc;
362 }
363
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000364private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000365 CFGBlockInfo(LocalVarContext EmptyCtx)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000366 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000367
368public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000369 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000370};
371
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000372// A LocalVariableMap maintains a map from local variables to their currently
373// valid definitions. It provides SSA-like functionality when traversing the
374// CFG. Like SSA, each definition or assignment to a variable is assigned a
375// unique name (an integer), which acts as the SSA name for that definition.
376// The total set of names is shared among all CFG basic blocks.
377// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
378// with their SSA-names. Instead, we compute a Context for each point in the
379// code, which maps local variables to the appropriate SSA-name. This map
380// changes with each assignment.
381//
382// The map is computed in a single pass over the CFG. Subsequent analyses can
383// then query the map to find the appropriate Context for a statement, and use
384// that Context to look up the definitions of variables.
385class LocalVariableMap {
386public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000387 using Context = LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000388
389 /// A VarDefinition consists of an expression, representing the value of the
390 /// variable, along with the context in which that expression should be
391 /// interpreted. A reference VarDefinition does not itself contain this
392 /// information, but instead contains a pointer to a previous VarDefinition.
393 struct VarDefinition {
394 public:
395 friend class LocalVariableMap;
396
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000397 // The original declaration for this variable.
398 const NamedDecl *Dec;
399
400 // The expression for this variable, OR
401 const Expr *Exp = nullptr;
402
403 // Reference to another VarDefinition
404 unsigned Ref = 0;
405
406 // The map with which Exp should be interpreted.
407 Context Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000408
409 bool isReference() { return !Exp; }
410
411 private:
412 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000413 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000414 : Dec(D), Exp(E), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000415
416 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000417 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000418 : Dec(D), Ref(R), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000419 };
420
421private:
422 Context::Factory ContextFactory;
423 std::vector<VarDefinition> VarDefinitions;
424 std::vector<unsigned> CtxIndices;
Aaron Puchertcd37c092018-08-23 21:53:04 +0000425 std::vector<std::pair<const Stmt *, Context>> SavedContexts;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000426
427public:
428 LocalVariableMap() {
429 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000430 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000431 }
432
433 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000434 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000435 const unsigned *i = Ctx.lookup(D);
436 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000437 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000438 assert(*i < VarDefinitions.size());
439 return &VarDefinitions[*i];
440 }
441
442 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000443 /// NULL if the expression is not statically known. If successful, also
444 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000445 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000446 const unsigned *P = Ctx.lookup(D);
447 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000448 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000449
450 unsigned i = *P;
451 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000452 if (VarDefinitions[i].Exp) {
453 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000454 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000455 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000456 i = VarDefinitions[i].Ref;
457 }
Craig Topper25542942014-05-20 04:30:07 +0000458 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000459 }
460
461 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
462
463 /// Return the next context after processing S. This function is used by
464 /// clients of the class to get the appropriate context when traversing the
465 /// CFG. It must be called for every assignment or DeclStmt.
Aaron Puchertcd37c092018-08-23 21:53:04 +0000466 Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000467 if (SavedContexts[CtxIndex+1].first == S) {
468 CtxIndex++;
469 Context Result = SavedContexts[CtxIndex].second;
470 return Result;
471 }
472 return C;
473 }
474
475 void dumpVarDefinitionName(unsigned i) {
476 if (i == 0) {
477 llvm::errs() << "Undefined";
478 return;
479 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000480 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000481 if (!Dec) {
482 llvm::errs() << "<<NULL>>";
483 return;
484 }
485 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000486 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000487 }
488
489 /// Dumps an ASCII representation of the variable map to llvm::errs()
490 void dump() {
491 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000492 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000493 unsigned Ref = VarDefinitions[i].Ref;
494
495 dumpVarDefinitionName(i);
496 llvm::errs() << " = ";
497 if (Exp) Exp->dump();
498 else {
499 dumpVarDefinitionName(Ref);
500 llvm::errs() << "\n";
501 }
502 }
503 }
504
505 /// Dumps an ASCII representation of a Context to llvm::errs()
506 void dumpContext(Context C) {
507 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000508 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000509 D->printName(llvm::errs());
510 const unsigned *i = C.lookup(D);
511 llvm::errs() << " -> ";
512 dumpVarDefinitionName(*i);
513 llvm::errs() << "\n";
514 }
515 }
516
517 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000518 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
519 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000520
521protected:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000522 friend class VarMapBuilder;
523
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000524 // Get the current context index
525 unsigned getContextIndex() { return SavedContexts.size()-1; }
526
527 // Save the current context for later replay
Aaron Puchertcd37c092018-08-23 21:53:04 +0000528 void saveContext(const Stmt *S, Context C) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000529 SavedContexts.push_back(std::make_pair(S, C));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000530 }
531
532 // Adds a new definition to the given context, and returns a new context.
533 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000534 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000535 assert(!Ctx.contains(D));
536 unsigned newID = VarDefinitions.size();
537 Context NewCtx = ContextFactory.add(Ctx, D, newID);
538 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
539 return NewCtx;
540 }
541
542 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000543 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000544 unsigned newID = VarDefinitions.size();
545 Context NewCtx = ContextFactory.add(Ctx, D, newID);
546 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
547 return NewCtx;
548 }
549
550 // Updates a definition only if that definition is already in the map.
551 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000552 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000553 if (Ctx.contains(D)) {
554 unsigned newID = VarDefinitions.size();
555 Context NewCtx = ContextFactory.remove(Ctx, D);
556 NewCtx = ContextFactory.add(NewCtx, D, newID);
557 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
558 return NewCtx;
559 }
560 return Ctx;
561 }
562
563 // Removes a definition from the context, but keeps the variable name
564 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000565 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000566 Context NewCtx = Ctx;
567 if (NewCtx.contains(D)) {
568 NewCtx = ContextFactory.remove(NewCtx, D);
569 NewCtx = ContextFactory.add(NewCtx, D, 0);
570 }
571 return NewCtx;
572 }
573
574 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000575 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000576 Context NewCtx = Ctx;
577 if (NewCtx.contains(D)) {
578 NewCtx = ContextFactory.remove(NewCtx, D);
579 }
580 return NewCtx;
581 }
582
583 Context intersectContexts(Context C1, Context C2);
584 Context createReferenceContext(Context C);
585 void intersectBackEdge(Context C1, Context C2);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000586};
587
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000588} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000589
590// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000591CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
592 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000593}
594
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000595namespace {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000596
597/// Visitor which builds a LocalVariableMap
Aaron Puchertcd37c092018-08-23 21:53:04 +0000598class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000599public:
600 LocalVariableMap* VMap;
601 LocalVariableMap::Context Ctx;
602
603 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000604 : VMap(VM), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000605
Aaron Puchertcd37c092018-08-23 21:53:04 +0000606 void VisitDeclStmt(const DeclStmt *S);
607 void VisitBinaryOperator(const BinaryOperator *BO);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000608};
609
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000610} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000611
612// Add new local variables to the variable map
Aaron Puchertcd37c092018-08-23 21:53:04 +0000613void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000614 bool modifiedCtx = false;
Aaron Puchertcd37c092018-08-23 21:53:04 +0000615 const DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000616 for (const auto *D : DGrp) {
617 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
618 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000619
620 // Add local variables with trivial type to the variable map
621 QualType T = VD->getType();
622 if (T.isTrivialType(VD->getASTContext())) {
623 Ctx = VMap->addDefinition(VD, E, Ctx);
624 modifiedCtx = true;
625 }
626 }
627 }
628 if (modifiedCtx)
629 VMap->saveContext(S, Ctx);
630}
631
632// Update local variable definitions in variable map
Aaron Puchertcd37c092018-08-23 21:53:04 +0000633void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000634 if (!BO->isAssignmentOp())
635 return;
636
637 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
638
639 // Update the variable map and current context.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000640 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
641 const ValueDecl *VDec = DRE->getDecl();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000642 if (Ctx.lookup(VDec)) {
643 if (BO->getOpcode() == BO_Assign)
644 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
645 else
646 // FIXME -- handle compound assignment operators
647 Ctx = VMap->clearDefinition(VDec, Ctx);
648 VMap->saveContext(BO, Ctx);
649 }
650 }
651}
652
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000653// Computes the intersection of two contexts. The intersection is the
654// set of variables which have the same definition in both contexts;
655// variables with different definitions are discarded.
656LocalVariableMap::Context
657LocalVariableMap::intersectContexts(Context C1, Context C2) {
658 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000659 for (const auto &P : C1) {
660 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000661 const unsigned *i2 = C2.lookup(Dec);
662 if (!i2) // variable doesn't exist on second path
663 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000664 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000665 Result = clearDefinition(Dec, Result);
666 }
667 return Result;
668}
669
670// For every variable in C, create a new variable that refers to the
671// definition in C. Return a new context that contains these new variables.
672// (We use this for a naive implementation of SSA on loop back-edges.)
673LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
674 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000675 for (const auto &P : C)
676 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000677 return Result;
678}
679
680// This routine also takes the intersection of C1 and C2, but it does so by
681// altering the VarDefinitions. C1 must be the result of an earlier call to
682// createReferenceContext.
683void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000684 for (const auto &P : C1) {
685 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000686 VarDefinition *VDef = &VarDefinitions[i1];
687 assert(VDef->isReference());
688
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000689 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000690 if (!i2 || (*i2 != i1))
691 VDef->Ref = 0; // Mark this variable as undefined
692 }
693}
694
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000695// Traverse the CFG in topological order, so all predecessors of a block
696// (excluding back-edges) are visited before the block itself. At
697// each point in the code, we calculate a Context, which holds the set of
698// variable definitions which are visible at that point in execution.
699// Visible variables are mapped to their definitions using an array that
700// contains all definitions.
701//
702// At join points in the CFG, the set is computed as the intersection of
703// the incoming sets along each edge, E.g.
704//
705// { Context | VarDefinitions }
706// int x = 0; { x -> x1 | x1 = 0 }
707// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
708// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
709// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
710// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
711//
712// This is essentially a simpler and more naive version of the standard SSA
713// algorithm. Those definitions that remain in the intersection are from blocks
714// that strictly dominate the current block. We do not bother to insert proper
715// phi nodes, because they are not used in our analysis; instead, wherever
716// a phi node would be required, we simply remove that definition from the
717// context (E.g. x above).
718//
719// The initial traversal does not capture back-edges, so those need to be
720// handled on a separate pass. Whenever the first pass encounters an
721// incoming back edge, it duplicates the context, creating new definitions
722// that refer back to the originals. (These correspond to places where SSA
723// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000724// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000725// node was actually required.) E.g.
726//
727// { Context | VarDefinitions }
728// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
729// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
730// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
731// ... { y -> y1 | x3 = 2, x2 = 1, ... }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000732void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000733 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000734 std::vector<CFGBlockInfo> &BlockInfo) {
735 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
736
737 CtxIndices.resize(CFGraph->getNumBlockIDs());
738
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000739 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000740 int CurrBlockID = CurrBlock->getBlockID();
741 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
742
743 VisitedBlocks.insert(CurrBlock);
744
745 // Calculate the entry context for the current block
746 bool HasBackEdges = false;
747 bool CtxInit = true;
748 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
749 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
750 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000751 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000752 HasBackEdges = true;
753 continue;
754 }
755
756 int PrevBlockID = (*PI)->getBlockID();
757 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
758
759 if (CtxInit) {
760 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
761 CtxInit = false;
762 }
763 else {
764 CurrBlockInfo->EntryContext =
765 intersectContexts(CurrBlockInfo->EntryContext,
766 PrevBlockInfo->ExitContext);
767 }
768 }
769
770 // Duplicate the context if we have back-edges, so we can call
771 // intersectBackEdges later.
772 if (HasBackEdges)
773 CurrBlockInfo->EntryContext =
774 createReferenceContext(CurrBlockInfo->EntryContext);
775
776 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000777 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000778 CurrBlockInfo->EntryIndex = getContextIndex();
779
780 // Visit all the statements in the basic block.
781 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000782 for (const auto &BI : *CurrBlock) {
783 switch (BI.getKind()) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000784 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000785 CFGStmt CS = BI.castAs<CFGStmt>();
Aaron Puchertcd37c092018-08-23 21:53:04 +0000786 VMapBuilder.Visit(CS.getStmt());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000787 break;
788 }
789 default:
790 break;
791 }
792 }
793 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
794
795 // Mark variables on back edges as "unknown" if they've been changed.
796 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
797 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
798 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000799 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000800 continue;
801
802 CFGBlock *FirstLoopBlock = *SI;
803 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
804 Context LoopEnd = CurrBlockInfo->ExitContext;
805 intersectBackEdge(LoopBegin, LoopEnd);
806 }
807 }
808
809 // Put an extra entry at the end of the indexed context array
810 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000811 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000812}
813
Richard Smith92286672012-02-03 04:45:26 +0000814/// Find the appropriate source locations to use when producing diagnostics for
815/// each block in the CFG.
816static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000817 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000818 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000819 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000820 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
821
822 // Find the source location of the last statement in the block, if the
823 // block is not empty.
824 if (const Stmt *S = CurrBlock->getTerminator()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000825 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000826 } else {
827 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
828 BE = CurrBlock->rend(); BI != BE; ++BI) {
829 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000830 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000831 CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000832 break;
833 }
834 }
835 }
836
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000837 if (CurrBlockInfo->ExitLoc.isValid()) {
Richard Smith92286672012-02-03 04:45:26 +0000838 // This block contains at least one statement. Find the source location
839 // of the first statement in the block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000840 for (const auto &BI : *CurrBlock) {
Richard Smith92286672012-02-03 04:45:26 +0000841 // FIXME: Handle other CFGElement kinds.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000842 if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000843 CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000844 break;
845 }
846 }
847 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
848 CurrBlock != &CFGraph->getExit()) {
849 // The block is empty, and has a single predecessor. Use its exit
850 // location.
851 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
852 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
853 }
854 }
855}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000856
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000857namespace {
858
Ed Schoutenca988742014-09-03 06:00:11 +0000859class LockableFactEntry : public FactEntry {
860private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000861 /// managed by ScopedLockable object
862 bool Managed;
Ed Schoutenca988742014-09-03 06:00:11 +0000863
864public:
865 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
866 bool Mng = false, bool Asrt = false)
867 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
868
869 void
870 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
871 SourceLocation JoinLoc, LockErrorKind LEK,
872 ThreadSafetyHandler &Handler) const override {
873 if (!Managed && !asserted() && !negative() && !isUniversal()) {
874 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
875 LEK);
876 }
877 }
878
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000879 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
880 ThreadSafetyHandler &Handler,
881 StringRef DiagKind) const override {
882 Handler.handleDoubleLock(DiagKind, entry.toString(), entry.loc());
883 }
884
Ed Schoutenca988742014-09-03 06:00:11 +0000885 void handleUnlock(FactSet &FSet, FactManager &FactMan,
886 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
887 bool FullyRemove, ThreadSafetyHandler &Handler,
888 StringRef DiagKind) const override {
889 FSet.removeLock(FactMan, Cp);
890 if (!Cp.negative()) {
891 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
892 !Cp, LK_Exclusive, UnlockLoc));
893 }
894 }
895};
896
897class ScopedLockableFactEntry : public FactEntry {
898private:
899 SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
900
901public:
902 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
903 const CapExprSet &Excl, const CapExprSet &Shrd)
904 : FactEntry(CE, LK_Exclusive, Loc, false) {
905 for (const auto &M : Excl)
906 UnderlyingMutexes.push_back(M.sexpr());
907 for (const auto &M : Shrd)
908 UnderlyingMutexes.push_back(M.sexpr());
909 }
910
911 void
912 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
913 SourceLocation JoinLoc, LockErrorKind LEK,
914 ThreadSafetyHandler &Handler) const override {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000915 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
Ed Schoutenca988742014-09-03 06:00:11 +0000916 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
917 // If this scoped lock manages another mutex, and if the underlying
918 // mutex is still held, then warn about the underlying mutex.
919 Handler.handleMutexHeldEndOfScope(
920 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
921 }
922 }
923 }
924
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000925 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
926 ThreadSafetyHandler &Handler,
927 StringRef DiagKind) const override {
928 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
929 CapabilityExpr UnderCp(UnderlyingMutex, false);
930
931 // We're relocking the underlying mutexes. Warn on double locking.
Aaron Puchert68c7fcd2018-08-23 21:13:32 +0000932 if (FSet.findLock(FactMan, UnderCp)) {
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000933 Handler.handleDoubleLock(DiagKind, UnderCp.toString(), entry.loc());
Aaron Puchert68c7fcd2018-08-23 21:13:32 +0000934 } else {
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000935 FSet.removeLock(FactMan, !UnderCp);
936 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
937 UnderCp, entry.kind(), entry.loc()));
938 }
939 }
940 }
941
Ed Schoutenca988742014-09-03 06:00:11 +0000942 void handleUnlock(FactSet &FSet, FactManager &FactMan,
943 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
944 bool FullyRemove, ThreadSafetyHandler &Handler,
945 StringRef DiagKind) const override {
946 assert(!Cp.negative() && "Managing object cannot be negative.");
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000947 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
Ed Schoutenca988742014-09-03 06:00:11 +0000948 CapabilityExpr UnderCp(UnderlyingMutex, false);
949 auto UnderEntry = llvm::make_unique<LockableFactEntry>(
950 !UnderCp, LK_Exclusive, UnlockLoc);
951
952 if (FullyRemove) {
953 // We're destroying the managing object.
954 // Remove the underlying mutex if it exists; but don't warn.
955 if (FSet.findLock(FactMan, UnderCp)) {
956 FSet.removeLock(FactMan, UnderCp);
957 FSet.addLock(FactMan, std::move(UnderEntry));
958 }
959 } else {
960 // We're releasing the underlying mutex, but not destroying the
961 // managing object. Warn on dual release.
962 if (!FSet.findLock(FactMan, UnderCp)) {
963 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
964 UnlockLoc);
965 }
966 FSet.removeLock(FactMan, UnderCp);
967 FSet.addLock(FactMan, std::move(UnderEntry));
968 }
969 }
970 if (FullyRemove)
971 FSet.removeLock(FactMan, Cp);
972 }
973};
974
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000975/// Class which implements the core thread safety analysis routines.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000976class ThreadSafetyAnalyzer {
977 friend class BuildLockset;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000978 friend class threadSafety::BeforeSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000979
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000980 llvm::BumpPtrAllocator Bpa;
981 threadSafety::til::MemRegionRef Arena;
982 threadSafety::SExprBuilder SxBuilder;
983
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000984 ThreadSafetyHandler &Handler;
985 const CXXMethodDecl *CurrentMethod;
986 LocalVariableMap LocalVarMap;
987 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000988 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000989
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000990 BeforeSet *GlobalBeforeSet;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000991
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000992public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000993 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000994 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000995
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000996 bool inCurrentScope(const CapabilityExpr &CapE);
997
Ed Schoutenca988742014-09-03 06:00:11 +0000998 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
999 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001000 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001001 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
1002 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001003
1004 template <typename AttrType>
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001005 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +00001006 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001007
1008 template <class AttrType>
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001009 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001010 const NamedDecl *D,
1011 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1012 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001013
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001014 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1015 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001016
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001017 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1018 const CFGBlock* PredBlock,
1019 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001020
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001021 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1022 SourceLocation JoinLoc,
1023 LockErrorKind LEK1, LockErrorKind LEK2,
1024 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001025
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001026 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1027 SourceLocation JoinLoc, LockErrorKind LEK1,
1028 bool Modify=true) {
1029 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001030 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001031
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001032 void runAnalysis(AnalysisDeclContext &AC);
1033};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001034
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001035} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001036
1037/// Process acquired_before and acquired_after attributes on Vd.
1038BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1039 ThreadSafetyAnalyzer& Analyzer) {
1040 // Create a new entry for Vd.
Reid Kleckner19ff5602015-11-20 19:08:30 +00001041 BeforeInfo *Info = nullptr;
1042 {
1043 // Keep InfoPtr in its own scope in case BMap is modified later and the
1044 // reference becomes invalid.
1045 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1046 if (!InfoPtr)
1047 InfoPtr.reset(new BeforeInfo());
1048 Info = InfoPtr.get();
1049 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001050
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001051 for (const auto *At : Vd->attrs()) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001052 switch (At->getKind()) {
1053 case attr::AcquiredBefore: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001054 const auto *A = cast<AcquiredBeforeAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001055
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001056 // Read exprs from the attribute, and add them to BeforeVect.
1057 for (const auto *Arg : A->args()) {
1058 CapabilityExpr Cp =
1059 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1060 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
Reid Kleckner19ff5602015-11-20 19:08:30 +00001061 Info->Vect.push_back(Cpvd);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001062 const auto It = BMap.find(Cpvd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001063 if (It == BMap.end())
1064 insertAttrExprs(Cpvd, Analyzer);
1065 }
1066 }
1067 break;
1068 }
1069 case attr::AcquiredAfter: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001070 const auto *A = cast<AcquiredAfterAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001071
1072 // Read exprs from the attribute, and add them to BeforeVect.
1073 for (const auto *Arg : A->args()) {
1074 CapabilityExpr Cp =
1075 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1076 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1077 // Get entry for mutex listed in attribute
Reid Kleckner19ff5602015-11-20 19:08:30 +00001078 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1079 ArgInfo->Vect.push_back(Vd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001080 }
1081 }
1082 break;
1083 }
1084 default:
1085 break;
1086 }
1087 }
1088
1089 return Info;
1090}
1091
Reid Kleckner19ff5602015-11-20 19:08:30 +00001092BeforeSet::BeforeInfo *
1093BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1094 ThreadSafetyAnalyzer &Analyzer) {
1095 auto It = BMap.find(Vd);
1096 BeforeInfo *Info = nullptr;
1097 if (It == BMap.end())
1098 Info = insertAttrExprs(Vd, Analyzer);
1099 else
1100 Info = It->second.get();
1101 assert(Info && "BMap contained nullptr?");
1102 return Info;
1103}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001104
1105/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1106void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1107 const FactSet& FSet,
1108 ThreadSafetyAnalyzer& Analyzer,
1109 SourceLocation Loc, StringRef CapKind) {
1110 SmallVector<BeforeInfo*, 8> InfoVect;
1111
1112 // Do a depth-first traversal of Vd.
1113 // Return true if there are cycles.
1114 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1115 if (!Vd)
1116 return false;
1117
Reid Kleckner19ff5602015-11-20 19:08:30 +00001118 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001119
1120 if (Info->Visited == 1)
1121 return true;
1122
1123 if (Info->Visited == 2)
1124 return false;
1125
Reid Kleckner19ff5602015-11-20 19:08:30 +00001126 if (Info->Vect.empty())
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001127 return false;
1128
1129 InfoVect.push_back(Info);
1130 Info->Visited = 1;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001131 for (const auto *Vdb : Info->Vect) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001132 // Exclude mutexes in our immediate before set.
1133 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1134 StringRef L1 = StartVd->getName();
1135 StringRef L2 = Vdb->getName();
1136 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1137 }
1138 // Transitively search other before sets, and warn on cycles.
1139 if (traverse(Vdb)) {
1140 if (CycMap.find(Vd) == CycMap.end()) {
1141 CycMap.insert(std::make_pair(Vd, true));
1142 StringRef L1 = Vd->getName();
1143 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1144 }
1145 }
1146 }
1147 Info->Visited = 2;
1148 return false;
1149 };
1150
1151 traverse(StartVd);
1152
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001153 for (auto *Info : InfoVect)
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001154 Info->Visited = 0;
1155}
1156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001157/// Gets the value decl pointer from DeclRefExprs or MemberExprs.
Aaron Ballmane0449042014-04-01 21:43:23 +00001158static const ValueDecl *getValueDecl(const Expr *Exp) {
1159 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1160 return getValueDecl(CE->getSubExpr());
1161
1162 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1163 return DR->getDecl();
1164
1165 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1166 return ME->getMemberDecl();
1167
1168 return nullptr;
1169}
1170
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001171namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001172
Aaron Ballmane0449042014-04-01 21:43:23 +00001173template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001174class has_arg_iterator_range {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001175 using yes = char[1];
1176 using no = char[2];
Aaron Ballmane0449042014-04-01 21:43:23 +00001177
1178 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001179 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001180
1181 template <typename>
1182 static no& test(...);
1183
1184public:
1185 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1186};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001187
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001188} // namespace
Aaron Ballmane0449042014-04-01 21:43:23 +00001189
1190static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1191 return A->getName();
1192}
1193
1194static StringRef ClassifyDiagnostic(QualType VDT) {
1195 // We need to look at the declaration of the type of the value to determine
1196 // which it is. The type should either be a record or a typedef, or a pointer
1197 // or reference thereof.
1198 if (const auto *RT = VDT->getAs<RecordType>()) {
1199 if (const auto *RD = RT->getDecl())
1200 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1201 return ClassifyDiagnostic(CA);
1202 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1203 if (const auto *TD = TT->getDecl())
1204 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1205 return ClassifyDiagnostic(CA);
1206 } else if (VDT->isPointerType() || VDT->isReferenceType())
1207 return ClassifyDiagnostic(VDT->getPointeeType());
1208
1209 return "mutex";
1210}
1211
1212static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1213 assert(VD && "No ValueDecl passed");
1214
1215 // The ValueDecl is the declaration of a mutex or role (hopefully).
1216 return ClassifyDiagnostic(VD->getType());
1217}
1218
1219template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001220static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001221 StringRef>::type
1222ClassifyDiagnostic(const AttrTy *A) {
1223 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1224 return ClassifyDiagnostic(VD);
1225 return "mutex";
1226}
1227
1228template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001229static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001230 StringRef>::type
1231ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001232 for (const auto *Arg : A->args()) {
1233 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001234 return ClassifyDiagnostic(VD);
1235 }
1236 return "mutex";
1237}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001238
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001239bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001240 if (!CurrentMethod)
1241 return false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001242 if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1243 const auto *VD = P->clangDecl();
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001244 if (VD)
1245 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1246 }
1247 return false;
1248}
1249
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001250/// Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001251/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001252void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1253 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001254 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001255 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001256 return;
1257
Ed Schoutenca988742014-09-03 06:00:11 +00001258 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001259 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001260 CapabilityExpr NegC = !*Entry;
Aaron Puchert969f32d2018-09-21 23:08:30 +00001261 const FactEntry *Nen = FSet.findLock(FactMan, NegC);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001262 if (Nen) {
1263 FSet.removeLock(FactMan, NegC);
1264 }
1265 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001266 if (inCurrentScope(*Entry) && !Entry->asserted())
1267 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1268 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001269 }
1270 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001271
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001272 // Check before/after constraints
1273 if (Handler.issueBetaWarnings() &&
1274 !Entry->asserted() && !Entry->declared()) {
1275 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1276 Entry->loc(), DiagKind);
1277 }
1278
DeLesley Hutchins42665222014-08-04 16:10:59 +00001279 // FIXME: Don't always warn when we have support for reentrant locks.
Aaron Puchert969f32d2018-09-21 23:08:30 +00001280 if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
Ed Schoutenca988742014-09-03 06:00:11 +00001281 if (!Entry->asserted())
Aaron Puchertc3e37b72018-08-22 22:14:53 +00001282 Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001283 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001284 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001285 }
1286}
1287
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001288/// Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001289/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001290void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001291 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001292 bool FullyRemove, LockKind ReceivedKind,
1293 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001294 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001295 return;
1296
DeLesley Hutchins42665222014-08-04 16:10:59 +00001297 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001298 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001299 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001300 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001301 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001302
Aaron Ballmandf115d92014-03-21 14:48:48 +00001303 // Generic lock removal doesn't care about lock kind mismatches, but
1304 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001305 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1306 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1307 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001308 }
1309
Ed Schoutenca988742014-09-03 06:00:11 +00001310 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1311 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001312}
1313
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001314/// Extract the list of mutexIDs from the attribute on an expression,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001315/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001316template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001317void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001318 const Expr *Exp, const NamedDecl *D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001319 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001320 if (Attr->args_size() == 0) {
1321 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001322 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1323 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001324 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1325 return;
1326 }
1327 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001328 if (!Cp.shouldIgnore())
1329 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001330 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001331 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001332
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001333 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001334 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1335 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001336 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001337 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001338 }
1339 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001340 if (!Cp.shouldIgnore())
1341 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001342 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001343}
1344
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001345/// Extract the list of mutexIDs from a trylock attribute. If the
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001346/// trylock applies to the given edge, then push them onto Mtxs, discarding
1347/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001348template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001349void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001350 const Expr *Exp, const NamedDecl *D,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001351 const CFGBlock *PredBlock,
1352 const CFGBlock *CurrBlock,
1353 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001354 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001355 bool branch = false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001356 if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001357 branch = BLE->getValue();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001358 else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001359 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001360
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001361 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001362 if (Neg)
1363 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001364
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001365 // If we've taken the trylock branch, then add the lock
1366 int i = 0;
1367 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1368 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001369 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001370 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001371 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001372}
1373
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001374static bool getStaticBooleanValue(Expr *E, bool &TCond) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001375 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1376 TCond = false;
1377 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001378 } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001379 TCond = BLE->getValue();
1380 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001381 } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001382 TCond = ILE->getValue().getBoolValue();
1383 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001384 } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001385 return getStaticBooleanValue(CE->getSubExpr(), TCond);
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001386 return false;
1387}
1388
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001389// If Cond can be traced back to a function call, return the call expression.
1390// The negate variable should be called with false, and will be set to true
1391// if the function call is negated, e.g. if (!mu.tryLock(...))
1392const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1393 LocalVarContext C,
1394 bool &Negate) {
1395 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001396 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001397
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001398 if (const auto *CallExp = dyn_cast<CallExpr>(Cond))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001399 return CallExp;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001400 else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001401 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001402 else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001403 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001404 else if (const auto *EWC = dyn_cast<ExprWithCleanups>(Cond))
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001405 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001406 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001407 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1408 return getTrylockCallExpr(E, C, Negate);
1409 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001410 else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001411 if (UOP->getOpcode() == UO_LNot) {
1412 Negate = !Negate;
1413 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1414 }
Craig Topper25542942014-05-20 04:30:07 +00001415 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001416 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001417 else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001418 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1419 if (BOP->getOpcode() == BO_NE)
1420 Negate = !Negate;
1421
1422 bool TCond = false;
1423 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1424 if (!TCond) Negate = !Negate;
1425 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1426 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001427 TCond = false;
1428 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001429 if (!TCond) Negate = !Negate;
1430 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1431 }
Craig Topper25542942014-05-20 04:30:07 +00001432 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001433 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001434 if (BOP->getOpcode() == BO_LAnd) {
1435 // LHS must have been evaluated in a different block.
1436 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1437 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001438 if (BOP->getOpcode() == BO_LOr)
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001439 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
Craig Topper25542942014-05-20 04:30:07 +00001440 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001441 }
Craig Topper25542942014-05-20 04:30:07 +00001442 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001443}
1444
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001445/// Find the lockset that holds on the edge between PredBlock
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001446/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1447/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001448void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1449 const FactSet &ExitSet,
1450 const CFGBlock *PredBlock,
1451 const CFGBlock *CurrBlock) {
1452 Result = ExitSet;
1453
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001454 const Stmt *Cond = PredBlock->getTerminatorCondition();
1455 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001456 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001457
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001458 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001459 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1460 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001461 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001462
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001463 const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001464 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001465 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001466
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001467 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001468 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001469 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001470
DeLesley Hutchins42665222014-08-04 16:10:59 +00001471 CapExprSet ExclusiveLocksToAdd;
1472 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001473
1474 // If the condition is a call to a Trylock function, then grab the attributes
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001475 for (const auto *Attr : FunDecl->attrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001476 switch (Attr->getKind()) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00001477 case attr::TryAcquireCapability: {
1478 auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1479 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1480 Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1481 Negate);
1482 CapDiagKind = ClassifyDiagnostic(A);
1483 break;
1484 };
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001485 case attr::ExclusiveTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001486 const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001487 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1488 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001489 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001490 break;
1491 }
1492 case attr::SharedTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001493 const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001494 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001495 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001496 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001497 break;
1498 }
1499 default:
1500 break;
1501 }
1502 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001503
1504 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001505 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001506 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001507 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1508 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001509 CapDiagKind);
1510 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001511 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1512 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001513 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001514}
1515
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001516namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001517
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001518/// We use this class to visit different types of expressions in
Caitlin Sadowski33208342011-09-09 16:11:56 +00001519/// CFGBlocks, and build up the lockset.
1520/// An expression may cause us to add or remove locks from the lockset, or else
1521/// output error messages related to missing locks.
1522/// FIXME: In future, we may be able to not inherit from a visitor.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001523class BuildLockset : public ConstStmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001524 friend class ThreadSafetyAnalyzer;
1525
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001526 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001527 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001528 LocalVariableMap::Context LVarCtx;
1529 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001530
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001531 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001532 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001533 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001534 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001535 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1536 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001537
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001538 void checkAccess(const Expr *Exp, AccessKind AK,
1539 ProtectedOperationKind POK = POK_VarAccess);
1540 void checkPtAccess(const Expr *Exp, AccessKind AK,
1541 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001542
Aaron Puchertcd37c092018-08-23 21:53:04 +00001543 void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001544
Caitlin Sadowski33208342011-09-09 16:11:56 +00001545public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001546 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
Aaron Puchertcd37c092018-08-23 21:53:04 +00001547 : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001548 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001549
Aaron Puchertcd37c092018-08-23 21:53:04 +00001550 void VisitUnaryOperator(const UnaryOperator *UO);
1551 void VisitBinaryOperator(const BinaryOperator *BO);
1552 void VisitCastExpr(const CastExpr *CE);
1553 void VisitCallExpr(const CallExpr *Exp);
1554 void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1555 void VisitDeclStmt(const DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001556};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001557
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001558} // namespace
DeLesley Hutchins42665222014-08-04 16:10:59 +00001559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001560/// Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001561/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001562void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001563 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001564 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001565 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001566 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001567
DeLesley Hutchins42665222014-08-04 16:10:59 +00001568 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1569 if (Cp.isInvalid()) {
1570 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001571 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001572 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001573 return;
1574 }
1575
DeLesley Hutchins42665222014-08-04 16:10:59 +00001576 if (Cp.negative()) {
1577 // Negative capabilities act like locks excluded
Aaron Puchert969f32d2018-09-21 23:08:30 +00001578 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001579 if (LDat) {
1580 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001581 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001582 return;
1583 }
1584
1585 // If this does not refer to a negative capability in the same class,
1586 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001587 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001588 return;
1589
1590 // Otherwise the negative requirement must be propagated to the caller.
1591 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1592 if (!LDat) {
1593 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001594 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001595 }
1596 return;
1597 }
1598
Aaron Puchert969f32d2018-09-21 23:08:30 +00001599 const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001600 bool NoError = true;
1601 if (!LDat) {
1602 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001603 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1604 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001605 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001606 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001607 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001608 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1609 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001610 } else {
1611 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001612 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1613 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001614 }
1615 NoError = false;
1616 }
1617 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001618 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001619 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1620 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001621 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001622}
1623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001624/// Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001625void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001626 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001627 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1628 if (Cp.isInvalid()) {
1629 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1630 return;
1631 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001632 return;
1633 }
1634
Aaron Puchert969f32d2018-09-21 23:08:30 +00001635 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001636 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001637 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001638 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1639 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001640}
1641
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001642/// Checks guarded_by and pt_guarded_by attributes.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001643/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1644/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1645/// Similarly, we check if the access is to an expression that dereferences
1646/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001647void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1648 ProtectedOperationKind POK) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00001649 Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001650
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001651 SourceLocation Loc = Exp->getExprLoc();
1652
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001653 // Local variables of reference type cannot be re-assigned;
1654 // map them to their initializer.
1655 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1656 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1657 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1658 if (const auto *E = VD->getInit()) {
Aaron Ballman57deab72018-08-24 18:48:35 +00001659 // Guard against self-initialization. e.g., int &i = i;
1660 if (E == Exp)
1661 break;
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001662 Exp = E;
1663 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001664 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001665 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001666 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001667 }
1668
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001669 if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001670 // For dereferences
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001671 if (UO->getOpcode() == UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001672 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001673 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001674 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001675
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001676 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001677 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001678 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001679 }
1680
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001681 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001682 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001683 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001684 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001685 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001686 }
1687
Caitlin Sadowski33208342011-09-09 16:11:56 +00001688 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001689 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001690 return;
1691
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001692 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001693 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001694 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001695
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001696 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001697 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001698 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001699}
1700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001701/// Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001702/// POK is the same operationKind that was passed to checkAccess.
1703void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1704 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001705 while (true) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001706 if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001707 Exp = PE->getSubExpr();
1708 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001709 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001710 if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001711 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1712 // If it's an actual array, and not a pointer, then it's elements
1713 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001714 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001715 return;
1716 }
1717 Exp = CE->getSubExpr();
1718 continue;
1719 }
1720 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001721 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001722
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001723 // Pass by reference warnings are under a different flag.
1724 ProtectedOperationKind PtPOK = POK_VarDereference;
1725 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1726
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001727 const ValueDecl *D = getValueDecl(Exp);
1728 if (!D || !D->hasAttrs())
1729 return;
1730
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001731 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001732 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001733 Exp->getExprLoc());
1734
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001735 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001736 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001737 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001738}
1739
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001740/// Process a function call, method call, constructor call,
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001741/// or destructor call. This involves looking at the attributes on the
1742/// corresponding function/method/constructor/destructor, issuing warnings,
1743/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001744///
1745/// FIXME: For classes annotated with one of the guarded annotations, we need
1746/// to treat const method calls as reads and non-const method calls as writes,
1747/// and check that the appropriate locks are held. Non-const method calls with
1748/// the same signature as const method calls can be also treated as reads.
1749///
Aaron Puchertcd37c092018-08-23 21:53:04 +00001750void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1751 VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001752 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001753 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1754 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001755 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
Aaron Ballmane0449042014-04-01 21:43:23 +00001756 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001757
Richard Smithe97654b2018-01-11 22:13:57 +00001758 // Figure out if we're constructing an object of scoped lockable class
Haojian Wu74e0f402018-08-13 12:50:30 +00001759 bool isScopedVar = false;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001760 if (VD) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001761 if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001762 const CXXRecordDecl* PD = CD->getParent();
1763 if (PD && PD->hasAttr<ScopedLockableAttr>())
Haojian Wu74e0f402018-08-13 12:50:30 +00001764 isScopedVar = true;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001765 }
1766 }
1767
Aaron Ballman1b587592018-07-26 13:03:16 +00001768 for(const Attr *At : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001769 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001770 // When we encounter a lock function, we need to add the lock to our
1771 // lockset.
1772 case attr::AcquireCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001773 const auto *A = cast<AcquireCapabilityAttr>(At);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001774 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1775 : ExclusiveLocksToAdd,
1776 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001777
1778 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001779 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001780 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001781
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001782 // An assert will add a lock to the lockset, but will not generate
1783 // a warning if it is already there, and will not generate a warning
1784 // if it is not removed.
1785 case attr::AssertExclusiveLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001786 const auto *A = cast<AssertExclusiveLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001787
DeLesley Hutchins42665222014-08-04 16:10:59 +00001788 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001789 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001790 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001791 Analyzer->addLock(FSet,
1792 llvm::make_unique<LockableFactEntry>(
1793 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001794 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001795 break;
1796 }
1797 case attr::AssertSharedLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001798 const auto *A = cast<AssertSharedLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001799
DeLesley Hutchins42665222014-08-04 16:10:59 +00001800 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001801 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001802 for (const auto &AssertLock : AssertLocks)
Josh Gaoec1369e2017-08-08 19:44:34 +00001803 Analyzer->addLock(FSet,
1804 llvm::make_unique<LockableFactEntry>(
1805 AssertLock, LK_Shared, Loc, false, true),
1806 ClassifyDiagnostic(A));
1807 break;
1808 }
1809
1810 case attr::AssertCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001811 const auto *A = cast<AssertCapabilityAttr>(At);
Josh Gaoec1369e2017-08-08 19:44:34 +00001812 CapExprSet AssertLocks;
1813 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1814 for (const auto &AssertLock : AssertLocks)
1815 Analyzer->addLock(FSet,
1816 llvm::make_unique<LockableFactEntry>(
1817 AssertLock,
1818 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1819 false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001820 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001821 break;
1822 }
1823
Caitlin Sadowski33208342011-09-09 16:11:56 +00001824 // When we encounter an unlock function, we need to remove unlocked
1825 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001826 case attr::ReleaseCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001827 const auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001828 if (A->isGeneric())
1829 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1830 else if (A->isShared())
1831 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1832 else
1833 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001834
1835 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001836 break;
1837 }
1838
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001839 case attr::RequiresCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001840 const auto *A = cast<RequiresCapabilityAttr>(At);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001841 for (auto *Arg : A->args()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001842 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001843 POK_FunctionCall, ClassifyDiagnostic(A),
1844 Exp->getExprLoc());
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001845 // use for adopting a lock
Haojian Wu74e0f402018-08-13 12:50:30 +00001846 if (isScopedVar) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001847 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1848 : ScopedExclusiveReqs,
1849 A, Exp, D, VD);
1850 }
1851 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001852 break;
1853 }
1854
1855 case attr::LocksExcluded: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001856 const auto *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001857 for (auto *Arg : A->args())
1858 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001859 break;
1860 }
1861
Alp Tokerd4733632013-12-05 04:47:09 +00001862 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001863 default:
1864 break;
1865 }
1866 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001867
Aaron Ballman1b587592018-07-26 13:03:16 +00001868 // Remove locks first to allow lock upgrading/downgrading.
1869 // FIXME -- should only fully remove if the attribute refers to 'this'.
1870 bool Dtor = isa<CXXDestructorDecl>(D);
1871 for (const auto &M : ExclusiveLocksToRemove)
1872 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1873 for (const auto &M : SharedLocksToRemove)
1874 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1875 for (const auto &M : GenericLocksToRemove)
1876 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1877
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001878 // Add locks.
Haojian Wu74e0f402018-08-13 12:50:30 +00001879 for (const auto &M : ExclusiveLocksToAdd)
1880 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1881 M, LK_Exclusive, Loc, isScopedVar),
1882 CapDiagKind);
1883 for (const auto &M : SharedLocksToAdd)
1884 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1885 M, LK_Shared, Loc, isScopedVar),
1886 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001887
Haojian Wu74e0f402018-08-13 12:50:30 +00001888 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001889 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001890 SourceLocation MLoc = VD->getLocation();
1891 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001892 // FIXME: does this store a pointer to DRE?
1893 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001894
1895 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1896 std::back_inserter(ExclusiveLocksToAdd));
1897 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1898 std::back_inserter(SharedLocksToAdd));
Ed Schoutenca988742014-09-03 06:00:11 +00001899 Analyzer->addLock(FSet,
1900 llvm::make_unique<ScopedLockableFactEntry>(
1901 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1902 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001903 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001904}
1905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001906/// For unary operations which read and write a variable, we need to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001907/// check whether we hold any required mutexes. Reads are checked in
1908/// VisitCastExpr.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001909void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001910 switch (UO->getOpcode()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001911 case UO_PostDec:
1912 case UO_PostInc:
1913 case UO_PreDec:
1914 case UO_PreInc:
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001915 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001916 break;
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001917 default:
1918 break;
1919 }
1920}
1921
1922/// For binary operations which assign to a variable (writes), we need to check
1923/// whether we hold any required mutexes.
1924/// FIXME: Deal with non-primitive types.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001925void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001926 if (!BO->isAssignmentOp())
1927 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001928
1929 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001930 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001931
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001932 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001933}
1934
1935/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1936/// need to ensure we hold any required mutexes.
1937/// FIXME: Deal with non-primitive types.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001938void BuildLockset::VisitCastExpr(const CastExpr *CE) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001939 if (CE->getCastKind() != CK_LValueToRValue)
1940 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001941 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001942}
1943
Aaron Puchertcd37c092018-08-23 21:53:04 +00001944void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001945 bool ExamineArgs = true;
1946 bool OperatorFun = false;
1947
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001948 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1949 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001950 // ME can be null when calling a method pointer
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001951 const CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001952
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001953 if (ME && MD) {
1954 if (ME->isArrow()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001955 if (MD->isConst())
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001956 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001957 else // FIXME -- should be AK_Written
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001958 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001959 } else {
1960 if (MD->isConst())
1961 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1962 else // FIXME -- should be AK_Written
1963 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001964 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001965 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001966 } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001967 OperatorFun = true;
1968
1969 auto OEop = OE->getOperator();
1970 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001971 case OO_Equal: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001972 ExamineArgs = false;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001973 const Expr *Target = OE->getArg(0);
1974 const Expr *Source = OE->getArg(1);
1975 checkAccess(Target, AK_Written);
1976 checkAccess(Source, AK_Read);
1977 break;
1978 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001979 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001980 case OO_Arrow:
1981 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001982 const Expr *Obj = OE->getArg(0);
1983 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001984 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1985 // Grrr. operator* can be multiplication...
1986 checkPtAccess(Obj, AK_Read);
1987 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001988 break;
1989 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001990 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001991 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001992 const Expr *Obj = OE->getArg(0);
1993 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001994 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001995 }
1996 }
1997 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001998
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001999 if (ExamineArgs) {
Aaron Puchertcd37c092018-08-23 21:53:04 +00002000 if (const FunctionDecl *FD = Exp->getDirectCallee()) {
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002001 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
2002 // only turns off checking within the body of a function, but we also
2003 // use it to turn off checking in arguments to the function. This
2004 // could result in some false negatives, but the alternative is to
2005 // create yet another attribute.
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002006 if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
2007 unsigned Fn = FD->getNumParams();
2008 unsigned Cn = Exp->getNumArgs();
2009 unsigned Skip = 0;
2010
2011 unsigned i = 0;
2012 if (OperatorFun) {
2013 if (isa<CXXMethodDecl>(FD)) {
2014 // First arg in operator call is implicit self argument,
2015 // and doesn't appear in the FunctionDecl.
2016 Skip = 1;
2017 Cn--;
2018 } else {
2019 // Ignore the first argument of operators; it's been checked above.
2020 i = 1;
2021 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002022 }
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002023 // Ignore default arguments
2024 unsigned n = (Fn < Cn) ? Fn : Cn;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002025
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002026 for (; i < n; ++i) {
Aaron Puchertcd37c092018-08-23 21:53:04 +00002027 const ParmVarDecl *Pvd = FD->getParamDecl(i);
2028 const Expr *Arg = Exp->getArg(i + Skip);
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00002029 QualType Qt = Pvd->getType();
2030 if (Qt->isReferenceType())
2031 checkAccess(Arg, AK_Read, POK_PassByRef);
2032 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002033 }
2034 }
2035 }
2036
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002037 auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002038 if(!D || !D->hasAttrs())
2039 return;
2040 handleCall(Exp, D);
2041}
2042
Aaron Puchertcd37c092018-08-23 21:53:04 +00002043void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002044 const CXXConstructorDecl *D = Exp->getConstructor();
2045 if (D && D->isCopyConstructor()) {
2046 const Expr* Source = Exp->getArg(0);
2047 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002048 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002049 // FIXME -- only handles constructors in DeclStmt below.
2050}
2051
Richard Smithe97654b2018-01-11 22:13:57 +00002052static CXXConstructorDecl *
2053findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2054 // Prefer a move constructor over a copy constructor. If there's more than
2055 // one copy constructor or more than one move constructor, we arbitrarily
2056 // pick the first declared such constructor rather than trying to guess which
2057 // one is more appropriate.
2058 CXXConstructorDecl *CopyCtor = nullptr;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002059 for (auto *Ctor : RD->ctors()) {
Richard Smithe97654b2018-01-11 22:13:57 +00002060 if (Ctor->isDeleted())
2061 continue;
2062 if (Ctor->isMoveConstructor())
2063 return Ctor;
2064 if (!CopyCtor && Ctor->isCopyConstructor())
2065 CopyCtor = Ctor;
2066 }
2067 return CopyCtor;
2068}
2069
2070static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2071 SourceLocation Loc) {
2072 ASTContext &Ctx = CD->getASTContext();
2073 return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2074 CD, true, Args, false, false, false, false,
2075 CXXConstructExpr::CK_Complete,
2076 SourceRange(Loc, Loc));
2077}
2078
Aaron Puchertcd37c092018-08-23 21:53:04 +00002079void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002080 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002081 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002082
Aaron Ballman9ee54d12014-05-14 20:42:13 +00002083 for (auto *D : S->getDeclGroup()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002084 if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002085 Expr *E = VD->getInit();
Richard Smithe97654b2018-01-11 22:13:57 +00002086 if (!E)
2087 continue;
2088 E = E->IgnoreParens();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002089
Richard Smithe97654b2018-01-11 22:13:57 +00002090 // handle constructors that involve temporaries
2091 if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2092 E = EWC->getSubExpr();
2093 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2094 E = BTE->getSubExpr();
2095
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002096 if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2097 const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002098 if (!CtorD || !CtorD->hasAttrs())
Richard Smithe97654b2018-01-11 22:13:57 +00002099 continue;
2100 handleCall(E, CtorD, VD);
2101 } else if (isa<CallExpr>(E) && E->isRValue()) {
2102 // If the object is initialized by a function call that returns a
2103 // scoped lockable by value, use the attributes on the copy or move
2104 // constructor to figure out what effect that should have on the
2105 // lockset.
2106 // FIXME: Is this really the best way to handle this situation?
2107 auto *RD = E->getType()->getAsCXXRecordDecl();
2108 if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2109 continue;
2110 CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2111 if (!CtorD || !CtorD->hasAttrs())
2112 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002113 handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002114 }
2115 }
2116 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002117}
2118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002119/// Compute the intersection of two locksets and issue warnings for any
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002120/// locks in the symmetric difference.
2121///
2122/// This function is used at a merge point in the CFG when comparing the lockset
2123/// of each branch being merged. For example, given the following sequence:
2124/// A; if () then B; else C; D; we need to check that the lockset after B and C
2125/// are the same. In the event of a difference, we use the intersection of these
2126/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002127///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002128/// \param FSet1 The first lockset.
2129/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002130/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002131/// \param LEK1 The error message to report if a mutex is missing from LSet1
2132/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002133void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2134 const FactSet &FSet2,
2135 SourceLocation JoinLoc,
2136 LockErrorKind LEK1,
2137 LockErrorKind LEK2,
2138 bool Modify) {
2139 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002140
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002141 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002142 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002143 const FactEntry *LDat1 = nullptr;
2144 const FactEntry *LDat2 = &FactMan[Fact];
2145 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2146 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002147
DeLesley Hutchins42665222014-08-04 16:10:59 +00002148 if (LDat1) {
2149 if (LDat1->kind() != LDat2->kind()) {
2150 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2151 LDat2->loc(), LDat1->loc());
2152 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002153 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002154 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002155 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002156 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00002157 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002158 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002159 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002160 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002161 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00002162 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2163 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002164 }
2165 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002166
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002167 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002168 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002169 const FactEntry *LDat1 = &FactMan[Fact];
2170 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002171
DeLesley Hutchins42665222014-08-04 16:10:59 +00002172 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00002173 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2174 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002175 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00002176 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002177 }
2178 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002179}
2180
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002181// Return true if block B never continues to its successors.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002182static bool neverReturns(const CFGBlock *B) {
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002183 if (B->hasNoReturnElement())
2184 return true;
2185 if (B->empty())
2186 return false;
2187
2188 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002189 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2190 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002191 return true;
2192 }
2193 return false;
2194}
2195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002196/// Check a function's CFG for thread-safety violations.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002197///
2198/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2199/// at the end of each block, and issue warnings for thread safety violations.
2200/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002201void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002202 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2203 // For now, we just use the walker to set things up.
2204 threadSafety::CFGWalker walker;
2205 if (!walker.init(AC))
2206 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002207
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002208 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002209 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002210
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002211 CFG *CFGraph = walker.getGraph();
2212 const NamedDecl *D = walker.getDecl();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002213 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00002214 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002215
Aaron Ballman9ead1242013-12-19 02:39:40 +00002216 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002217 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002218
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002219 // FIXME: Do something a bit more intelligent inside constructor and
2220 // destructor code. Constructors and destructors must assume unique access
2221 // to 'this', so checks on member variable access is disabled, but we should
2222 // still enable checks on other objects.
2223 if (isa<CXXConstructorDecl>(D))
2224 return; // Don't check inside constructors.
2225 if (isa<CXXDestructorDecl>(D))
2226 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002227
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002228 Handler.enterFunction(CurrentFunction);
2229
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002230 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002231 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002232
2233 // We need to explore the CFG via a "topological" ordering.
2234 // That way, we will be guaranteed to have information about required
2235 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002236 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002237 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002238
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002239 // Mark entry block as reachable
2240 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2241
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002242 // Compute SSA names for local variables
2243 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2244
Richard Smith92286672012-02-03 04:45:26 +00002245 // Fill in source locations for all CFGBlocks.
2246 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2247
DeLesley Hutchins42665222014-08-04 16:10:59 +00002248 CapExprSet ExclusiveLocksAcquired;
2249 CapExprSet SharedLocksAcquired;
2250 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002251
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002252 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002253 // to initial lockset. Also turn off checking for lock and unlock functions.
2254 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002255 if (!SortedGraph->empty() && D->hasAttrs()) {
2256 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002257 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002258
DeLesley Hutchins42665222014-08-04 16:10:59 +00002259 CapExprSet ExclusiveLocksToAdd;
2260 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002261 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002262
2263 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002264 for (const auto *Attr : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002265 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002266 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002267 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00002268 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002269 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002270 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002271 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2272 // We must ignore such methods.
2273 if (A->args_size() == 0)
2274 return;
Aaron Ballmaneaa18e62018-08-03 19:37:45 +00002275 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2276 nullptr, D);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002277 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002278 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002279 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002280 if (A->args_size() == 0)
2281 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002282 getMutexIDs(A->isShared() ? SharedLocksAcquired
2283 : ExclusiveLocksAcquired,
2284 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002285 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002286 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002287 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002288 return;
2289 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002290 // Don't try to check trylock functions for now.
2291 return;
2292 } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2293 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002294 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002295 }
2296 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002297
2298 // FIXME -- Loc can be wrong here.
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002299 for (const auto &Mu : ExclusiveLocksToAdd) {
2300 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2301 Entry->setDeclared(true);
2302 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2303 }
2304 for (const auto &Mu : SharedLocksToAdd) {
2305 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2306 Entry->setDeclared(true);
2307 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2308 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002309 }
2310
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002311 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002312 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002313 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002314
2315 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002316 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002317
2318 // Iterate through the predecessor blocks and warn if the lockset for all
2319 // predecessors is not the same. We take the entry lockset of the current
2320 // block to be the intersection of all previous locksets.
2321 // FIXME: By keeping the intersection, we may output more errors in future
2322 // for a lock which is not in the intersection, but was in the union. We
2323 // may want to also keep the union in future. As an example, let's say
2324 // the intersection contains Mutex L, and the union contains L and M.
2325 // Later we unlock M. At this point, we would output an error because we
2326 // never locked M; although the real error is probably that we forgot to
2327 // lock M on all code paths. Conversely, let's say that later we lock M.
2328 // In this case, we should compare against the intersection instead of the
2329 // union because the real error is probably that we forgot to unlock M on
2330 // all code paths.
2331 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002332 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002333 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2334 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002335 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002336 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002337 continue;
2338
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002339 int PrevBlockID = (*PI)->getBlockID();
2340 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2341
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002342 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002343 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002344 continue;
2345
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002346 // Okay, we can reach this block from the entry.
2347 CurrBlockInfo->Reachable = true;
2348
Richard Smith815b29d2012-02-03 03:30:07 +00002349 // If the previous block ended in a 'continue' or 'break' statement, then
2350 // a difference in locksets is probably due to a bug in that block, rather
2351 // than in some other predecessor. In that case, keep the other
2352 // predecessor's lockset.
2353 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2354 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2355 SpecialBlocks.push_back(*PI);
2356 continue;
2357 }
2358 }
2359
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002360 FactSet PrevLockset;
2361 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002362
Caitlin Sadowski33208342011-09-09 16:11:56 +00002363 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002364 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002365 LocksetInitialized = true;
2366 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002367 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2368 CurrBlockInfo->EntryLoc,
2369 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002370 }
2371 }
2372
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002373 // Skip rest of block if it's not reachable.
2374 if (!CurrBlockInfo->Reachable)
2375 continue;
2376
Richard Smith815b29d2012-02-03 03:30:07 +00002377 // Process continue and break blocks. Assume that the lockset for the
2378 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002379 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00002380 int PrevBlockID = PrevBlock->getBlockID();
2381 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2382
2383 if (!LocksetInitialized) {
2384 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2385 LocksetInitialized = true;
2386 } else {
2387 // Determine whether this edge is a loop terminator for diagnostic
2388 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2389 // it might also be part of a switch. Also, a subsequent destructor
2390 // might add to the lockset, in which case the real issue might be a
2391 // double lock on the other path.
2392 const Stmt *Terminator = PrevBlock->getTerminator();
2393 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2394
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002395 FactSet PrevLockset;
2396 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2397 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002398
Richard Smith815b29d2012-02-03 03:30:07 +00002399 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002400 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2401 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002402 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002403 : LEK_LockedSomePredecessors,
2404 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002405 }
2406 }
2407
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002408 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2409
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002410 // Visit all the statements in the basic block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002411 for (const auto &BI : *CurrBlock) {
2412 switch (BI.getKind()) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002413 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002414 CFGStmt CS = BI.castAs<CFGStmt>();
Aaron Puchertcd37c092018-08-23 21:53:04 +00002415 LocksetBuilder.Visit(CS.getStmt());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002416 break;
2417 }
2418 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2419 case CFGElement::AutomaticObjectDtor: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002420 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
Aaron Puchertcd37c092018-08-23 21:53:04 +00002421 const auto *DD = AD.getDestructorDecl(AC.getASTContext());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002422 if (!DD->hasAttrs())
2423 break;
2424
2425 // Create a dummy expression,
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002426 auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
Richard Trieua1877592015-03-16 21:49:43 +00002427 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002428 VK_LValue, AD.getTriggerStmt()->getEndLoc());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002429 LocksetBuilder.handleCall(&DRE, DD);
2430 break;
2431 }
2432 default:
2433 break;
2434 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002435 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002436 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002437
2438 // For every back edge from CurrBlock (the end of the loop) to another block
2439 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2440 // the one held at the beginning of FirstLoopBlock. We can look up the
2441 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2442 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2443 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002444 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002445 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002446 continue;
2447
2448 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002449 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2450 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2451 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2452 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002453 LEK_LockedSomeLoopIterations,
2454 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002455 }
2456 }
2457
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002458 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2459 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002460
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002461 // Skip the final check if the exit block is unreachable.
2462 if (!Final->Reachable)
2463 return;
2464
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002465 // By default, we expect all locks held on entry to be held on exit.
2466 FactSet ExpectedExitSet = Initial->EntrySet;
2467
2468 // Adjust the expected exit set by adding or removing locks, as declared
2469 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2470 // issue the appropriate warning.
2471 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002472 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002473 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2474 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002475 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002476 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2477 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002478 for (const auto &Lock : LocksReleased)
2479 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002480
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002481 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002482 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002483 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002484 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002485 LEK_NotLockedAtEndOfFunction,
2486 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002487
2488 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002489}
2490
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002491/// Check a function's CFG for thread-safety violations.
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002492///
2493/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2494/// at the end of each block, and issue warnings for thread safety violations.
2495/// Each block in the CFG is traversed exactly once.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002496void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2497 ThreadSafetyHandler &Handler,
2498 BeforeSet **BSet) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002499 if (!*BSet)
2500 *BSet = new BeforeSet;
2501 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002502 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002503}
2504
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002505void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002506
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002507/// Helper function that returns a LockKind required for the given level
Caitlin Sadowski33208342011-09-09 16:11:56 +00002508/// of access.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002509LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002510 switch (AK) {
2511 case AK_Read :
2512 return LK_Shared;
2513 case AK_Written :
2514 return LK_Exclusive;
2515 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002516 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002517}