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, const 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                                    const PostOrderCFGView *SortedGraph,
1293                                    std::vector<CFGBlockInfo> &BlockInfo) {
1294   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1295 
1296   CtxIndices.resize(CFGraph->getNumBlockIDs());
1297 
1298   for (const auto *CurrBlock : *SortedGraph) {
1299     int CurrBlockID = CurrBlock->getBlockID();
1300     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1301 
1302     VisitedBlocks.insert(CurrBlock);
1303 
1304     // Calculate the entry context for the current block
1305     bool HasBackEdges = false;
1306     bool CtxInit = true;
1307     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1308          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
1309       // if *PI -> CurrBlock is a back edge, so skip it
1310       if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1311         HasBackEdges = true;
1312         continue;
1313       }
1314 
1315       int PrevBlockID = (*PI)->getBlockID();
1316       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1317 
1318       if (CtxInit) {
1319         CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1320         CtxInit = false;
1321       }
1322       else {
1323         CurrBlockInfo->EntryContext =
1324           intersectContexts(CurrBlockInfo->EntryContext,
1325                             PrevBlockInfo->ExitContext);
1326       }
1327     }
1328 
1329     // Duplicate the context if we have back-edges, so we can call
1330     // intersectBackEdges later.
1331     if (HasBackEdges)
1332       CurrBlockInfo->EntryContext =
1333         createReferenceContext(CurrBlockInfo->EntryContext);
1334 
1335     // Create a starting context index for the current block
1336     saveContext(0, CurrBlockInfo->EntryContext);
1337     CurrBlockInfo->EntryIndex = getContextIndex();
1338 
1339     // Visit all the statements in the basic block.
1340     VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1341     for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1342          BE = CurrBlock->end(); BI != BE; ++BI) {
1343       switch (BI->getKind()) {
1344         case CFGElement::Statement: {
1345           CFGStmt CS = BI->castAs<CFGStmt>();
1346           VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
1347           break;
1348         }
1349         default:
1350           break;
1351       }
1352     }
1353     CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1354 
1355     // Mark variables on back edges as "unknown" if they've been changed.
1356     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1357          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
1358       // if CurrBlock -> *SI is *not* a back edge
1359       if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1360         continue;
1361 
1362       CFGBlock *FirstLoopBlock = *SI;
1363       Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1364       Context LoopEnd   = CurrBlockInfo->ExitContext;
1365       intersectBackEdge(LoopBegin, LoopEnd);
1366     }
1367   }
1368 
1369   // Put an extra entry at the end of the indexed context array
1370   unsigned exitID = CFGraph->getExit().getBlockID();
1371   saveContext(0, BlockInfo[exitID].ExitContext);
1372 }
1373 
1374 /// Find the appropriate source locations to use when producing diagnostics for
1375 /// each block in the CFG.
1376 static void findBlockLocations(CFG *CFGraph,
1377                                const PostOrderCFGView *SortedGraph,
1378                                std::vector<CFGBlockInfo> &BlockInfo) {
1379   for (const auto *CurrBlock : *SortedGraph) {
1380     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1381 
1382     // Find the source location of the last statement in the block, if the
1383     // block is not empty.
1384     if (const Stmt *S = CurrBlock->getTerminator()) {
1385       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1386     } else {
1387       for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1388            BE = CurrBlock->rend(); BI != BE; ++BI) {
1389         // FIXME: Handle other CFGElement kinds.
1390         if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1391           CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1392           break;
1393         }
1394       }
1395     }
1396 
1397     if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1398       // This block contains at least one statement. Find the source location
1399       // of the first statement in the block.
1400       for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1401            BE = CurrBlock->end(); BI != BE; ++BI) {
1402         // FIXME: Handle other CFGElement kinds.
1403         if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1404           CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1405           break;
1406         }
1407       }
1408     } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1409                CurrBlock != &CFGraph->getExit()) {
1410       // The block is empty, and has a single predecessor. Use its exit
1411       // location.
1412       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1413           BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1414     }
1415   }
1416 }
1417 
1418 /// \brief Class which implements the core thread safety analysis routines.
1419 class ThreadSafetyAnalyzer {
1420   friend class BuildLockset;
1421 
1422   ThreadSafetyHandler       &Handler;
1423   LocalVariableMap          LocalVarMap;
1424   FactManager               FactMan;
1425   std::vector<CFGBlockInfo> BlockInfo;
1426 
1427 public:
1428   ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1429 
1430   void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat,
1431                StringRef DiagKind);
1432   void removeLock(FactSet &FSet, const SExpr &Mutex, SourceLocation UnlockLoc,
1433                   bool FullyRemove, LockKind Kind, StringRef DiagKind);
1434 
1435   template <typename AttrType>
1436   void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1437                    const NamedDecl *D, VarDecl *SelfDecl=0);
1438 
1439   template <class AttrType>
1440   void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1441                    const NamedDecl *D,
1442                    const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1443                    Expr *BrE, bool Neg);
1444 
1445   const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1446                                      bool &Negate);
1447 
1448   void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1449                       const CFGBlock* PredBlock,
1450                       const CFGBlock *CurrBlock);
1451 
1452   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1453                         SourceLocation JoinLoc,
1454                         LockErrorKind LEK1, LockErrorKind LEK2,
1455                         bool Modify=true);
1456 
1457   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1458                         SourceLocation JoinLoc, LockErrorKind LEK1,
1459                         bool Modify=true) {
1460     intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
1461   }
1462 
1463   void runAnalysis(AnalysisDeclContext &AC);
1464 };
1465 
1466 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1467 static const ValueDecl *getValueDecl(const Expr *Exp) {
1468   if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1469     return getValueDecl(CE->getSubExpr());
1470 
1471   if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1472     return DR->getDecl();
1473 
1474   if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1475     return ME->getMemberDecl();
1476 
1477   return nullptr;
1478 }
1479 
1480 template <typename Ty>
1481 class has_arg_iterator {
1482   typedef char yes[1];
1483   typedef char no[2];
1484 
1485   template <typename Inner>
1486   static yes& test(Inner *I, decltype(I->args_begin()) * = nullptr);
1487 
1488   template <typename>
1489   static no& test(...);
1490 
1491 public:
1492   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1493 };
1494 
1495 static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1496   return A->getName();
1497 }
1498 
1499 static StringRef ClassifyDiagnostic(QualType VDT) {
1500   // We need to look at the declaration of the type of the value to determine
1501   // which it is. The type should either be a record or a typedef, or a pointer
1502   // or reference thereof.
1503   if (const auto *RT = VDT->getAs<RecordType>()) {
1504     if (const auto *RD = RT->getDecl())
1505       if (const auto *CA = RD->getAttr<CapabilityAttr>())
1506         return ClassifyDiagnostic(CA);
1507   } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1508     if (const auto *TD = TT->getDecl())
1509       if (const auto *CA = TD->getAttr<CapabilityAttr>())
1510         return ClassifyDiagnostic(CA);
1511   } else if (VDT->isPointerType() || VDT->isReferenceType())
1512     return ClassifyDiagnostic(VDT->getPointeeType());
1513 
1514   return "mutex";
1515 }
1516 
1517 static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1518   assert(VD && "No ValueDecl passed");
1519 
1520   // The ValueDecl is the declaration of a mutex or role (hopefully).
1521   return ClassifyDiagnostic(VD->getType());
1522 }
1523 
1524 template <typename AttrTy>
1525 static typename std::enable_if<!has_arg_iterator<AttrTy>::value,
1526                                StringRef>::type
1527 ClassifyDiagnostic(const AttrTy *A) {
1528   if (const ValueDecl *VD = getValueDecl(A->getArg()))
1529     return ClassifyDiagnostic(VD);
1530   return "mutex";
1531 }
1532 
1533 template <typename AttrTy>
1534 static typename std::enable_if<has_arg_iterator<AttrTy>::value,
1535                                StringRef>::type
1536 ClassifyDiagnostic(const AttrTy *A) {
1537   for (auto I = A->args_begin(), E = A->args_end(); I != E; ++I) {
1538     if (const ValueDecl *VD = getValueDecl(*I))
1539       return ClassifyDiagnostic(VD);
1540   }
1541   return "mutex";
1542 }
1543 
1544 /// \brief Add a new lock to the lockset, warning if the lock is already there.
1545 /// \param Mutex -- the Mutex expression for the lock
1546 /// \param LDat  -- the LockData for the lock
1547 void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
1548                                    const LockData &LDat, StringRef DiagKind) {
1549   // FIXME: deal with acquired before/after annotations.
1550   // FIXME: Don't always warn when we have support for reentrant locks.
1551   if (Mutex.shouldIgnore())
1552     return;
1553 
1554   if (FSet.findLock(FactMan, Mutex)) {
1555     if (!LDat.Asserted)
1556       Handler.handleDoubleLock(DiagKind, Mutex.toString(), LDat.AcquireLoc);
1557   } else {
1558     FSet.addLock(FactMan, Mutex, LDat);
1559   }
1560 }
1561 
1562 
1563 /// \brief Remove a lock from the lockset, warning if the lock is not there.
1564 /// \param Mutex The lock expression corresponding to the lock to be removed
1565 /// \param UnlockLoc The source location of the unlock (only used in error msg)
1566 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const SExpr &Mutex,
1567                                       SourceLocation UnlockLoc,
1568                                       bool FullyRemove, LockKind ReceivedKind,
1569                                       StringRef DiagKind) {
1570   if (Mutex.shouldIgnore())
1571     return;
1572 
1573   const LockData *LDat = FSet.findLock(FactMan, Mutex);
1574   if (!LDat) {
1575     Handler.handleUnmatchedUnlock(DiagKind, Mutex.toString(), UnlockLoc);
1576     return;
1577   }
1578 
1579   // Generic lock removal doesn't care about lock kind mismatches, but
1580   // otherwise diagnose when the lock kinds are mismatched.
1581   if (ReceivedKind != LK_Generic && LDat->LKind != ReceivedKind) {
1582     Handler.handleIncorrectUnlockKind(DiagKind, Mutex.toString(), LDat->LKind,
1583                                       ReceivedKind, UnlockLoc);
1584     return;
1585   }
1586 
1587   if (LDat->UnderlyingMutex.isValid()) {
1588     // This is scoped lockable object, which manages the real mutex.
1589     if (FullyRemove) {
1590       // We're destroying the managing object.
1591       // Remove the underlying mutex if it exists; but don't warn.
1592       if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1593         FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1594     } else {
1595       // We're releasing the underlying mutex, but not destroying the
1596       // managing object.  Warn on dual release.
1597       if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
1598         Handler.handleUnmatchedUnlock(
1599             DiagKind, LDat->UnderlyingMutex.toString(), UnlockLoc);
1600       }
1601       FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1602       return;
1603     }
1604   }
1605   FSet.removeLock(FactMan, Mutex);
1606 }
1607 
1608 
1609 /// \brief Extract the list of mutexIDs from the attribute on an expression,
1610 /// and push them onto Mtxs, discarding any duplicates.
1611 template <typename AttrType>
1612 void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1613                                        Expr *Exp, const NamedDecl *D,
1614                                        VarDecl *SelfDecl) {
1615   typedef typename AttrType::args_iterator iterator_type;
1616 
1617   if (Attr->args_size() == 0) {
1618     // The mutex held is the "this" object.
1619     SExpr Mu(0, Exp, D, SelfDecl);
1620     if (!Mu.isValid())
1621       SExpr::warnInvalidLock(Handler, 0, Exp, D, ClassifyDiagnostic(Attr));
1622     else
1623       Mtxs.push_back_nodup(Mu);
1624     return;
1625   }
1626 
1627   for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
1628     SExpr Mu(*I, Exp, D, SelfDecl);
1629     if (!Mu.isValid())
1630       SExpr::warnInvalidLock(Handler, *I, Exp, D, ClassifyDiagnostic(Attr));
1631     else
1632       Mtxs.push_back_nodup(Mu);
1633   }
1634 }
1635 
1636 
1637 /// \brief Extract the list of mutexIDs from a trylock attribute.  If the
1638 /// trylock applies to the given edge, then push them onto Mtxs, discarding
1639 /// any duplicates.
1640 template <class AttrType>
1641 void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1642                                        Expr *Exp, const NamedDecl *D,
1643                                        const CFGBlock *PredBlock,
1644                                        const CFGBlock *CurrBlock,
1645                                        Expr *BrE, bool Neg) {
1646   // Find out which branch has the lock
1647   bool branch = 0;
1648   if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1649     branch = BLE->getValue();
1650   }
1651   else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1652     branch = ILE->getValue().getBoolValue();
1653   }
1654   int branchnum = branch ? 0 : 1;
1655   if (Neg) branchnum = !branchnum;
1656 
1657   // If we've taken the trylock branch, then add the lock
1658   int i = 0;
1659   for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1660        SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1661     if (*SI == CurrBlock && i == branchnum) {
1662       getMutexIDs(Mtxs, Attr, Exp, D);
1663     }
1664   }
1665 }
1666 
1667 
1668 bool getStaticBooleanValue(Expr* E, bool& TCond) {
1669   if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1670     TCond = false;
1671     return true;
1672   } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1673     TCond = BLE->getValue();
1674     return true;
1675   } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1676     TCond = ILE->getValue().getBoolValue();
1677     return true;
1678   } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1679     return getStaticBooleanValue(CE->getSubExpr(), TCond);
1680   }
1681   return false;
1682 }
1683 
1684 
1685 // If Cond can be traced back to a function call, return the call expression.
1686 // The negate variable should be called with false, and will be set to true
1687 // if the function call is negated, e.g. if (!mu.tryLock(...))
1688 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1689                                                          LocalVarContext C,
1690                                                          bool &Negate) {
1691   if (!Cond)
1692     return 0;
1693 
1694   if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1695     return CallExp;
1696   }
1697   else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1698     return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1699   }
1700   else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1701     return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1702   }
1703   else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1704     return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1705   }
1706   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1707     const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1708     return getTrylockCallExpr(E, C, Negate);
1709   }
1710   else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1711     if (UOP->getOpcode() == UO_LNot) {
1712       Negate = !Negate;
1713       return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1714     }
1715     return 0;
1716   }
1717   else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1718     if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1719       if (BOP->getOpcode() == BO_NE)
1720         Negate = !Negate;
1721 
1722       bool TCond = false;
1723       if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1724         if (!TCond) Negate = !Negate;
1725         return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1726       }
1727       TCond = false;
1728       if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1729         if (!TCond) Negate = !Negate;
1730         return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1731       }
1732       return 0;
1733     }
1734     if (BOP->getOpcode() == BO_LAnd) {
1735       // LHS must have been evaluated in a different block.
1736       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1737     }
1738     if (BOP->getOpcode() == BO_LOr) {
1739       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1740     }
1741     return 0;
1742   }
1743   return 0;
1744 }
1745 
1746 
1747 /// \brief Find the lockset that holds on the edge between PredBlock
1748 /// and CurrBlock.  The edge set is the exit set of PredBlock (passed
1749 /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1750 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1751                                           const FactSet &ExitSet,
1752                                           const CFGBlock *PredBlock,
1753                                           const CFGBlock *CurrBlock) {
1754   Result = ExitSet;
1755 
1756   const Stmt *Cond = PredBlock->getTerminatorCondition();
1757   if (!Cond)
1758     return;
1759 
1760   bool Negate = false;
1761   const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1762   const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1763   StringRef CapDiagKind = "mutex";
1764 
1765   CallExpr *Exp =
1766     const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
1767   if (!Exp)
1768     return;
1769 
1770   NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1771   if(!FunDecl || !FunDecl->hasAttrs())
1772     return;
1773 
1774   MutexIDList ExclusiveLocksToAdd;
1775   MutexIDList SharedLocksToAdd;
1776 
1777   // If the condition is a call to a Trylock function, then grab the attributes
1778   AttrVec &ArgAttrs = FunDecl->getAttrs();
1779   for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1780     Attr *Attr = ArgAttrs[i];
1781     switch (Attr->getKind()) {
1782       case attr::ExclusiveTrylockFunction: {
1783         ExclusiveTrylockFunctionAttr *A =
1784           cast<ExclusiveTrylockFunctionAttr>(Attr);
1785         getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1786                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1787         CapDiagKind = ClassifyDiagnostic(A);
1788         break;
1789       }
1790       case attr::SharedTrylockFunction: {
1791         SharedTrylockFunctionAttr *A =
1792           cast<SharedTrylockFunctionAttr>(Attr);
1793         getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
1794                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1795         CapDiagKind = ClassifyDiagnostic(A);
1796         break;
1797       }
1798       default:
1799         break;
1800     }
1801   }
1802 
1803   // Add and remove locks.
1804   SourceLocation Loc = Exp->getExprLoc();
1805   for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1806     addLock(Result, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
1807             CapDiagKind);
1808   for (const auto &SharedLockToAdd : SharedLocksToAdd)
1809     addLock(Result, SharedLockToAdd, LockData(Loc, LK_Shared), CapDiagKind);
1810 }
1811 
1812 /// \brief We use this class to visit different types of expressions in
1813 /// CFGBlocks, and build up the lockset.
1814 /// An expression may cause us to add or remove locks from the lockset, or else
1815 /// output error messages related to missing locks.
1816 /// FIXME: In future, we may be able to not inherit from a visitor.
1817 class BuildLockset : public StmtVisitor<BuildLockset> {
1818   friend class ThreadSafetyAnalyzer;
1819 
1820   ThreadSafetyAnalyzer *Analyzer;
1821   FactSet FSet;
1822   LocalVariableMap::Context LVarCtx;
1823   unsigned CtxIndex;
1824 
1825   // Helper functions
1826 
1827   void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1828                           Expr *MutexExp, ProtectedOperationKind POK,
1829                           StringRef DiagKind);
1830   void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1831                        StringRef DiagKind);
1832 
1833   void checkAccess(const Expr *Exp, AccessKind AK);
1834   void checkPtAccess(const Expr *Exp, AccessKind AK);
1835 
1836   void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
1837 
1838 public:
1839   BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1840     : StmtVisitor<BuildLockset>(),
1841       Analyzer(Anlzr),
1842       FSet(Info.EntrySet),
1843       LVarCtx(Info.EntryContext),
1844       CtxIndex(Info.EntryIndex)
1845   {}
1846 
1847   void VisitUnaryOperator(UnaryOperator *UO);
1848   void VisitBinaryOperator(BinaryOperator *BO);
1849   void VisitCastExpr(CastExpr *CE);
1850   void VisitCallExpr(CallExpr *Exp);
1851   void VisitCXXConstructExpr(CXXConstructExpr *Exp);
1852   void VisitDeclStmt(DeclStmt *S);
1853 };
1854 
1855 /// \brief Warn if the LSet does not contain a lock sufficient to protect access
1856 /// of at least the passed in AccessKind.
1857 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1858                                       AccessKind AK, Expr *MutexExp,
1859                                       ProtectedOperationKind POK,
1860                                       StringRef DiagKind) {
1861   LockKind LK = getLockKindFromAccessKind(AK);
1862 
1863   SExpr Mutex(MutexExp, Exp, D);
1864   if (!Mutex.isValid()) {
1865     SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
1866     return;
1867   } else if (Mutex.shouldIgnore()) {
1868     return;
1869   }
1870 
1871   LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
1872   bool NoError = true;
1873   if (!LDat) {
1874     // No exact match found.  Look for a partial match.
1875     FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1876     if (FEntry) {
1877       // Warn that there's no precise match.
1878       LDat = &FEntry->LDat;
1879       std::string PartMatchStr = FEntry->MutID.toString();
1880       StringRef   PartMatchName(PartMatchStr);
1881       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1882                                            LK, Exp->getExprLoc(),
1883                                            &PartMatchName);
1884     } else {
1885       // Warn that there's no match at all.
1886       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1887                                            LK, Exp->getExprLoc());
1888     }
1889     NoError = false;
1890   }
1891   // Make sure the mutex we found is the right kind.
1892   if (NoError && LDat && !LDat->isAtLeast(LK))
1893     Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(), LK,
1894                                          Exp->getExprLoc());
1895 }
1896 
1897 /// \brief Warn if the LSet contains the given lock.
1898 void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1899                                    Expr *MutexExp,
1900                                    StringRef DiagKind) {
1901   SExpr Mutex(MutexExp, Exp, D);
1902   if (!Mutex.isValid()) {
1903     SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
1904     return;
1905   }
1906 
1907   LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
1908   if (LDat)
1909     Analyzer->Handler.handleFunExcludesLock(
1910         DiagKind, D->getNameAsString(), Mutex.toString(), Exp->getExprLoc());
1911 }
1912 
1913 /// \brief Checks guarded_by and pt_guarded_by attributes.
1914 /// Whenever we identify an access (read or write) to a DeclRefExpr that is
1915 /// marked with guarded_by, we must ensure the appropriate mutexes are held.
1916 /// Similarly, we check if the access is to an expression that dereferences
1917 /// a pointer marked with pt_guarded_by.
1918 void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1919   Exp = Exp->IgnoreParenCasts();
1920 
1921   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1922     // For dereferences
1923     if (UO->getOpcode() == clang::UO_Deref)
1924       checkPtAccess(UO->getSubExpr(), AK);
1925     return;
1926   }
1927 
1928   if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1929     checkPtAccess(AE->getLHS(), AK);
1930     return;
1931   }
1932 
1933   if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1934     if (ME->isArrow())
1935       checkPtAccess(ME->getBase(), AK);
1936     else
1937       checkAccess(ME->getBase(), AK);
1938   }
1939 
1940   const ValueDecl *D = getValueDecl(Exp);
1941   if (!D || !D->hasAttrs())
1942     return;
1943 
1944   if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
1945     Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarAccess, AK,
1946                                         Exp->getExprLoc());
1947 
1948   for (const auto *I : D->specific_attrs<GuardedByAttr>())
1949     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess,
1950                        ClassifyDiagnostic(I));
1951 }
1952 
1953 /// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1954 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
1955   while (true) {
1956     if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1957       Exp = PE->getSubExpr();
1958       continue;
1959     }
1960     if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1961       if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1962         // If it's an actual array, and not a pointer, then it's elements
1963         // are protected by GUARDED_BY, not PT_GUARDED_BY;
1964         checkAccess(CE->getSubExpr(), AK);
1965         return;
1966       }
1967       Exp = CE->getSubExpr();
1968       continue;
1969     }
1970     break;
1971   }
1972 
1973   const ValueDecl *D = getValueDecl(Exp);
1974   if (!D || !D->hasAttrs())
1975     return;
1976 
1977   if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
1978     Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarDereference, AK,
1979                                         Exp->getExprLoc());
1980 
1981   for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1982     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference,
1983                        ClassifyDiagnostic(I));
1984 }
1985 
1986 /// \brief Process a function call, method call, constructor call,
1987 /// or destructor call.  This involves looking at the attributes on the
1988 /// corresponding function/method/constructor/destructor, issuing warnings,
1989 /// and updating the locksets accordingly.
1990 ///
1991 /// FIXME: For classes annotated with one of the guarded annotations, we need
1992 /// to treat const method calls as reads and non-const method calls as writes,
1993 /// and check that the appropriate locks are held. Non-const method calls with
1994 /// the same signature as const method calls can be also treated as reads.
1995 ///
1996 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1997   SourceLocation Loc = Exp->getExprLoc();
1998   const AttrVec &ArgAttrs = D->getAttrs();
1999   MutexIDList ExclusiveLocksToAdd, SharedLocksToAdd;
2000   MutexIDList ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
2001   StringRef CapDiagKind = "mutex";
2002 
2003   for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
2004     Attr *At = const_cast<Attr*>(ArgAttrs[i]);
2005     switch (At->getKind()) {
2006       // When we encounter a lock function, we need to add the lock to our
2007       // lockset.
2008       case attr::AcquireCapability: {
2009         auto *A = cast<AcquireCapabilityAttr>(At);
2010         Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
2011                                             : ExclusiveLocksToAdd,
2012                               A, Exp, D, VD);
2013 
2014         CapDiagKind = ClassifyDiagnostic(A);
2015         break;
2016       }
2017 
2018       // An assert will add a lock to the lockset, but will not generate
2019       // a warning if it is already there, and will not generate a warning
2020       // if it is not removed.
2021       case attr::AssertExclusiveLock: {
2022         AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
2023 
2024         MutexIDList AssertLocks;
2025         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
2026         for (const auto &AssertLock : AssertLocks)
2027           Analyzer->addLock(FSet, AssertLock,
2028                             LockData(Loc, LK_Exclusive, false, true),
2029                             ClassifyDiagnostic(A));
2030         break;
2031       }
2032       case attr::AssertSharedLock: {
2033         AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
2034 
2035         MutexIDList AssertLocks;
2036         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
2037         for (const auto &AssertLock : AssertLocks)
2038           Analyzer->addLock(FSet, AssertLock,
2039                             LockData(Loc, LK_Shared, false, true),
2040                             ClassifyDiagnostic(A));
2041         break;
2042       }
2043 
2044       // When we encounter an unlock function, we need to remove unlocked
2045       // mutexes from the lockset, and flag a warning if they are not there.
2046       case attr::ReleaseCapability: {
2047         auto *A = cast<ReleaseCapabilityAttr>(At);
2048         if (A->isGeneric())
2049           Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
2050         else if (A->isShared())
2051           Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
2052         else
2053           Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
2054 
2055         CapDiagKind = ClassifyDiagnostic(A);
2056         break;
2057       }
2058 
2059       case attr::RequiresCapability: {
2060         RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
2061 
2062         for (RequiresCapabilityAttr::args_iterator I = A->args_begin(),
2063              E = A->args_end(); I != E; ++I)
2064           warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, *I,
2065                              POK_FunctionCall, ClassifyDiagnostic(A));
2066         break;
2067       }
2068 
2069       case attr::LocksExcluded: {
2070         LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
2071 
2072         for (LocksExcludedAttr::args_iterator I = A->args_begin(),
2073             E = A->args_end(); I != E; ++I) {
2074           warnIfMutexHeld(D, Exp, *I, ClassifyDiagnostic(A));
2075         }
2076         break;
2077       }
2078 
2079       // Ignore attributes unrelated to thread-safety
2080       default:
2081         break;
2082     }
2083   }
2084 
2085   // Figure out if we're calling the constructor of scoped lockable class
2086   bool isScopedVar = false;
2087   if (VD) {
2088     if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
2089       const CXXRecordDecl* PD = CD->getParent();
2090       if (PD && PD->hasAttr<ScopedLockableAttr>())
2091         isScopedVar = true;
2092     }
2093   }
2094 
2095   // Add locks.
2096   for (const auto &M : ExclusiveLocksToAdd)
2097     Analyzer->addLock(FSet, M, LockData(Loc, LK_Exclusive, isScopedVar),
2098                       CapDiagKind);
2099   for (const auto &M : SharedLocksToAdd)
2100     Analyzer->addLock(FSet, M, LockData(Loc, LK_Shared, isScopedVar),
2101                       CapDiagKind);
2102 
2103   // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2104   // FIXME -- this doesn't work if we acquire multiple locks.
2105   if (isScopedVar) {
2106     SourceLocation MLoc = VD->getLocation();
2107     DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
2108     SExpr SMutex(&DRE, 0, 0);
2109 
2110     for (const auto &M : ExclusiveLocksToAdd)
2111       Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive, M),
2112                         CapDiagKind);
2113     for (const auto &M : SharedLocksToAdd)
2114       Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared, M),
2115                         CapDiagKind);
2116   }
2117 
2118   // Remove locks.
2119   // FIXME -- should only fully remove if the attribute refers to 'this'.
2120   bool Dtor = isa<CXXDestructorDecl>(D);
2121   for (const auto &M : ExclusiveLocksToRemove)
2122     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
2123   for (const auto &M : SharedLocksToRemove)
2124     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
2125   for (const auto &M : GenericLocksToRemove)
2126     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
2127 }
2128 
2129 
2130 /// \brief For unary operations which read and write a variable, we need to
2131 /// check whether we hold any required mutexes. Reads are checked in
2132 /// VisitCastExpr.
2133 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2134   switch (UO->getOpcode()) {
2135     case clang::UO_PostDec:
2136     case clang::UO_PostInc:
2137     case clang::UO_PreDec:
2138     case clang::UO_PreInc: {
2139       checkAccess(UO->getSubExpr(), AK_Written);
2140       break;
2141     }
2142     default:
2143       break;
2144   }
2145 }
2146 
2147 /// For binary operations which assign to a variable (writes), we need to check
2148 /// whether we hold any required mutexes.
2149 /// FIXME: Deal with non-primitive types.
2150 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2151   if (!BO->isAssignmentOp())
2152     return;
2153 
2154   // adjust the context
2155   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
2156 
2157   checkAccess(BO->getLHS(), AK_Written);
2158 }
2159 
2160 
2161 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2162 /// need to ensure we hold any required mutexes.
2163 /// FIXME: Deal with non-primitive types.
2164 void BuildLockset::VisitCastExpr(CastExpr *CE) {
2165   if (CE->getCastKind() != CK_LValueToRValue)
2166     return;
2167   checkAccess(CE->getSubExpr(), AK_Read);
2168 }
2169 
2170 
2171 void BuildLockset::VisitCallExpr(CallExpr *Exp) {
2172   if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2173     MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2174     // ME can be null when calling a method pointer
2175     CXXMethodDecl *MD = CE->getMethodDecl();
2176 
2177     if (ME && MD) {
2178       if (ME->isArrow()) {
2179         if (MD->isConst()) {
2180           checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2181         } else {  // FIXME -- should be AK_Written
2182           checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2183         }
2184       } else {
2185         if (MD->isConst())
2186           checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2187         else     // FIXME -- should be AK_Written
2188           checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2189       }
2190     }
2191   } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2192     switch (OE->getOperator()) {
2193       case OO_Equal: {
2194         const Expr *Target = OE->getArg(0);
2195         const Expr *Source = OE->getArg(1);
2196         checkAccess(Target, AK_Written);
2197         checkAccess(Source, AK_Read);
2198         break;
2199       }
2200       case OO_Star:
2201       case OO_Arrow:
2202       case OO_Subscript: {
2203         const Expr *Obj = OE->getArg(0);
2204         checkAccess(Obj, AK_Read);
2205         checkPtAccess(Obj, AK_Read);
2206         break;
2207       }
2208       default: {
2209         const Expr *Obj = OE->getArg(0);
2210         checkAccess(Obj, AK_Read);
2211         break;
2212       }
2213     }
2214   }
2215   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2216   if(!D || !D->hasAttrs())
2217     return;
2218   handleCall(Exp, D);
2219 }
2220 
2221 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
2222   const CXXConstructorDecl *D = Exp->getConstructor();
2223   if (D && D->isCopyConstructor()) {
2224     const Expr* Source = Exp->getArg(0);
2225     checkAccess(Source, AK_Read);
2226   }
2227   // FIXME -- only handles constructors in DeclStmt below.
2228 }
2229 
2230 void BuildLockset::VisitDeclStmt(DeclStmt *S) {
2231   // adjust the context
2232   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2233 
2234   DeclGroupRef DGrp = S->getDeclGroup();
2235   for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2236     Decl *D = *I;
2237     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2238       Expr *E = VD->getInit();
2239       // handle constructors that involve temporaries
2240       if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2241         E = EWC->getSubExpr();
2242 
2243       if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2244         NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2245         if (!CtorD || !CtorD->hasAttrs())
2246           return;
2247         handleCall(CE, CtorD, VD);
2248       }
2249     }
2250   }
2251 }
2252 
2253 
2254 
2255 /// \brief Compute the intersection of two locksets and issue warnings for any
2256 /// locks in the symmetric difference.
2257 ///
2258 /// This function is used at a merge point in the CFG when comparing the lockset
2259 /// of each branch being merged. For example, given the following sequence:
2260 /// A; if () then B; else C; D; we need to check that the lockset after B and C
2261 /// are the same. In the event of a difference, we use the intersection of these
2262 /// two locksets at the start of D.
2263 ///
2264 /// \param FSet1 The first lockset.
2265 /// \param FSet2 The second lockset.
2266 /// \param JoinLoc The location of the join point for error reporting
2267 /// \param LEK1 The error message to report if a mutex is missing from LSet1
2268 /// \param LEK2 The error message to report if a mutex is missing from Lset2
2269 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2270                                             const FactSet &FSet2,
2271                                             SourceLocation JoinLoc,
2272                                             LockErrorKind LEK1,
2273                                             LockErrorKind LEK2,
2274                                             bool Modify) {
2275   FactSet FSet1Orig = FSet1;
2276 
2277   // Find locks in FSet2 that conflict or are not in FSet1, and warn.
2278   for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2279        I != E; ++I) {
2280     const SExpr &FSet2Mutex = FactMan[*I].MutID;
2281     const LockData &LDat2 = FactMan[*I].LDat;
2282     FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
2283 
2284     if (I1 != FSet1.end()) {
2285       const LockData* LDat1 = &FactMan[*I1].LDat;
2286       if (LDat1->LKind != LDat2.LKind) {
2287         Handler.handleExclusiveAndShared("mutex", FSet2Mutex.toString(),
2288                                          LDat2.AcquireLoc, LDat1->AcquireLoc);
2289         if (Modify && LDat1->LKind != LK_Exclusive) {
2290           // Take the exclusive lock, which is the one in FSet2.
2291           *I1 = *I;
2292         }
2293       }
2294       else if (LDat1->Asserted && !LDat2.Asserted) {
2295         // The non-asserted lock in FSet2 is the one we want to track.
2296         *I1 = *I;
2297       }
2298     } else {
2299       if (LDat2.UnderlyingMutex.isValid()) {
2300         if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
2301           // If this is a scoped lock that manages another mutex, and if the
2302           // underlying mutex is still held, then warn about the underlying
2303           // mutex.
2304           Handler.handleMutexHeldEndOfScope("mutex",
2305                                             LDat2.UnderlyingMutex.toString(),
2306                                             LDat2.AcquireLoc, JoinLoc, LEK1);
2307         }
2308       }
2309       else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted)
2310         Handler.handleMutexHeldEndOfScope("mutex", FSet2Mutex.toString(),
2311                                           LDat2.AcquireLoc, JoinLoc, LEK1);
2312     }
2313   }
2314 
2315   // Find locks in FSet1 that are not in FSet2, and remove them.
2316   for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end();
2317        I != E; ++I) {
2318     const SExpr &FSet1Mutex = FactMan[*I].MutID;
2319     const LockData &LDat1 = FactMan[*I].LDat;
2320 
2321     if (!FSet2.findLock(FactMan, FSet1Mutex)) {
2322       if (LDat1.UnderlyingMutex.isValid()) {
2323         if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
2324           // If this is a scoped lock that manages another mutex, and if the
2325           // underlying mutex is still held, then warn about the underlying
2326           // mutex.
2327           Handler.handleMutexHeldEndOfScope("mutex",
2328                                             LDat1.UnderlyingMutex.toString(),
2329                                             LDat1.AcquireLoc, JoinLoc, LEK1);
2330         }
2331       }
2332       else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted)
2333         Handler.handleMutexHeldEndOfScope("mutex", FSet1Mutex.toString(),
2334                                           LDat1.AcquireLoc, JoinLoc, LEK2);
2335       if (Modify)
2336         FSet1.removeLock(FactMan, FSet1Mutex);
2337     }
2338   }
2339 }
2340 
2341 
2342 // Return true if block B never continues to its successors.
2343 inline bool neverReturns(const CFGBlock* B) {
2344   if (B->hasNoReturnElement())
2345     return true;
2346   if (B->empty())
2347     return false;
2348 
2349   CFGElement Last = B->back();
2350   if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2351     if (isa<CXXThrowExpr>(S->getStmt()))
2352       return true;
2353   }
2354   return false;
2355 }
2356 
2357 
2358 /// \brief Check a function's CFG for thread-safety violations.
2359 ///
2360 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2361 /// at the end of each block, and issue warnings for thread safety violations.
2362 /// Each block in the CFG is traversed exactly once.
2363 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2364   // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2365   // For now, we just use the walker to set things up.
2366   threadSafety::CFGWalker walker;
2367   if (!walker.init(AC))
2368     return;
2369 
2370   // AC.dumpCFG(true);
2371   // threadSafety::printSCFG(walker);
2372 
2373   CFG *CFGraph = walker.getGraph();
2374   const NamedDecl *D = walker.getDecl();
2375 
2376   if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
2377     return;
2378 
2379   // FIXME: Do something a bit more intelligent inside constructor and
2380   // destructor code.  Constructors and destructors must assume unique access
2381   // to 'this', so checks on member variable access is disabled, but we should
2382   // still enable checks on other objects.
2383   if (isa<CXXConstructorDecl>(D))
2384     return;  // Don't check inside constructors.
2385   if (isa<CXXDestructorDecl>(D))
2386     return;  // Don't check inside destructors.
2387 
2388   BlockInfo.resize(CFGraph->getNumBlockIDs(),
2389     CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2390 
2391   // We need to explore the CFG via a "topological" ordering.
2392   // That way, we will be guaranteed to have information about required
2393   // predecessor locksets when exploring a new block.
2394   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
2395   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2396 
2397   // Mark entry block as reachable
2398   BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2399 
2400   // Compute SSA names for local variables
2401   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2402 
2403   // Fill in source locations for all CFGBlocks.
2404   findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2405 
2406   MutexIDList ExclusiveLocksAcquired;
2407   MutexIDList SharedLocksAcquired;
2408   MutexIDList LocksReleased;
2409 
2410   // Add locks from exclusive_locks_required and shared_locks_required
2411   // to initial lockset. Also turn off checking for lock and unlock functions.
2412   // FIXME: is there a more intelligent way to check lock/unlock functions?
2413   if (!SortedGraph->empty() && D->hasAttrs()) {
2414     const CFGBlock *FirstBlock = *SortedGraph->begin();
2415     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2416     const AttrVec &ArgAttrs = D->getAttrs();
2417 
2418     MutexIDList ExclusiveLocksToAdd;
2419     MutexIDList SharedLocksToAdd;
2420     StringRef CapDiagKind = "mutex";
2421 
2422     SourceLocation Loc = D->getLocation();
2423     for (const auto *Attr : ArgAttrs) {
2424       Loc = Attr->getLocation();
2425       if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2426         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2427                     0, D);
2428         CapDiagKind = ClassifyDiagnostic(A);
2429       } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
2430         // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2431         // We must ignore such methods.
2432         if (A->args_size() == 0)
2433           return;
2434         // FIXME -- deal with exclusive vs. shared unlock functions?
2435         getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
2436         getMutexIDs(LocksReleased, A, nullptr, D);
2437         CapDiagKind = ClassifyDiagnostic(A);
2438       } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
2439         if (A->args_size() == 0)
2440           return;
2441         getMutexIDs(A->isShared() ? SharedLocksAcquired
2442                                   : ExclusiveLocksAcquired,
2443                     A, nullptr, D);
2444         CapDiagKind = ClassifyDiagnostic(A);
2445       } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2446         // Don't try to check trylock functions for now
2447         return;
2448       } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2449         // Don't try to check trylock functions for now
2450         return;
2451       }
2452     }
2453 
2454     // FIXME -- Loc can be wrong here.
2455     for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
2456       addLock(InitialLockset, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
2457               CapDiagKind);
2458     for (const auto &SharedLockToAdd : SharedLocksToAdd)
2459       addLock(InitialLockset, SharedLockToAdd, LockData(Loc, LK_Shared),
2460               CapDiagKind);
2461   }
2462 
2463   for (const auto *CurrBlock : *SortedGraph) {
2464     int CurrBlockID = CurrBlock->getBlockID();
2465     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2466 
2467     // Use the default initial lockset in case there are no predecessors.
2468     VisitedBlocks.insert(CurrBlock);
2469 
2470     // Iterate through the predecessor blocks and warn if the lockset for all
2471     // predecessors is not the same. We take the entry lockset of the current
2472     // block to be the intersection of all previous locksets.
2473     // FIXME: By keeping the intersection, we may output more errors in future
2474     // for a lock which is not in the intersection, but was in the union. We
2475     // may want to also keep the union in future. As an example, let's say
2476     // the intersection contains Mutex L, and the union contains L and M.
2477     // Later we unlock M. At this point, we would output an error because we
2478     // never locked M; although the real error is probably that we forgot to
2479     // lock M on all code paths. Conversely, let's say that later we lock M.
2480     // In this case, we should compare against the intersection instead of the
2481     // union because the real error is probably that we forgot to unlock M on
2482     // all code paths.
2483     bool LocksetInitialized = false;
2484     SmallVector<CFGBlock *, 8> SpecialBlocks;
2485     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2486          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
2487 
2488       // if *PI -> CurrBlock is a back edge
2489       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
2490         continue;
2491 
2492       int PrevBlockID = (*PI)->getBlockID();
2493       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2494 
2495       // Ignore edges from blocks that can't return.
2496       if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
2497         continue;
2498 
2499       // Okay, we can reach this block from the entry.
2500       CurrBlockInfo->Reachable = true;
2501 
2502       // If the previous block ended in a 'continue' or 'break' statement, then
2503       // a difference in locksets is probably due to a bug in that block, rather
2504       // than in some other predecessor. In that case, keep the other
2505       // predecessor's lockset.
2506       if (const Stmt *Terminator = (*PI)->getTerminator()) {
2507         if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2508           SpecialBlocks.push_back(*PI);
2509           continue;
2510         }
2511       }
2512 
2513       FactSet PrevLockset;
2514       getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2515 
2516       if (!LocksetInitialized) {
2517         CurrBlockInfo->EntrySet = PrevLockset;
2518         LocksetInitialized = true;
2519       } else {
2520         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2521                          CurrBlockInfo->EntryLoc,
2522                          LEK_LockedSomePredecessors);
2523       }
2524     }
2525 
2526     // Skip rest of block if it's not reachable.
2527     if (!CurrBlockInfo->Reachable)
2528       continue;
2529 
2530     // Process continue and break blocks. Assume that the lockset for the
2531     // resulting block is unaffected by any discrepancies in them.
2532     for (const auto *PrevBlock : SpecialBlocks) {
2533       int PrevBlockID = PrevBlock->getBlockID();
2534       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2535 
2536       if (!LocksetInitialized) {
2537         CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2538         LocksetInitialized = true;
2539       } else {
2540         // Determine whether this edge is a loop terminator for diagnostic
2541         // purposes. FIXME: A 'break' statement might be a loop terminator, but
2542         // it might also be part of a switch. Also, a subsequent destructor
2543         // might add to the lockset, in which case the real issue might be a
2544         // double lock on the other path.
2545         const Stmt *Terminator = PrevBlock->getTerminator();
2546         bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2547 
2548         FactSet PrevLockset;
2549         getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2550                        PrevBlock, CurrBlock);
2551 
2552         // Do not update EntrySet.
2553         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2554                          PrevBlockInfo->ExitLoc,
2555                          IsLoop ? LEK_LockedSomeLoopIterations
2556                                 : LEK_LockedSomePredecessors,
2557                          false);
2558       }
2559     }
2560 
2561     BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2562 
2563     // Visit all the statements in the basic block.
2564     for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2565          BE = CurrBlock->end(); BI != BE; ++BI) {
2566       switch (BI->getKind()) {
2567         case CFGElement::Statement: {
2568           CFGStmt CS = BI->castAs<CFGStmt>();
2569           LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
2570           break;
2571         }
2572         // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2573         case CFGElement::AutomaticObjectDtor: {
2574           CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2575           CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2576               AD.getDestructorDecl(AC.getASTContext()));
2577           if (!DD->hasAttrs())
2578             break;
2579 
2580           // Create a dummy expression,
2581           VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
2582           DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
2583                           AD.getTriggerStmt()->getLocEnd());
2584           LocksetBuilder.handleCall(&DRE, DD);
2585           break;
2586         }
2587         default:
2588           break;
2589       }
2590     }
2591     CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2592 
2593     // For every back edge from CurrBlock (the end of the loop) to another block
2594     // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2595     // the one held at the beginning of FirstLoopBlock. We can look up the
2596     // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2597     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2598          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
2599 
2600       // if CurrBlock -> *SI is *not* a back edge
2601       if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2602         continue;
2603 
2604       CFGBlock *FirstLoopBlock = *SI;
2605       CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2606       CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2607       intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2608                        PreLoop->EntryLoc,
2609                        LEK_LockedSomeLoopIterations,
2610                        false);
2611     }
2612   }
2613 
2614   CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2615   CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
2616 
2617   // Skip the final check if the exit block is unreachable.
2618   if (!Final->Reachable)
2619     return;
2620 
2621   // By default, we expect all locks held on entry to be held on exit.
2622   FactSet ExpectedExitSet = Initial->EntrySet;
2623 
2624   // Adjust the expected exit set by adding or removing locks, as declared
2625   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
2626   // issue the appropriate warning.
2627   // FIXME: the location here is not quite right.
2628   for (const auto &Lock : ExclusiveLocksAcquired)
2629     ExpectedExitSet.addLock(FactMan, Lock,
2630                             LockData(D->getLocation(), LK_Exclusive));
2631   for (const auto &Lock : SharedLocksAcquired)
2632     ExpectedExitSet.addLock(FactMan, Lock,
2633                             LockData(D->getLocation(), LK_Shared));
2634   for (const auto &Lock : LocksReleased)
2635     ExpectedExitSet.removeLock(FactMan, Lock);
2636 
2637   // FIXME: Should we call this function for all blocks which exit the function?
2638   intersectAndWarn(ExpectedExitSet, Final->ExitSet,
2639                    Final->ExitLoc,
2640                    LEK_LockedAtEndOfFunction,
2641                    LEK_NotLockedAtEndOfFunction,
2642                    false);
2643 }
2644 
2645 } // end anonymous namespace
2646 
2647 
2648 namespace clang {
2649 namespace thread_safety {
2650 
2651 /// \brief Check a function's CFG for thread-safety violations.
2652 ///
2653 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2654 /// at the end of each block, and issue warnings for thread safety violations.
2655 /// Each block in the CFG is traversed exactly once.
2656 void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2657                              ThreadSafetyHandler &Handler) {
2658   ThreadSafetyAnalyzer Analyzer(Handler);
2659   Analyzer.runAnalysis(AC);
2660 }
2661 
2662 /// \brief Helper function that returns a LockKind required for the given level
2663 /// of access.
2664 LockKind getLockKindFromAccessKind(AccessKind AK) {
2665   switch (AK) {
2666     case AK_Read :
2667       return LK_Shared;
2668     case AK_Written :
2669       return LK_Exclusive;
2670   }
2671   llvm_unreachable("Unknown AccessKind");
2672 }
2673 
2674 }} // end namespace clang::thread_safety
2675