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