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