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