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