1 //===- ThreadSafety.cpp ---------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // A intra-procedural analysis for thread safety (e.g. deadlocks and race
11 // conditions), based off of an annotation system.
12 //
13 // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
14 // for more information.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "clang/Analysis/Analyses/ThreadSafety.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclGroup.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/OperationKinds.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/Type.h"
29 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
30 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
31 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
32 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
33 #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
34 #include "clang/Analysis/AnalysisDeclContext.h"
35 #include "clang/Analysis/CFG.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/STLExtras.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/StringRef.h"
47 #include "llvm/Support/Allocator.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <functional>
54 #include <iterator>
55 #include <memory>
56 #include <string>
57 #include <type_traits>
58 #include <utility>
59 #include <vector>
60 
61 using namespace clang;
62 using namespace threadSafety;
63 
64 // Key method definition
65 ThreadSafetyHandler::~ThreadSafetyHandler() = default;
66 
67 namespace {
68 
69 class TILPrinter :
70     public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
71 
72 } // namespace
73 
74 /// Issue a warning about an invalid lock expression
75 static void warnInvalidLock(ThreadSafetyHandler &Handler,
76                             const Expr *MutexExp, const NamedDecl *D,
77                             const Expr *DeclExp, StringRef Kind) {
78   SourceLocation Loc;
79   if (DeclExp)
80     Loc = DeclExp->getExprLoc();
81 
82   // FIXME: add a note about the attribute location in MutexExp or D
83   if (Loc.isValid())
84     Handler.handleInvalidLockExp(Kind, Loc);
85 }
86 
87 namespace {
88 
89 /// \brief A set of CapabilityInfo objects, which are compiled from the
90 /// requires attributes on a function.
91 class CapExprSet : public SmallVector<CapabilityExpr, 4> {
92 public:
93   /// \brief Push M onto list, but discard duplicates.
94   void push_back_nodup(const CapabilityExpr &CapE) {
95     iterator It = std::find_if(begin(), end(),
96                                [=](const CapabilityExpr &CapE2) {
97       return CapE.equals(CapE2);
98     });
99     if (It == end())
100       push_back(CapE);
101   }
102 };
103 
104 class FactManager;
105 class FactSet;
106 
107 /// \brief This is a helper class that stores a fact that is known at a
108 /// particular point in program execution.  Currently, a fact is a capability,
109 /// along with additional information, such as where it was acquired, whether
110 /// it is exclusive or shared, etc.
111 ///
112 /// FIXME: this analysis does not currently support either re-entrant
113 /// locking or lock "upgrading" and "downgrading" between exclusive and
114 /// shared.
115 class FactEntry : public CapabilityExpr {
116 private:
117   /// Exclusive or shared.
118   LockKind LKind;
119 
120   /// Where it was acquired.
121   SourceLocation AcquireLoc;
122 
123   /// True if the lock was asserted.
124   bool Asserted;
125 
126   /// True if the lock was declared.
127   bool Declared;
128 
129 public:
130   FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
131             bool Asrt, bool Declrd = false)
132       : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
133         Declared(Declrd) {}
134   virtual ~FactEntry() = default;
135 
136   LockKind kind() const { return LKind;      }
137   SourceLocation loc() const { return AcquireLoc; }
138   bool asserted() const { return Asserted; }
139   bool declared() const { return Declared; }
140 
141   void setDeclared(bool D) { Declared = D; }
142 
143   virtual void
144   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
145                                 SourceLocation JoinLoc, LockErrorKind LEK,
146                                 ThreadSafetyHandler &Handler) 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) {
154     return  (LKind == LK_Exclusive) || (LK == LK_Shared);
155   }
156 };
157 
158 using FactID = unsigned short;
159 
160 /// \brief 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<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   FactEntry &operator[](FactID F) { return *Facts[F]; }
174 };
175 
176 /// \brief A FactSet is the set of facts that are known to be true at a
177 /// particular program point.  FactSets must be small, because they are
178 /// frequently copied, and are thus implemented as a set of indices into a
179 /// table maintained by a FactManager.  A typical FactSet only holds 1 or 2
180 /// locks, so we can get away with doing a linear search for lookup.  Note
181 /// that a hashtable or map is inappropriate in this case, because lookups
182 /// may involve partial pattern matches, rather than exact matches.
183 class FactSet {
184 private:
185   using FactVec = SmallVector<FactID, 4>;
186 
187   FactVec FactIDs;
188 
189 public:
190   using iterator = FactVec::iterator;
191   using const_iterator = FactVec::const_iterator;
192 
193   iterator begin() { return FactIDs.begin(); }
194   const_iterator begin() const { return FactIDs.begin(); }
195 
196   iterator end() { return FactIDs.end(); }
197   const_iterator end() const { return FactIDs.end(); }
198 
199   bool isEmpty() const { return FactIDs.size() == 0; }
200 
201   // Return true if the set contains only negative facts
202   bool isEmpty(FactManager &FactMan) const {
203     for (const auto FID : *this) {
204       if (!FactMan[FID].negative())
205         return false;
206     }
207     return true;
208   }
209 
210   void addLockByID(FactID ID) { FactIDs.push_back(ID); }
211 
212   FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
213     FactID F = FM.newFact(std::move(Entry));
214     FactIDs.push_back(F);
215     return F;
216   }
217 
218   bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
219     unsigned n = FactIDs.size();
220     if (n == 0)
221       return false;
222 
223     for (unsigned i = 0; i < n-1; ++i) {
224       if (FM[FactIDs[i]].matches(CapE)) {
225         FactIDs[i] = FactIDs[n-1];
226         FactIDs.pop_back();
227         return true;
228       }
229     }
230     if (FM[FactIDs[n-1]].matches(CapE)) {
231       FactIDs.pop_back();
232       return true;
233     }
234     return false;
235   }
236 
237   iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
238     return std::find_if(begin(), end(), [&](FactID ID) {
239       return FM[ID].matches(CapE);
240     });
241   }
242 
243   FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
244     auto I = std::find_if(begin(), end(), [&](FactID ID) {
245       return FM[ID].matches(CapE);
246     });
247     return I != end() ? &FM[*I] : nullptr;
248   }
249 
250   FactEntry *findLockUniv(FactManager &FM, 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   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<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, 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(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 StmtVisitor<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(DeclStmt *S);
606   void VisitBinaryOperator(BinaryOperator *BO);
607 };
608 
609 } // namespace
610 
611 // Add new local variables to the variable map
612 void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
613   bool modifiedCtx = false;
614   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(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     int 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       int 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(const_cast<Stmt *>(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->getTerminator()) {
824       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
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()->getLocStart();
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()->getLocStart();
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     }
853   }
854 }
855 
856 namespace {
857 
858 class LockableFactEntry : public FactEntry {
859 private:
860   /// managed by ScopedLockable object
861   bool Managed;
862 
863 public:
864   LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
865                     bool Mng = false, bool Asrt = false)
866       : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
867 
868   void
869   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
870                                 SourceLocation JoinLoc, LockErrorKind LEK,
871                                 ThreadSafetyHandler &Handler) const override {
872     if (!Managed && !asserted() && !negative() && !isUniversal()) {
873       Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
874                                         LEK);
875     }
876   }
877 
878   void handleUnlock(FactSet &FSet, FactManager &FactMan,
879                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
880                     bool FullyRemove, ThreadSafetyHandler &Handler,
881                     StringRef DiagKind) const override {
882     FSet.removeLock(FactMan, Cp);
883     if (!Cp.negative()) {
884       FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
885                                 !Cp, LK_Exclusive, UnlockLoc));
886     }
887   }
888 };
889 
890 class ScopedLockableFactEntry : public FactEntry {
891 private:
892   SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
893 
894 public:
895   ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
896                           const CapExprSet &Excl, const CapExprSet &Shrd)
897       : FactEntry(CE, LK_Exclusive, Loc, false) {
898     for (const auto &M : Excl)
899       UnderlyingMutexes.push_back(M.sexpr());
900     for (const auto &M : Shrd)
901       UnderlyingMutexes.push_back(M.sexpr());
902   }
903 
904   void
905   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
906                                 SourceLocation JoinLoc, LockErrorKind LEK,
907                                 ThreadSafetyHandler &Handler) const override {
908     for (const auto *UnderlyingMutex : UnderlyingMutexes) {
909       if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
910         // If this scoped lock manages another mutex, and if the underlying
911         // mutex is still held, then warn about the underlying mutex.
912         Handler.handleMutexHeldEndOfScope(
913             "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
914       }
915     }
916   }
917 
918   void handleUnlock(FactSet &FSet, FactManager &FactMan,
919                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
920                     bool FullyRemove, ThreadSafetyHandler &Handler,
921                     StringRef DiagKind) const override {
922     assert(!Cp.negative() && "Managing object cannot be negative.");
923     for (const auto *UnderlyingMutex : UnderlyingMutexes) {
924       CapabilityExpr UnderCp(UnderlyingMutex, false);
925       auto UnderEntry = llvm::make_unique<LockableFactEntry>(
926           !UnderCp, LK_Exclusive, UnlockLoc);
927 
928       if (FullyRemove) {
929         // We're destroying the managing object.
930         // Remove the underlying mutex if it exists; but don't warn.
931         if (FSet.findLock(FactMan, UnderCp)) {
932           FSet.removeLock(FactMan, UnderCp);
933           FSet.addLock(FactMan, std::move(UnderEntry));
934         }
935       } else {
936         // We're releasing the underlying mutex, but not destroying the
937         // managing object.  Warn on dual release.
938         if (!FSet.findLock(FactMan, UnderCp)) {
939           Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
940                                         UnlockLoc);
941         }
942         FSet.removeLock(FactMan, UnderCp);
943         FSet.addLock(FactMan, std::move(UnderEntry));
944       }
945     }
946     if (FullyRemove)
947       FSet.removeLock(FactMan, Cp);
948   }
949 };
950 
951 /// \brief Class which implements the core thread safety analysis routines.
952 class ThreadSafetyAnalyzer {
953   friend class BuildLockset;
954   friend class threadSafety::BeforeSet;
955 
956   llvm::BumpPtrAllocator Bpa;
957   threadSafety::til::MemRegionRef Arena;
958   threadSafety::SExprBuilder SxBuilder;
959 
960   ThreadSafetyHandler &Handler;
961   const CXXMethodDecl *CurrentMethod;
962   LocalVariableMap LocalVarMap;
963   FactManager FactMan;
964   std::vector<CFGBlockInfo> BlockInfo;
965 
966   BeforeSet *GlobalBeforeSet;
967 
968 public:
969   ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
970       : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
971 
972   bool inCurrentScope(const CapabilityExpr &CapE);
973 
974   void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
975                StringRef DiagKind, bool ReqAttr = false);
976   void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
977                   SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
978                   StringRef DiagKind);
979 
980   template <typename AttrType>
981   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
982                    const NamedDecl *D, VarDecl *SelfDecl = nullptr);
983 
984   template <class AttrType>
985   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
986                    const NamedDecl *D,
987                    const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
988                    Expr *BrE, bool Neg);
989 
990   const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
991                                      bool &Negate);
992 
993   void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
994                       const CFGBlock* PredBlock,
995                       const CFGBlock *CurrBlock);
996 
997   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
998                         SourceLocation JoinLoc,
999                         LockErrorKind LEK1, LockErrorKind LEK2,
1000                         bool Modify=true);
1001 
1002   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1003                         SourceLocation JoinLoc, LockErrorKind LEK1,
1004                         bool Modify=true) {
1005     intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
1006   }
1007 
1008   void runAnalysis(AnalysisDeclContext &AC);
1009 };
1010 
1011 } // namespace
1012 
1013 /// Process acquired_before and acquired_after attributes on Vd.
1014 BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1015     ThreadSafetyAnalyzer& Analyzer) {
1016   // Create a new entry for Vd.
1017   BeforeInfo *Info = nullptr;
1018   {
1019     // Keep InfoPtr in its own scope in case BMap is modified later and the
1020     // reference becomes invalid.
1021     std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1022     if (!InfoPtr)
1023       InfoPtr.reset(new BeforeInfo());
1024     Info = InfoPtr.get();
1025   }
1026 
1027   for (const auto *At : Vd->attrs()) {
1028     switch (At->getKind()) {
1029       case attr::AcquiredBefore: {
1030         const auto *A = cast<AcquiredBeforeAttr>(At);
1031 
1032         // Read exprs from the attribute, and add them to BeforeVect.
1033         for (const auto *Arg : A->args()) {
1034           CapabilityExpr Cp =
1035             Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1036           if (const ValueDecl *Cpvd = Cp.valueDecl()) {
1037             Info->Vect.push_back(Cpvd);
1038             const auto It = BMap.find(Cpvd);
1039             if (It == BMap.end())
1040               insertAttrExprs(Cpvd, Analyzer);
1041           }
1042         }
1043         break;
1044       }
1045       case attr::AcquiredAfter: {
1046         const auto *A = cast<AcquiredAfterAttr>(At);
1047 
1048         // Read exprs from the attribute, and add them to BeforeVect.
1049         for (const auto *Arg : A->args()) {
1050           CapabilityExpr Cp =
1051             Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1052           if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1053             // Get entry for mutex listed in attribute
1054             BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1055             ArgInfo->Vect.push_back(Vd);
1056           }
1057         }
1058         break;
1059       }
1060       default:
1061         break;
1062     }
1063   }
1064 
1065   return Info;
1066 }
1067 
1068 BeforeSet::BeforeInfo *
1069 BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1070                                 ThreadSafetyAnalyzer &Analyzer) {
1071   auto It = BMap.find(Vd);
1072   BeforeInfo *Info = nullptr;
1073   if (It == BMap.end())
1074     Info = insertAttrExprs(Vd, Analyzer);
1075   else
1076     Info = It->second.get();
1077   assert(Info && "BMap contained nullptr?");
1078   return Info;
1079 }
1080 
1081 /// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1082 void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1083                                  const FactSet& FSet,
1084                                  ThreadSafetyAnalyzer& Analyzer,
1085                                  SourceLocation Loc, StringRef CapKind) {
1086   SmallVector<BeforeInfo*, 8> InfoVect;
1087 
1088   // Do a depth-first traversal of Vd.
1089   // Return true if there are cycles.
1090   std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1091     if (!Vd)
1092       return false;
1093 
1094     BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
1095 
1096     if (Info->Visited == 1)
1097       return true;
1098 
1099     if (Info->Visited == 2)
1100       return false;
1101 
1102     if (Info->Vect.empty())
1103       return false;
1104 
1105     InfoVect.push_back(Info);
1106     Info->Visited = 1;
1107     for (const auto *Vdb : Info->Vect) {
1108       // Exclude mutexes in our immediate before set.
1109       if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1110         StringRef L1 = StartVd->getName();
1111         StringRef L2 = Vdb->getName();
1112         Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1113       }
1114       // Transitively search other before sets, and warn on cycles.
1115       if (traverse(Vdb)) {
1116         if (CycMap.find(Vd) == CycMap.end()) {
1117           CycMap.insert(std::make_pair(Vd, true));
1118           StringRef L1 = Vd->getName();
1119           Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1120         }
1121       }
1122     }
1123     Info->Visited = 2;
1124     return false;
1125   };
1126 
1127   traverse(StartVd);
1128 
1129   for (auto *Info : InfoVect)
1130     Info->Visited = 0;
1131 }
1132 
1133 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1134 static const ValueDecl *getValueDecl(const Expr *Exp) {
1135   if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1136     return getValueDecl(CE->getSubExpr());
1137 
1138   if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1139     return DR->getDecl();
1140 
1141   if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1142     return ME->getMemberDecl();
1143 
1144   return nullptr;
1145 }
1146 
1147 namespace {
1148 
1149 template <typename Ty>
1150 class has_arg_iterator_range {
1151   using yes = char[1];
1152   using no = char[2];
1153 
1154   template <typename Inner>
1155   static yes& test(Inner *I, decltype(I->args()) * = nullptr);
1156 
1157   template <typename>
1158   static no& test(...);
1159 
1160 public:
1161   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1162 };
1163 
1164 } // namespace
1165 
1166 static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1167   return A->getName();
1168 }
1169 
1170 static StringRef ClassifyDiagnostic(QualType VDT) {
1171   // We need to look at the declaration of the type of the value to determine
1172   // which it is. The type should either be a record or a typedef, or a pointer
1173   // or reference thereof.
1174   if (const auto *RT = VDT->getAs<RecordType>()) {
1175     if (const auto *RD = RT->getDecl())
1176       if (const auto *CA = RD->getAttr<CapabilityAttr>())
1177         return ClassifyDiagnostic(CA);
1178   } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1179     if (const auto *TD = TT->getDecl())
1180       if (const auto *CA = TD->getAttr<CapabilityAttr>())
1181         return ClassifyDiagnostic(CA);
1182   } else if (VDT->isPointerType() || VDT->isReferenceType())
1183     return ClassifyDiagnostic(VDT->getPointeeType());
1184 
1185   return "mutex";
1186 }
1187 
1188 static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1189   assert(VD && "No ValueDecl passed");
1190 
1191   // The ValueDecl is the declaration of a mutex or role (hopefully).
1192   return ClassifyDiagnostic(VD->getType());
1193 }
1194 
1195 template <typename AttrTy>
1196 static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
1197                                StringRef>::type
1198 ClassifyDiagnostic(const AttrTy *A) {
1199   if (const ValueDecl *VD = getValueDecl(A->getArg()))
1200     return ClassifyDiagnostic(VD);
1201   return "mutex";
1202 }
1203 
1204 template <typename AttrTy>
1205 static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
1206                                StringRef>::type
1207 ClassifyDiagnostic(const AttrTy *A) {
1208   for (const auto *Arg : A->args()) {
1209     if (const ValueDecl *VD = getValueDecl(Arg))
1210       return ClassifyDiagnostic(VD);
1211   }
1212   return "mutex";
1213 }
1214 
1215 bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1216   if (!CurrentMethod)
1217       return false;
1218   if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1219     const auto *VD = P->clangDecl();
1220     if (VD)
1221       return VD->getDeclContext() == CurrentMethod->getDeclContext();
1222   }
1223   return false;
1224 }
1225 
1226 /// \brief Add a new lock to the lockset, warning if the lock is already there.
1227 /// \param ReqAttr -- true if this is part of an initial Requires attribute.
1228 void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1229                                    std::unique_ptr<FactEntry> Entry,
1230                                    StringRef DiagKind, bool ReqAttr) {
1231   if (Entry->shouldIgnore())
1232     return;
1233 
1234   if (!ReqAttr && !Entry->negative()) {
1235     // look for the negative capability, and remove it from the fact set.
1236     CapabilityExpr NegC = !*Entry;
1237     FactEntry *Nen = FSet.findLock(FactMan, NegC);
1238     if (Nen) {
1239       FSet.removeLock(FactMan, NegC);
1240     }
1241     else {
1242       if (inCurrentScope(*Entry) && !Entry->asserted())
1243         Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1244                                       NegC.toString(), Entry->loc());
1245     }
1246   }
1247 
1248   // Check before/after constraints
1249   if (Handler.issueBetaWarnings() &&
1250       !Entry->asserted() && !Entry->declared()) {
1251     GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1252                                       Entry->loc(), DiagKind);
1253   }
1254 
1255   // FIXME: Don't always warn when we have support for reentrant locks.
1256   if (FSet.findLock(FactMan, *Entry)) {
1257     if (!Entry->asserted())
1258       Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
1259   } else {
1260     FSet.addLock(FactMan, std::move(Entry));
1261   }
1262 }
1263 
1264 /// \brief Remove a lock from the lockset, warning if the lock is not there.
1265 /// \param UnlockLoc The source location of the unlock (only used in error msg)
1266 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
1267                                       SourceLocation UnlockLoc,
1268                                       bool FullyRemove, LockKind ReceivedKind,
1269                                       StringRef DiagKind) {
1270   if (Cp.shouldIgnore())
1271     return;
1272 
1273   const FactEntry *LDat = FSet.findLock(FactMan, Cp);
1274   if (!LDat) {
1275     Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
1276     return;
1277   }
1278 
1279   // Generic lock removal doesn't care about lock kind mismatches, but
1280   // otherwise diagnose when the lock kinds are mismatched.
1281   if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1282     Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1283                                       LDat->kind(), ReceivedKind, UnlockLoc);
1284   }
1285 
1286   LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1287                      DiagKind);
1288 }
1289 
1290 /// \brief Extract the list of mutexIDs from the attribute on an expression,
1291 /// and push them onto Mtxs, discarding any duplicates.
1292 template <typename AttrType>
1293 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1294                                        Expr *Exp, const NamedDecl *D,
1295                                        VarDecl *SelfDecl) {
1296   if (Attr->args_size() == 0) {
1297     // The mutex held is the "this" object.
1298     CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1299     if (Cp.isInvalid()) {
1300        warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1301        return;
1302     }
1303     //else
1304     if (!Cp.shouldIgnore())
1305       Mtxs.push_back_nodup(Cp);
1306     return;
1307   }
1308 
1309   for (const auto *Arg : Attr->args()) {
1310     CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1311     if (Cp.isInvalid()) {
1312        warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1313        continue;
1314     }
1315     //else
1316     if (!Cp.shouldIgnore())
1317       Mtxs.push_back_nodup(Cp);
1318   }
1319 }
1320 
1321 /// \brief Extract the list of mutexIDs from a trylock attribute.  If the
1322 /// trylock applies to the given edge, then push them onto Mtxs, discarding
1323 /// any duplicates.
1324 template <class AttrType>
1325 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1326                                        Expr *Exp, const NamedDecl *D,
1327                                        const CFGBlock *PredBlock,
1328                                        const CFGBlock *CurrBlock,
1329                                        Expr *BrE, bool Neg) {
1330   // Find out which branch has the lock
1331   bool branch = false;
1332   if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1333     branch = BLE->getValue();
1334   else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1335     branch = ILE->getValue().getBoolValue();
1336 
1337   int branchnum = branch ? 0 : 1;
1338   if (Neg)
1339     branchnum = !branchnum;
1340 
1341   // If we've taken the trylock branch, then add the lock
1342   int i = 0;
1343   for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1344        SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1345     if (*SI == CurrBlock && i == branchnum)
1346       getMutexIDs(Mtxs, Attr, Exp, D);
1347   }
1348 }
1349 
1350 static bool getStaticBooleanValue(Expr *E, bool &TCond) {
1351   if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1352     TCond = false;
1353     return true;
1354   } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1355     TCond = BLE->getValue();
1356     return true;
1357   } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
1358     TCond = ILE->getValue().getBoolValue();
1359     return true;
1360   } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
1361     return getStaticBooleanValue(CE->getSubExpr(), TCond);
1362   return false;
1363 }
1364 
1365 // If Cond can be traced back to a function call, return the call expression.
1366 // The negate variable should be called with false, and will be set to true
1367 // if the function call is negated, e.g. if (!mu.tryLock(...))
1368 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1369                                                          LocalVarContext C,
1370                                                          bool &Negate) {
1371   if (!Cond)
1372     return nullptr;
1373 
1374   if (const auto *CallExp = dyn_cast<CallExpr>(Cond))
1375     return CallExp;
1376   else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
1377     return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1378   else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
1379     return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1380   else if (const auto *EWC = dyn_cast<ExprWithCleanups>(Cond))
1381     return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1382   else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1383     const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1384     return getTrylockCallExpr(E, C, Negate);
1385   }
1386   else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
1387     if (UOP->getOpcode() == UO_LNot) {
1388       Negate = !Negate;
1389       return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1390     }
1391     return nullptr;
1392   }
1393   else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
1394     if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1395       if (BOP->getOpcode() == BO_NE)
1396         Negate = !Negate;
1397 
1398       bool TCond = false;
1399       if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1400         if (!TCond) Negate = !Negate;
1401         return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1402       }
1403       TCond = false;
1404       if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1405         if (!TCond) Negate = !Negate;
1406         return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1407       }
1408       return nullptr;
1409     }
1410     if (BOP->getOpcode() == BO_LAnd) {
1411       // LHS must have been evaluated in a different block.
1412       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1413     }
1414     if (BOP->getOpcode() == BO_LOr)
1415       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1416     return nullptr;
1417   }
1418   return nullptr;
1419 }
1420 
1421 /// \brief Find the lockset that holds on the edge between PredBlock
1422 /// and CurrBlock.  The edge set is the exit set of PredBlock (passed
1423 /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1424 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1425                                           const FactSet &ExitSet,
1426                                           const CFGBlock *PredBlock,
1427                                           const CFGBlock *CurrBlock) {
1428   Result = ExitSet;
1429 
1430   const Stmt *Cond = PredBlock->getTerminatorCondition();
1431   if (!Cond)
1432     return;
1433 
1434   bool Negate = false;
1435   const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1436   const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1437   StringRef CapDiagKind = "mutex";
1438 
1439   auto *Exp = const_cast<CallExpr *>(getTrylockCallExpr(Cond, LVarCtx, Negate));
1440   if (!Exp)
1441     return;
1442 
1443   auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1444   if(!FunDecl || !FunDecl->hasAttrs())
1445     return;
1446 
1447   CapExprSet ExclusiveLocksToAdd;
1448   CapExprSet SharedLocksToAdd;
1449 
1450   // If the condition is a call to a Trylock function, then grab the attributes
1451   for (const auto *Attr : FunDecl->attrs()) {
1452     switch (Attr->getKind()) {
1453       case attr::TryAcquireCapability: {
1454         auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1455         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1456                     Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1457                     Negate);
1458         CapDiagKind = ClassifyDiagnostic(A);
1459         break;
1460       };
1461       case attr::ExclusiveTrylockFunction: {
1462         const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
1463         getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1464                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1465         CapDiagKind = ClassifyDiagnostic(A);
1466         break;
1467       }
1468       case attr::SharedTrylockFunction: {
1469         const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
1470         getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
1471                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1472         CapDiagKind = ClassifyDiagnostic(A);
1473         break;
1474       }
1475       default:
1476         break;
1477     }
1478   }
1479 
1480   // Add and remove locks.
1481   SourceLocation Loc = Exp->getExprLoc();
1482   for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1483     addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1484                                                          LK_Exclusive, Loc),
1485             CapDiagKind);
1486   for (const auto &SharedLockToAdd : SharedLocksToAdd)
1487     addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1488                                                          LK_Shared, Loc),
1489             CapDiagKind);
1490 }
1491 
1492 namespace {
1493 
1494 /// \brief We use this class to visit different types of expressions in
1495 /// CFGBlocks, and build up the lockset.
1496 /// An expression may cause us to add or remove locks from the lockset, or else
1497 /// output error messages related to missing locks.
1498 /// FIXME: In future, we may be able to not inherit from a visitor.
1499 class BuildLockset : public StmtVisitor<BuildLockset> {
1500   friend class ThreadSafetyAnalyzer;
1501 
1502   ThreadSafetyAnalyzer *Analyzer;
1503   FactSet FSet;
1504   LocalVariableMap::Context LVarCtx;
1505   unsigned CtxIndex;
1506 
1507   // helper functions
1508   void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1509                           Expr *MutexExp, ProtectedOperationKind POK,
1510                           StringRef DiagKind, SourceLocation Loc);
1511   void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1512                        StringRef DiagKind);
1513 
1514   void checkAccess(const Expr *Exp, AccessKind AK,
1515                    ProtectedOperationKind POK = POK_VarAccess);
1516   void checkPtAccess(const Expr *Exp, AccessKind AK,
1517                      ProtectedOperationKind POK = POK_VarAccess);
1518 
1519   void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
1520 
1521 public:
1522   BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1523       : StmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
1524         LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
1525 
1526   void VisitUnaryOperator(UnaryOperator *UO);
1527   void VisitBinaryOperator(BinaryOperator *BO);
1528   void VisitCastExpr(CastExpr *CE);
1529   void VisitCallExpr(CallExpr *Exp);
1530   void VisitCXXConstructExpr(CXXConstructExpr *Exp);
1531   void VisitDeclStmt(DeclStmt *S);
1532 };
1533 
1534 } // namespace
1535 
1536 /// \brief Warn if the LSet does not contain a lock sufficient to protect access
1537 /// of at least the passed in AccessKind.
1538 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1539                                       AccessKind AK, Expr *MutexExp,
1540                                       ProtectedOperationKind POK,
1541                                       StringRef DiagKind, SourceLocation Loc) {
1542   LockKind LK = getLockKindFromAccessKind(AK);
1543 
1544   CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1545   if (Cp.isInvalid()) {
1546     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1547     return;
1548   } else if (Cp.shouldIgnore()) {
1549     return;
1550   }
1551 
1552   if (Cp.negative()) {
1553     // Negative capabilities act like locks excluded
1554     FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1555     if (LDat) {
1556       Analyzer->Handler.handleFunExcludesLock(
1557           DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
1558       return;
1559     }
1560 
1561     // If this does not refer to a negative capability in the same class,
1562     // then stop here.
1563     if (!Analyzer->inCurrentScope(Cp))
1564       return;
1565 
1566     // Otherwise the negative requirement must be propagated to the caller.
1567     LDat = FSet.findLock(Analyzer->FactMan, Cp);
1568     if (!LDat) {
1569       Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
1570                                            LK_Shared, Loc);
1571     }
1572     return;
1573   }
1574 
1575   FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
1576   bool NoError = true;
1577   if (!LDat) {
1578     // No exact match found.  Look for a partial match.
1579     LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1580     if (LDat) {
1581       // Warn that there's no precise match.
1582       std::string PartMatchStr = LDat->toString();
1583       StringRef   PartMatchName(PartMatchStr);
1584       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1585                                            LK, Loc, &PartMatchName);
1586     } else {
1587       // Warn that there's no match at all.
1588       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1589                                            LK, Loc);
1590     }
1591     NoError = false;
1592   }
1593   // Make sure the mutex we found is the right kind.
1594   if (NoError && LDat && !LDat->isAtLeast(LK)) {
1595     Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1596                                          LK, Loc);
1597   }
1598 }
1599 
1600 /// \brief Warn if the LSet contains the given lock.
1601 void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1602                                    Expr *MutexExp, StringRef DiagKind) {
1603   CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1604   if (Cp.isInvalid()) {
1605     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1606     return;
1607   } else if (Cp.shouldIgnore()) {
1608     return;
1609   }
1610 
1611   FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
1612   if (LDat) {
1613     Analyzer->Handler.handleFunExcludesLock(
1614         DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1615   }
1616 }
1617 
1618 /// \brief Checks guarded_by and pt_guarded_by attributes.
1619 /// Whenever we identify an access (read or write) to a DeclRefExpr that is
1620 /// marked with guarded_by, we must ensure the appropriate mutexes are held.
1621 /// Similarly, we check if the access is to an expression that dereferences
1622 /// a pointer marked with pt_guarded_by.
1623 void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1624                                ProtectedOperationKind POK) {
1625   Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
1626 
1627   SourceLocation Loc = Exp->getExprLoc();
1628 
1629   // Local variables of reference type cannot be re-assigned;
1630   // map them to their initializer.
1631   while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1632     const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1633     if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1634       if (const auto *E = VD->getInit()) {
1635         Exp = E;
1636         continue;
1637       }
1638     }
1639     break;
1640   }
1641 
1642   if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
1643     // For dereferences
1644     if (UO->getOpcode() == UO_Deref)
1645       checkPtAccess(UO->getSubExpr(), AK, POK);
1646     return;
1647   }
1648 
1649   if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1650     checkPtAccess(AE->getLHS(), AK, POK);
1651     return;
1652   }
1653 
1654   if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
1655     if (ME->isArrow())
1656       checkPtAccess(ME->getBase(), AK, POK);
1657     else
1658       checkAccess(ME->getBase(), AK, POK);
1659   }
1660 
1661   const ValueDecl *D = getValueDecl(Exp);
1662   if (!D || !D->hasAttrs())
1663     return;
1664 
1665   if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
1666     Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
1667   }
1668 
1669   for (const auto *I : D->specific_attrs<GuardedByAttr>())
1670     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
1671                        ClassifyDiagnostic(I), Loc);
1672 }
1673 
1674 /// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1675 /// POK is the same  operationKind that was passed to checkAccess.
1676 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1677                                  ProtectedOperationKind POK) {
1678   while (true) {
1679     if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
1680       Exp = PE->getSubExpr();
1681       continue;
1682     }
1683     if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
1684       if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1685         // If it's an actual array, and not a pointer, then it's elements
1686         // are protected by GUARDED_BY, not PT_GUARDED_BY;
1687         checkAccess(CE->getSubExpr(), AK, POK);
1688         return;
1689       }
1690       Exp = CE->getSubExpr();
1691       continue;
1692     }
1693     break;
1694   }
1695 
1696   // Pass by reference warnings are under a different flag.
1697   ProtectedOperationKind PtPOK = POK_VarDereference;
1698   if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1699 
1700   const ValueDecl *D = getValueDecl(Exp);
1701   if (!D || !D->hasAttrs())
1702     return;
1703 
1704   if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
1705     Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
1706                                         Exp->getExprLoc());
1707 
1708   for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1709     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
1710                        ClassifyDiagnostic(I), Exp->getExprLoc());
1711 }
1712 
1713 /// \brief Process a function call, method call, constructor call,
1714 /// or destructor call.  This involves looking at the attributes on the
1715 /// corresponding function/method/constructor/destructor, issuing warnings,
1716 /// and updating the locksets accordingly.
1717 ///
1718 /// FIXME: For classes annotated with one of the guarded annotations, we need
1719 /// to treat const method calls as reads and non-const method calls as writes,
1720 /// and check that the appropriate locks are held. Non-const method calls with
1721 /// the same signature as const method calls can be also treated as reads.
1722 ///
1723 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1724   SourceLocation Loc = Exp->getExprLoc();
1725   CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1726   CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1727   CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
1728   StringRef CapDiagKind = "mutex";
1729 
1730   // Figure out if we're constructing an object of scoped lockable class
1731   bool isScopedVar = false;
1732   if (VD) {
1733     if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1734       const CXXRecordDecl* PD = CD->getParent();
1735       if (PD && PD->hasAttr<ScopedLockableAttr>())
1736         isScopedVar = true;
1737     }
1738   }
1739 
1740   for(Attr *Atconst : D->attrs()) {
1741     auto *At = const_cast<Attr *>(Atconst);
1742     switch (At->getKind()) {
1743       // When we encounter a lock function, we need to add the lock to our
1744       // lockset.
1745       case attr::AcquireCapability: {
1746         const auto *A = cast<AcquireCapabilityAttr>(At);
1747         Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1748                                             : ExclusiveLocksToAdd,
1749                               A, Exp, D, VD);
1750 
1751         CapDiagKind = ClassifyDiagnostic(A);
1752         break;
1753       }
1754 
1755       // An assert will add a lock to the lockset, but will not generate
1756       // a warning if it is already there, and will not generate a warning
1757       // if it is not removed.
1758       case attr::AssertExclusiveLock: {
1759         const auto *A = cast<AssertExclusiveLockAttr>(At);
1760 
1761         CapExprSet AssertLocks;
1762         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1763         for (const auto &AssertLock : AssertLocks)
1764           Analyzer->addLock(FSet,
1765                             llvm::make_unique<LockableFactEntry>(
1766                                 AssertLock, LK_Exclusive, Loc, false, true),
1767                             ClassifyDiagnostic(A));
1768         break;
1769       }
1770       case attr::AssertSharedLock: {
1771         const auto *A = cast<AssertSharedLockAttr>(At);
1772 
1773         CapExprSet AssertLocks;
1774         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1775         for (const auto &AssertLock : AssertLocks)
1776           Analyzer->addLock(FSet,
1777                             llvm::make_unique<LockableFactEntry>(
1778                                 AssertLock, LK_Shared, Loc, false, true),
1779                             ClassifyDiagnostic(A));
1780         break;
1781       }
1782 
1783       case attr::AssertCapability: {
1784         const auto *A = cast<AssertCapabilityAttr>(At);
1785         CapExprSet AssertLocks;
1786         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1787         for (const auto &AssertLock : AssertLocks)
1788           Analyzer->addLock(FSet,
1789                             llvm::make_unique<LockableFactEntry>(
1790                                 AssertLock,
1791                                 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1792                                 false, true),
1793                             ClassifyDiagnostic(A));
1794         break;
1795       }
1796 
1797       // When we encounter an unlock function, we need to remove unlocked
1798       // mutexes from the lockset, and flag a warning if they are not there.
1799       case attr::ReleaseCapability: {
1800         const auto *A = cast<ReleaseCapabilityAttr>(At);
1801         if (A->isGeneric())
1802           Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1803         else if (A->isShared())
1804           Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1805         else
1806           Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
1807 
1808         CapDiagKind = ClassifyDiagnostic(A);
1809         break;
1810       }
1811 
1812       case attr::RequiresCapability: {
1813         const auto *A = cast<RequiresCapabilityAttr>(At);
1814         for (auto *Arg : A->args()) {
1815           warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
1816                              POK_FunctionCall, ClassifyDiagnostic(A),
1817                              Exp->getExprLoc());
1818           // use for adopting a lock
1819           if (isScopedVar) {
1820             Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1821                                                 : ScopedExclusiveReqs,
1822                                   A, Exp, D, VD);
1823           }
1824         }
1825         break;
1826       }
1827 
1828       case attr::LocksExcluded: {
1829         const auto *A = cast<LocksExcludedAttr>(At);
1830         for (auto *Arg : A->args())
1831           warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
1832         break;
1833       }
1834 
1835       // Ignore attributes unrelated to thread-safety
1836       default:
1837         break;
1838     }
1839   }
1840 
1841   // Add locks.
1842   for (const auto &M : ExclusiveLocksToAdd)
1843     Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1844                                 M, LK_Exclusive, Loc, isScopedVar),
1845                       CapDiagKind);
1846   for (const auto &M : SharedLocksToAdd)
1847     Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1848                                 M, LK_Shared, Loc, isScopedVar),
1849                       CapDiagKind);
1850 
1851   if (isScopedVar) {
1852     // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1853     SourceLocation MLoc = VD->getLocation();
1854     DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
1855     // FIXME: does this store a pointer to DRE?
1856     CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
1857 
1858     std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1859               std::back_inserter(ExclusiveLocksToAdd));
1860     std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1861               std::back_inserter(SharedLocksToAdd));
1862     Analyzer->addLock(FSet,
1863                       llvm::make_unique<ScopedLockableFactEntry>(
1864                           Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1865                       CapDiagKind);
1866   }
1867 
1868   // Remove locks.
1869   // FIXME -- should only fully remove if the attribute refers to 'this'.
1870   bool Dtor = isa<CXXDestructorDecl>(D);
1871   for (const auto &M : ExclusiveLocksToRemove)
1872     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1873   for (const auto &M : SharedLocksToRemove)
1874     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1875   for (const auto &M : GenericLocksToRemove)
1876     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1877 }
1878 
1879 /// \brief For unary operations which read and write a variable, we need to
1880 /// check whether we hold any required mutexes. Reads are checked in
1881 /// VisitCastExpr.
1882 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1883   switch (UO->getOpcode()) {
1884     case UO_PostDec:
1885     case UO_PostInc:
1886     case UO_PreDec:
1887     case UO_PreInc:
1888       checkAccess(UO->getSubExpr(), AK_Written);
1889       break;
1890     default:
1891       break;
1892   }
1893 }
1894 
1895 /// For binary operations which assign to a variable (writes), we need to check
1896 /// whether we hold any required mutexes.
1897 /// FIXME: Deal with non-primitive types.
1898 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1899   if (!BO->isAssignmentOp())
1900     return;
1901 
1902   // adjust the context
1903   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1904 
1905   checkAccess(BO->getLHS(), AK_Written);
1906 }
1907 
1908 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1909 /// need to ensure we hold any required mutexes.
1910 /// FIXME: Deal with non-primitive types.
1911 void BuildLockset::VisitCastExpr(CastExpr *CE) {
1912   if (CE->getCastKind() != CK_LValueToRValue)
1913     return;
1914   checkAccess(CE->getSubExpr(), AK_Read);
1915 }
1916 
1917 void BuildLockset::VisitCallExpr(CallExpr *Exp) {
1918   bool ExamineArgs = true;
1919   bool OperatorFun = false;
1920 
1921   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1922     const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
1923     // ME can be null when calling a method pointer
1924     const CXXMethodDecl *MD = CE->getMethodDecl();
1925 
1926     if (ME && MD) {
1927       if (ME->isArrow()) {
1928         if (MD->isConst())
1929           checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1930         else // FIXME -- should be AK_Written
1931           checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1932       } else {
1933         if (MD->isConst())
1934           checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1935         else     // FIXME -- should be AK_Written
1936           checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1937       }
1938     }
1939   } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
1940     OperatorFun = true;
1941 
1942     auto OEop = OE->getOperator();
1943     switch (OEop) {
1944       case OO_Equal: {
1945         ExamineArgs = false;
1946         const Expr *Target = OE->getArg(0);
1947         const Expr *Source = OE->getArg(1);
1948         checkAccess(Target, AK_Written);
1949         checkAccess(Source, AK_Read);
1950         break;
1951       }
1952       case OO_Star:
1953       case OO_Arrow:
1954       case OO_Subscript: {
1955         const Expr *Obj = OE->getArg(0);
1956         checkAccess(Obj, AK_Read);
1957         if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1958           // Grrr.  operator* can be multiplication...
1959           checkPtAccess(Obj, AK_Read);
1960         }
1961         break;
1962       }
1963       default: {
1964         // TODO: get rid of this, and rely on pass-by-ref instead.
1965         const Expr *Obj = OE->getArg(0);
1966         checkAccess(Obj, AK_Read);
1967         break;
1968       }
1969     }
1970   }
1971 
1972   if (ExamineArgs) {
1973     if (FunctionDecl *FD = Exp->getDirectCallee()) {
1974       // NO_THREAD_SAFETY_ANALYSIS does double duty here.  Normally it
1975       // only turns off checking within the body of a function, but we also
1976       // use it to turn off checking in arguments to the function.  This
1977       // could result in some false negatives, but the alternative is to
1978       // create yet another attribute.
1979       if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
1980         unsigned Fn = FD->getNumParams();
1981         unsigned Cn = Exp->getNumArgs();
1982         unsigned Skip = 0;
1983 
1984         unsigned i = 0;
1985         if (OperatorFun) {
1986           if (isa<CXXMethodDecl>(FD)) {
1987             // First arg in operator call is implicit self argument,
1988             // and doesn't appear in the FunctionDecl.
1989             Skip = 1;
1990             Cn--;
1991           } else {
1992             // Ignore the first argument of operators; it's been checked above.
1993             i = 1;
1994           }
1995         }
1996         // Ignore default arguments
1997         unsigned n = (Fn < Cn) ? Fn : Cn;
1998 
1999         for (; i < n; ++i) {
2000           ParmVarDecl* Pvd = FD->getParamDecl(i);
2001           Expr* Arg = Exp->getArg(i+Skip);
2002           QualType Qt = Pvd->getType();
2003           if (Qt->isReferenceType())
2004             checkAccess(Arg, AK_Read, POK_PassByRef);
2005         }
2006       }
2007     }
2008   }
2009 
2010   auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2011   if(!D || !D->hasAttrs())
2012     return;
2013   handleCall(Exp, D);
2014 }
2015 
2016 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
2017   const CXXConstructorDecl *D = Exp->getConstructor();
2018   if (D && D->isCopyConstructor()) {
2019     const Expr* Source = Exp->getArg(0);
2020     checkAccess(Source, AK_Read);
2021   }
2022   // FIXME -- only handles constructors in DeclStmt below.
2023 }
2024 
2025 static CXXConstructorDecl *
2026 findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2027   // Prefer a move constructor over a copy constructor. If there's more than
2028   // one copy constructor or more than one move constructor, we arbitrarily
2029   // pick the first declared such constructor rather than trying to guess which
2030   // one is more appropriate.
2031   CXXConstructorDecl *CopyCtor = nullptr;
2032   for (auto *Ctor : RD->ctors()) {
2033     if (Ctor->isDeleted())
2034       continue;
2035     if (Ctor->isMoveConstructor())
2036       return Ctor;
2037     if (!CopyCtor && Ctor->isCopyConstructor())
2038       CopyCtor = Ctor;
2039   }
2040   return CopyCtor;
2041 }
2042 
2043 static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2044                                SourceLocation Loc) {
2045   ASTContext &Ctx = CD->getASTContext();
2046   return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2047                                   CD, true, Args, false, false, false, false,
2048                                   CXXConstructExpr::CK_Complete,
2049                                   SourceRange(Loc, Loc));
2050 }
2051 
2052 void BuildLockset::VisitDeclStmt(DeclStmt *S) {
2053   // adjust the context
2054   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2055 
2056   for (auto *D : S->getDeclGroup()) {
2057     if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2058       Expr *E = VD->getInit();
2059       if (!E)
2060         continue;
2061       E = E->IgnoreParens();
2062 
2063       // handle constructors that involve temporaries
2064       if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2065         E = EWC->getSubExpr();
2066       if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2067         E = BTE->getSubExpr();
2068 
2069       if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2070         const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2071         if (!CtorD || !CtorD->hasAttrs())
2072           continue;
2073         handleCall(E, CtorD, VD);
2074       } else if (isa<CallExpr>(E) && E->isRValue()) {
2075         // If the object is initialized by a function call that returns a
2076         // scoped lockable by value, use the attributes on the copy or move
2077         // constructor to figure out what effect that should have on the
2078         // lockset.
2079         // FIXME: Is this really the best way to handle this situation?
2080         auto *RD = E->getType()->getAsCXXRecordDecl();
2081         if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2082           continue;
2083         CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2084         if (!CtorD || !CtorD->hasAttrs())
2085           continue;
2086         handleCall(buildFakeCtorCall(CtorD, {E}, E->getLocStart()), CtorD, VD);
2087       }
2088     }
2089   }
2090 }
2091 
2092 /// \brief Compute the intersection of two locksets and issue warnings for any
2093 /// locks in the symmetric difference.
2094 ///
2095 /// This function is used at a merge point in the CFG when comparing the lockset
2096 /// of each branch being merged. For example, given the following sequence:
2097 /// A; if () then B; else C; D; we need to check that the lockset after B and C
2098 /// are the same. In the event of a difference, we use the intersection of these
2099 /// two locksets at the start of D.
2100 ///
2101 /// \param FSet1 The first lockset.
2102 /// \param FSet2 The second lockset.
2103 /// \param JoinLoc The location of the join point for error reporting
2104 /// \param LEK1 The error message to report if a mutex is missing from LSet1
2105 /// \param LEK2 The error message to report if a mutex is missing from Lset2
2106 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2107                                             const FactSet &FSet2,
2108                                             SourceLocation JoinLoc,
2109                                             LockErrorKind LEK1,
2110                                             LockErrorKind LEK2,
2111                                             bool Modify) {
2112   FactSet FSet1Orig = FSet1;
2113 
2114   // Find locks in FSet2 that conflict or are not in FSet1, and warn.
2115   for (const auto &Fact : FSet2) {
2116     const FactEntry *LDat1 = nullptr;
2117     const FactEntry *LDat2 = &FactMan[Fact];
2118     FactSet::iterator Iter1  = FSet1.findLockIter(FactMan, *LDat2);
2119     if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
2120 
2121     if (LDat1) {
2122       if (LDat1->kind() != LDat2->kind()) {
2123         Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2124                                          LDat2->loc(), LDat1->loc());
2125         if (Modify && LDat1->kind() != LK_Exclusive) {
2126           // Take the exclusive lock, which is the one in FSet2.
2127           *Iter1 = Fact;
2128         }
2129       }
2130       else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
2131         // The non-asserted lock in FSet2 is the one we want to track.
2132         *Iter1 = Fact;
2133       }
2134     } else {
2135       LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2136                                            Handler);
2137     }
2138   }
2139 
2140   // Find locks in FSet1 that are not in FSet2, and remove them.
2141   for (const auto &Fact : FSet1Orig) {
2142     const FactEntry *LDat1 = &FactMan[Fact];
2143     const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
2144 
2145     if (!LDat2) {
2146       LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2147                                            Handler);
2148       if (Modify)
2149         FSet1.removeLock(FactMan, *LDat1);
2150     }
2151   }
2152 }
2153 
2154 // Return true if block B never continues to its successors.
2155 static bool neverReturns(const CFGBlock *B) {
2156   if (B->hasNoReturnElement())
2157     return true;
2158   if (B->empty())
2159     return false;
2160 
2161   CFGElement Last = B->back();
2162   if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2163     if (isa<CXXThrowExpr>(S->getStmt()))
2164       return true;
2165   }
2166   return false;
2167 }
2168 
2169 /// \brief Check a function's CFG for thread-safety violations.
2170 ///
2171 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2172 /// at the end of each block, and issue warnings for thread safety violations.
2173 /// Each block in the CFG is traversed exactly once.
2174 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2175   // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2176   // For now, we just use the walker to set things up.
2177   threadSafety::CFGWalker walker;
2178   if (!walker.init(AC))
2179     return;
2180 
2181   // AC.dumpCFG(true);
2182   // threadSafety::printSCFG(walker);
2183 
2184   CFG *CFGraph = walker.getGraph();
2185   const NamedDecl *D = walker.getDecl();
2186   const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
2187   CurrentMethod = dyn_cast<CXXMethodDecl>(D);
2188 
2189   if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
2190     return;
2191 
2192   // FIXME: Do something a bit more intelligent inside constructor and
2193   // destructor code.  Constructors and destructors must assume unique access
2194   // to 'this', so checks on member variable access is disabled, but we should
2195   // still enable checks on other objects.
2196   if (isa<CXXConstructorDecl>(D))
2197     return;  // Don't check inside constructors.
2198   if (isa<CXXDestructorDecl>(D))
2199     return;  // Don't check inside destructors.
2200 
2201   Handler.enterFunction(CurrentFunction);
2202 
2203   BlockInfo.resize(CFGraph->getNumBlockIDs(),
2204     CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2205 
2206   // We need to explore the CFG via a "topological" ordering.
2207   // That way, we will be guaranteed to have information about required
2208   // predecessor locksets when exploring a new block.
2209   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
2210   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2211 
2212   // Mark entry block as reachable
2213   BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2214 
2215   // Compute SSA names for local variables
2216   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2217 
2218   // Fill in source locations for all CFGBlocks.
2219   findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2220 
2221   CapExprSet ExclusiveLocksAcquired;
2222   CapExprSet SharedLocksAcquired;
2223   CapExprSet LocksReleased;
2224 
2225   // Add locks from exclusive_locks_required and shared_locks_required
2226   // to initial lockset. Also turn off checking for lock and unlock functions.
2227   // FIXME: is there a more intelligent way to check lock/unlock functions?
2228   if (!SortedGraph->empty() && D->hasAttrs()) {
2229     const CFGBlock *FirstBlock = *SortedGraph->begin();
2230     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2231 
2232     CapExprSet ExclusiveLocksToAdd;
2233     CapExprSet SharedLocksToAdd;
2234     StringRef CapDiagKind = "mutex";
2235 
2236     SourceLocation Loc = D->getLocation();
2237     for (const auto *Attr : D->attrs()) {
2238       Loc = Attr->getLocation();
2239       if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2240         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2241                     nullptr, D);
2242         CapDiagKind = ClassifyDiagnostic(A);
2243       } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
2244         // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2245         // We must ignore such methods.
2246         if (A->args_size() == 0)
2247           return;
2248         // FIXME -- deal with exclusive vs. shared unlock functions?
2249         getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
2250         getMutexIDs(LocksReleased, A, nullptr, D);
2251         CapDiagKind = ClassifyDiagnostic(A);
2252       } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
2253         if (A->args_size() == 0)
2254           return;
2255         getMutexIDs(A->isShared() ? SharedLocksAcquired
2256                                   : ExclusiveLocksAcquired,
2257                     A, nullptr, D);
2258         CapDiagKind = ClassifyDiagnostic(A);
2259       } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2260         // Don't try to check trylock functions for now.
2261         return;
2262       } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2263         // Don't try to check trylock functions for now.
2264         return;
2265       } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2266         // Don't try to check trylock functions for now.
2267         return;
2268       }
2269     }
2270 
2271     // FIXME -- Loc can be wrong here.
2272     for (const auto &Mu : ExclusiveLocksToAdd) {
2273       auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2274       Entry->setDeclared(true);
2275       addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2276     }
2277     for (const auto &Mu : SharedLocksToAdd) {
2278       auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2279       Entry->setDeclared(true);
2280       addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2281     }
2282   }
2283 
2284   for (const auto *CurrBlock : *SortedGraph) {
2285     int CurrBlockID = CurrBlock->getBlockID();
2286     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2287 
2288     // Use the default initial lockset in case there are no predecessors.
2289     VisitedBlocks.insert(CurrBlock);
2290 
2291     // Iterate through the predecessor blocks and warn if the lockset for all
2292     // predecessors is not the same. We take the entry lockset of the current
2293     // block to be the intersection of all previous locksets.
2294     // FIXME: By keeping the intersection, we may output more errors in future
2295     // for a lock which is not in the intersection, but was in the union. We
2296     // may want to also keep the union in future. As an example, let's say
2297     // the intersection contains Mutex L, and the union contains L and M.
2298     // Later we unlock M. At this point, we would output an error because we
2299     // never locked M; although the real error is probably that we forgot to
2300     // lock M on all code paths. Conversely, let's say that later we lock M.
2301     // In this case, we should compare against the intersection instead of the
2302     // union because the real error is probably that we forgot to unlock M on
2303     // all code paths.
2304     bool LocksetInitialized = false;
2305     SmallVector<CFGBlock *, 8> SpecialBlocks;
2306     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2307          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
2308       // if *PI -> CurrBlock is a back edge
2309       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
2310         continue;
2311 
2312       int PrevBlockID = (*PI)->getBlockID();
2313       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2314 
2315       // Ignore edges from blocks that can't return.
2316       if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
2317         continue;
2318 
2319       // Okay, we can reach this block from the entry.
2320       CurrBlockInfo->Reachable = true;
2321 
2322       // If the previous block ended in a 'continue' or 'break' statement, then
2323       // a difference in locksets is probably due to a bug in that block, rather
2324       // than in some other predecessor. In that case, keep the other
2325       // predecessor's lockset.
2326       if (const Stmt *Terminator = (*PI)->getTerminator()) {
2327         if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2328           SpecialBlocks.push_back(*PI);
2329           continue;
2330         }
2331       }
2332 
2333       FactSet PrevLockset;
2334       getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2335 
2336       if (!LocksetInitialized) {
2337         CurrBlockInfo->EntrySet = PrevLockset;
2338         LocksetInitialized = true;
2339       } else {
2340         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2341                          CurrBlockInfo->EntryLoc,
2342                          LEK_LockedSomePredecessors);
2343       }
2344     }
2345 
2346     // Skip rest of block if it's not reachable.
2347     if (!CurrBlockInfo->Reachable)
2348       continue;
2349 
2350     // Process continue and break blocks. Assume that the lockset for the
2351     // resulting block is unaffected by any discrepancies in them.
2352     for (const auto *PrevBlock : SpecialBlocks) {
2353       int PrevBlockID = PrevBlock->getBlockID();
2354       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2355 
2356       if (!LocksetInitialized) {
2357         CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2358         LocksetInitialized = true;
2359       } else {
2360         // Determine whether this edge is a loop terminator for diagnostic
2361         // purposes. FIXME: A 'break' statement might be a loop terminator, but
2362         // it might also be part of a switch. Also, a subsequent destructor
2363         // might add to the lockset, in which case the real issue might be a
2364         // double lock on the other path.
2365         const Stmt *Terminator = PrevBlock->getTerminator();
2366         bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2367 
2368         FactSet PrevLockset;
2369         getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2370                        PrevBlock, CurrBlock);
2371 
2372         // Do not update EntrySet.
2373         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2374                          PrevBlockInfo->ExitLoc,
2375                          IsLoop ? LEK_LockedSomeLoopIterations
2376                                 : LEK_LockedSomePredecessors,
2377                          false);
2378       }
2379     }
2380 
2381     BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2382 
2383     // Visit all the statements in the basic block.
2384     for (const auto &BI : *CurrBlock) {
2385       switch (BI.getKind()) {
2386         case CFGElement::Statement: {
2387           CFGStmt CS = BI.castAs<CFGStmt>();
2388           LocksetBuilder.Visit(const_cast<Stmt *>(CS.getStmt()));
2389           break;
2390         }
2391         // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2392         case CFGElement::AutomaticObjectDtor: {
2393           CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
2394           auto *DD = const_cast<CXXDestructorDecl *>(
2395               AD.getDestructorDecl(AC.getASTContext()));
2396           if (!DD->hasAttrs())
2397             break;
2398 
2399           // Create a dummy expression,
2400           auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
2401           DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
2402                           VK_LValue, AD.getTriggerStmt()->getLocEnd());
2403           LocksetBuilder.handleCall(&DRE, DD);
2404           break;
2405         }
2406         default:
2407           break;
2408       }
2409     }
2410     CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2411 
2412     // For every back edge from CurrBlock (the end of the loop) to another block
2413     // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2414     // the one held at the beginning of FirstLoopBlock. We can look up the
2415     // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2416     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2417          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
2418       // if CurrBlock -> *SI is *not* a back edge
2419       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
2420         continue;
2421 
2422       CFGBlock *FirstLoopBlock = *SI;
2423       CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2424       CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2425       intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2426                        PreLoop->EntryLoc,
2427                        LEK_LockedSomeLoopIterations,
2428                        false);
2429     }
2430   }
2431 
2432   CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2433   CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
2434 
2435   // Skip the final check if the exit block is unreachable.
2436   if (!Final->Reachable)
2437     return;
2438 
2439   // By default, we expect all locks held on entry to be held on exit.
2440   FactSet ExpectedExitSet = Initial->EntrySet;
2441 
2442   // Adjust the expected exit set by adding or removing locks, as declared
2443   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
2444   // issue the appropriate warning.
2445   // FIXME: the location here is not quite right.
2446   for (const auto &Lock : ExclusiveLocksAcquired)
2447     ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2448                                          Lock, LK_Exclusive, D->getLocation()));
2449   for (const auto &Lock : SharedLocksAcquired)
2450     ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2451                                          Lock, LK_Shared, D->getLocation()));
2452   for (const auto &Lock : LocksReleased)
2453     ExpectedExitSet.removeLock(FactMan, Lock);
2454 
2455   // FIXME: Should we call this function for all blocks which exit the function?
2456   intersectAndWarn(ExpectedExitSet, Final->ExitSet,
2457                    Final->ExitLoc,
2458                    LEK_LockedAtEndOfFunction,
2459                    LEK_NotLockedAtEndOfFunction,
2460                    false);
2461 
2462   Handler.leaveFunction(CurrentFunction);
2463 }
2464 
2465 /// \brief Check a function's CFG for thread-safety violations.
2466 ///
2467 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2468 /// at the end of each block, and issue warnings for thread safety violations.
2469 /// Each block in the CFG is traversed exactly once.
2470 void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2471                                            ThreadSafetyHandler &Handler,
2472                                            BeforeSet **BSet) {
2473   if (!*BSet)
2474     *BSet = new BeforeSet;
2475   ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
2476   Analyzer.runAnalysis(AC);
2477 }
2478 
2479 void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
2480 
2481 /// \brief Helper function that returns a LockKind required for the given level
2482 /// of access.
2483 LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
2484   switch (AK) {
2485     case AK_Read :
2486       return LK_Shared;
2487     case AK_Written :
2488       return LK_Exclusive;
2489   }
2490   llvm_unreachable("Unknown AccessKind");
2491 }
2492