Bug Summary

File:tools/clang/lib/Analysis/ThreadSafety.cpp
Warning:line 345, 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~svn325874/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325874/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~svn325874/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-02-23-163436-368-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/lib/Analysis/ThreadSafety.cpp

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

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

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