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