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