Bug Summary

File:tools/clang/lib/Analysis/ThreadSafety.cpp
Warning:line 367, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ThreadSafety.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Analysis -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Analysis/ThreadSafety.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Analysis/ThreadSafety.cpp

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

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h

1//===- ThreadSafetyCommon.h -------------------------------------*- C++ -*-===//
2//
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// Parts of thread safety analysis that are not specific to thread safety
11// itself have been factored into classes here, where they can be potentially
12// used by other analyses. Currently these include:
13//
14// * Generalize clang CFG visitors.
15// * Conversion of the clang CFG to SSA form.
16// * Translation of clang Exprs to TIL SExprs
17//
18// UNDER CONSTRUCTION. USE AT YOUR OWN RISK.
19//
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
23#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
24
25#include "clang/AST/Decl.h"
26#include "clang/Analysis/Analyses/PostOrderCFGView.h"
27#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
28#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
29#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
30#include "clang/Analysis/AnalysisDeclContext.h"
31#include "clang/Analysis/CFG.h"
32#include "clang/Basic/LLVM.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/Support/Casting.h"
36#include <sstream>
37#include <string>
38#include <utility>
39#include <vector>
40
41namespace clang {
42
43class AbstractConditionalOperator;
44class ArraySubscriptExpr;
45class BinaryOperator;
46class CallExpr;
47class CastExpr;
48class CXXDestructorDecl;
49class CXXMemberCallExpr;
50class CXXOperatorCallExpr;
51class CXXThisExpr;
52class DeclRefExpr;
53class DeclStmt;
54class Expr;
55class MemberExpr;
56class Stmt;
57class UnaryOperator;
58
59namespace threadSafety {
60
61// Various helper functions on til::SExpr
62namespace sx {
63
64inline bool equals(const til::SExpr *E1, const til::SExpr *E2) {
65 return til::EqualsComparator::compareExprs(E1, E2);
66}
67
68inline bool matches(const til::SExpr *E1, const til::SExpr *E2) {
69 // We treat a top-level wildcard as the "univsersal" lock.
70 // It matches everything for the purpose of checking locks, but not
71 // for unlocking them.
72 if (isa<til::Wildcard>(E1))
73 return isa<til::Wildcard>(E2);
74 if (isa<til::Wildcard>(E2))
75 return isa<til::Wildcard>(E1);
76
77 return til::MatchComparator::compareExprs(E1, E2);
78}
79
80inline bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
81 const auto *PE1 = dyn_cast_or_null<til::Project>(E1);
82 if (!PE1)
83 return false;
84 const auto *PE2 = dyn_cast_or_null<til::Project>(E2);
85 if (!PE2)
86 return false;
87 return PE1->clangDecl() == PE2->clangDecl();
88}
89
90inline std::string toString(const til::SExpr *E) {
91 std::stringstream ss;
92 til::StdPrinter::print(E, ss);
93 return ss.str();
94}
95
96} // namespace sx
97
98// This class defines the interface of a clang CFG Visitor.
99// CFGWalker will invoke the following methods.
100// Note that methods are not virtual; the visitor is templatized.
101class CFGVisitor {
102 // Enter the CFG for Decl D, and perform any initial setup operations.
103 void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First) {}
104
105 // Enter a CFGBlock.
106 void enterCFGBlock(const CFGBlock *B) {}
107
108 // Returns true if this visitor implements handlePredecessor
109 bool visitPredecessors() { return true; }
110
111 // Process a predecessor edge.
112 void handlePredecessor(const CFGBlock *Pred) {}
113
114 // Process a successor back edge to a previously visited block.
115 void handlePredecessorBackEdge(const CFGBlock *Pred) {}
116
117 // Called just before processing statements.
118 void enterCFGBlockBody(const CFGBlock *B) {}
119
120 // Process an ordinary statement.
121 void handleStatement(const Stmt *S) {}
122
123 // Process a destructor call
124 void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD) {}
125
126 // Called after all statements have been handled.
127 void exitCFGBlockBody(const CFGBlock *B) {}
128
129 // Return true
130 bool visitSuccessors() { return true; }
131
132 // Process a successor edge.
133 void handleSuccessor(const CFGBlock *Succ) {}
134
135 // Process a successor back edge to a previously visited block.
136 void handleSuccessorBackEdge(const CFGBlock *Succ) {}
137
138 // Leave a CFGBlock.
139 void exitCFGBlock(const CFGBlock *B) {}
140
141 // Leave the CFG, and perform any final cleanup operations.
142 void exitCFG(const CFGBlock *Last) {}
143};
144
145// Walks the clang CFG, and invokes methods on a given CFGVisitor.
146class CFGWalker {
147public:
148 CFGWalker() = default;
149
150 // Initialize the CFGWalker. This setup only needs to be done once, even
151 // if there are multiple passes over the CFG.
152 bool init(AnalysisDeclContext &AC) {
153 ACtx = &AC;
154 CFGraph = AC.getCFG();
155 if (!CFGraph)
156 return false;
157
158 // Ignore anonymous functions.
159 if (!dyn_cast_or_null<NamedDecl>(AC.getDecl()))
160 return false;
161
162 SortedGraph = AC.getAnalysis<PostOrderCFGView>();
163 if (!SortedGraph)
164 return false;
165
166 return true;
167 }
168
169 // Traverse the CFG, calling methods on V as appropriate.
170 template <class Visitor>
171 void walk(Visitor &V) {
172 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
173
174 V.enterCFG(CFGraph, getDecl(), &CFGraph->getEntry());
175
176 for (const auto *CurrBlock : *SortedGraph) {
177 VisitedBlocks.insert(CurrBlock);
178
179 V.enterCFGBlock(CurrBlock);
180
181 // Process predecessors, handling back edges last
182 if (V.visitPredecessors()) {
183 SmallVector<CFGBlock*, 4> BackEdges;
184 // Process successors
185 for (CFGBlock::const_pred_iterator SI = CurrBlock->pred_begin(),
186 SE = CurrBlock->pred_end();
187 SI != SE; ++SI) {
188 if (*SI == nullptr)
189 continue;
190
191 if (!VisitedBlocks.alreadySet(*SI)) {
192 BackEdges.push_back(*SI);
193 continue;
194 }
195 V.handlePredecessor(*SI);
196 }
197
198 for (auto *Blk : BackEdges)
199 V.handlePredecessorBackEdge(Blk);
200 }
201
202 V.enterCFGBlockBody(CurrBlock);
203
204 // Process statements
205 for (const auto &BI : *CurrBlock) {
206 switch (BI.getKind()) {
207 case CFGElement::Statement:
208 V.handleStatement(BI.castAs<CFGStmt>().getStmt());
209 break;
210
211 case CFGElement::AutomaticObjectDtor: {
212 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
213 auto *DD = const_cast<CXXDestructorDecl *>(
214 AD.getDestructorDecl(ACtx->getASTContext()));
215 auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
216 V.handleDestructorCall(VD, DD);
217 break;
218 }
219 default:
220 break;
221 }
222 }
223
224 V.exitCFGBlockBody(CurrBlock);
225
226 // Process successors, handling back edges first.
227 if (V.visitSuccessors()) {
228 SmallVector<CFGBlock*, 8> ForwardEdges;
229
230 // Process successors
231 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
232 SE = CurrBlock->succ_end();
233 SI != SE; ++SI) {
234 if (*SI == nullptr)
235 continue;
236
237 if (!VisitedBlocks.alreadySet(*SI)) {
238 ForwardEdges.push_back(*SI);
239 continue;
240 }
241 V.handleSuccessorBackEdge(*SI);
242 }
243
244 for (auto *Blk : ForwardEdges)
245 V.handleSuccessor(Blk);
246 }
247
248 V.exitCFGBlock(CurrBlock);
249 }
250 V.exitCFG(&CFGraph->getExit());
251 }
252
253 const CFG *getGraph() const { return CFGraph; }
254 CFG *getGraph() { return CFGraph; }
255
256 const NamedDecl *getDecl() const {
257 return dyn_cast<NamedDecl>(ACtx->getDecl());
258 }
259
260 const PostOrderCFGView *getSortedGraph() const { return SortedGraph; }
261
262private:
263 CFG *CFGraph = nullptr;
264 AnalysisDeclContext *ACtx = nullptr;
265 PostOrderCFGView *SortedGraph = nullptr;
266};
267
268// TODO: move this back into ThreadSafety.cpp
269// This is specific to thread safety. It is here because
270// translateAttrExpr needs it, but that should be moved too.
271class CapabilityExpr {
272private:
273 /// The capability expression.
274 const til::SExpr* CapExpr;
275
276 /// True if this is a negative capability.
277 bool Negated;
278
279public:
280 CapabilityExpr(const til::SExpr *E, bool Neg) : CapExpr(E), Negated(Neg) {}
281
282 const til::SExpr* sexpr() const { return CapExpr; }
283 bool negative() const { return Negated; }
284
285 CapabilityExpr operator!() const {
286 return CapabilityExpr(CapExpr, !Negated);
287 }
288
289 bool equals(const CapabilityExpr &other) const {
290 return (Negated == other.Negated) && sx::equals(CapExpr, other.CapExpr);
291 }
292
293 bool matches(const CapabilityExpr &other) const {
294 return (Negated == other.Negated) && sx::matches(CapExpr, other.CapExpr);
295 }
296
297 bool matchesUniv(const CapabilityExpr &CapE) const {
298 return isUniversal() || matches(CapE);
299 }
300
301 bool partiallyMatches(const CapabilityExpr &other) const {
302 return (Negated == other.Negated) &&
303 sx::partiallyMatches(CapExpr, other.CapExpr);
304 }
305
306 const ValueDecl* valueDecl() const {
307 if (Negated || CapExpr == nullptr)
308 return nullptr;
309 if (const auto *P = dyn_cast<til::Project>(CapExpr))
310 return P->clangDecl();
311 if (const auto *P = dyn_cast<til::LiteralPtr>(CapExpr))
312 return P->clangDecl();
313 return nullptr;
314 }
315
316 std::string toString() const {
317 if (Negated)
318 return "!" + sx::toString(CapExpr);
319 return sx::toString(CapExpr);
320 }
321
322 bool shouldIgnore() const { return CapExpr == nullptr; }
323
324 bool isInvalid() const { return sexpr() && isa<til::Undefined>(sexpr()); }
325
326 bool isUniversal() const { return sexpr() && isa<til::Wildcard>(sexpr()); }
327};
328
329// Translate clang::Expr to til::SExpr.
330class SExprBuilder {
331public:
332 /// \brief Encapsulates the lexical context of a function call. The lexical
333 /// context includes the arguments to the call, including the implicit object
334 /// argument. When an attribute containing a mutex expression is attached to
335 /// a method, the expression may refer to formal parameters of the method.
336 /// Actual arguments must be substituted for formal parameters to derive
337 /// the appropriate mutex expression in the lexical context where the function
338 /// is called. PrevCtx holds the context in which the arguments themselves
339 /// should be evaluated; multiple calling contexts can be chained together
340 /// by the lock_returned attribute.
341 struct CallingContext {
342 // The previous context; or 0 if none.
343 CallingContext *Prev;
344
345 // The decl to which the attr is attached.
346 const NamedDecl *AttrDecl;
347
348 // Implicit object argument -- e.g. 'this'
349 const Expr *SelfArg = nullptr;
350
351 // Number of funArgs
352 unsigned NumArgs = 0;
353
354 // Function arguments
355 const Expr *const *FunArgs = nullptr;
356
357 // is Self referred to with -> or .?
358 bool SelfArrow = false;
359
360 CallingContext(CallingContext *P, const NamedDecl *D = nullptr)
361 : Prev(P), AttrDecl(D) {}
362 };
363
364 SExprBuilder(til::MemRegionRef A) : Arena(A) {
365 // FIXME: we don't always have a self-variable.
366 SelfVar = new (Arena) til::Variable(nullptr);
5
Null pointer value stored to 'Analyzer.SxBuilder.SelfVar'
367 SelfVar->setKind(til::Variable::VK_SFun);
6
Called C++ object pointer is null
368 }
369
370 // Translate a clang expression in an attribute to a til::SExpr.
371 // Constructs the context from D, DeclExp, and SelfDecl.
372 CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D,
373 const Expr *DeclExp, VarDecl *SelfD=nullptr);
374
375 CapabilityExpr translateAttrExpr(const Expr *AttrExp, CallingContext *Ctx);
376
377 // Translate a clang statement or expression to a TIL expression.
378 // Also performs substitution of variables; Ctx provides the context.
379 // Dispatches on the type of S.
380 til::SExpr *translate(const Stmt *S, CallingContext *Ctx);
381 til::SCFG *buildCFG(CFGWalker &Walker);
382
383 til::SExpr *lookupStmt(const Stmt *S);
384
385 til::BasicBlock *lookupBlock(const CFGBlock *B) {
386 return BlockMap[B->getBlockID()];
387 }
388
389 const til::SCFG *getCFG() const { return Scfg; }
390 til::SCFG *getCFG() { return Scfg; }
391
392private:
393 // We implement the CFGVisitor API
394 friend class CFGWalker;
395
396 til::SExpr *translateDeclRefExpr(const DeclRefExpr *DRE,
397 CallingContext *Ctx) ;
398 til::SExpr *translateCXXThisExpr(const CXXThisExpr *TE, CallingContext *Ctx);
399 til::SExpr *translateMemberExpr(const MemberExpr *ME, CallingContext *Ctx);
400 til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx,
401 const Expr *SelfE = nullptr);
402 til::SExpr *translateCXXMemberCallExpr(const CXXMemberCallExpr *ME,
403 CallingContext *Ctx);
404 til::SExpr *translateCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE,
405 CallingContext *Ctx);
406 til::SExpr *translateUnaryOperator(const UnaryOperator *UO,
407 CallingContext *Ctx);
408 til::SExpr *translateBinOp(til::TIL_BinaryOpcode Op,
409 const BinaryOperator *BO,
410 CallingContext *Ctx, bool Reverse = false);
411 til::SExpr *translateBinAssign(til::TIL_BinaryOpcode Op,
412 const BinaryOperator *BO,
413 CallingContext *Ctx, bool Assign = false);
414 til::SExpr *translateBinaryOperator(const BinaryOperator *BO,
415 CallingContext *Ctx);
416 til::SExpr *translateCastExpr(const CastExpr *CE, CallingContext *Ctx);
417 til::SExpr *translateArraySubscriptExpr(const ArraySubscriptExpr *E,
418 CallingContext *Ctx);
419 til::SExpr *translateAbstractConditionalOperator(
420 const AbstractConditionalOperator *C, CallingContext *Ctx);
421
422 til::SExpr *translateDeclStmt(const DeclStmt *S, CallingContext *Ctx);
423
424 // Map from statements in the clang CFG to SExprs in the til::SCFG.
425 using StatementMap = llvm::DenseMap<const Stmt *, til::SExpr *>;
426
427 // Map from clang local variables to indices in a LVarDefinitionMap.
428 using LVarIndexMap = llvm::DenseMap<const ValueDecl *, unsigned>;
429
430 // Map from local variable indices to SSA variables (or constants).
431 using NameVarPair = std::pair<const ValueDecl *, til::SExpr *>;
432 using LVarDefinitionMap = CopyOnWriteVector<NameVarPair>;
433
434 struct BlockInfo {
435 LVarDefinitionMap ExitMap;
436 bool HasBackEdges = false;
437
438 // Successors yet to be processed
439 unsigned UnprocessedSuccessors = 0;
440
441 // Predecessors already processed
442 unsigned ProcessedPredecessors = 0;
443
444 BlockInfo() = default;
445 BlockInfo(BlockInfo &&) = default;
446 BlockInfo &operator=(BlockInfo &&) = default;
447 };
448
449 void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First);
450 void enterCFGBlock(const CFGBlock *B);
451 bool visitPredecessors() { return true; }
452 void handlePredecessor(const CFGBlock *Pred);
453 void handlePredecessorBackEdge(const CFGBlock *Pred);
454 void enterCFGBlockBody(const CFGBlock *B);
455 void handleStatement(const Stmt *S);
456 void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD);
457 void exitCFGBlockBody(const CFGBlock *B);
458 bool visitSuccessors() { return true; }
459 void handleSuccessor(const CFGBlock *Succ);
460 void handleSuccessorBackEdge(const CFGBlock *Succ);
461 void exitCFGBlock(const CFGBlock *B);
462 void exitCFG(const CFGBlock *Last);
463
464 void insertStmt(const Stmt *S, til::SExpr *E) {
465 SMap.insert(std::make_pair(S, E));
466 }
467
468 til::SExpr *getCurrentLVarDefinition(const ValueDecl *VD);
469
470 til::SExpr *addStatement(til::SExpr *E, const Stmt *S,
471 const ValueDecl *VD = nullptr);
472 til::SExpr *lookupVarDecl(const ValueDecl *VD);
473 til::SExpr *addVarDecl(const ValueDecl *VD, til::SExpr *E);
474 til::SExpr *updateVarDecl(const ValueDecl *VD, til::SExpr *E);
475
476 void makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E);
477 void mergeEntryMap(LVarDefinitionMap Map);
478 void mergeEntryMapBackEdge();
479 void mergePhiNodesBackEdge(const CFGBlock *Blk);
480
481private:
482 // Set to true when parsing capability expressions, which get translated
483 // inaccurately in order to hack around smart pointers etc.
484 static const bool CapabilityExprMode = true;
485
486 til::MemRegionRef Arena;
487
488 // Variable to use for 'this'. May be null.
489 til::Variable *SelfVar = nullptr;
490
491 til::SCFG *Scfg = nullptr;
492
493 // Map from Stmt to TIL Variables
494 StatementMap SMap;
495
496 // Indices of clang local vars.
497 LVarIndexMap LVarIdxMap;
498
499 // Map from clang to til BBs.
500 std::vector<til::BasicBlock *> BlockMap;
501
502 // Extra information per BB. Indexed by clang BlockID.
503 std::vector<BlockInfo> BBInfo;
504
505 LVarDefinitionMap CurrentLVarMap;
506 std::vector<til::Phi *> CurrentArguments;
507 std::vector<til::SExpr *> CurrentInstructions;
508 std::vector<til::Phi *> IncompleteArgs;
509 til::BasicBlock *CurrentBB = nullptr;
510 BlockInfo *CurrentBlockInfo = nullptr;
511};
512
513// Dump an SCFG to llvm::errs().
514void printSCFG(CFGWalker &Walker);
515
516} // namespace threadSafety
517} // namespace clang
518
519#endif // LLVM_CLANG_THREAD_SAFETY_COMMON_H