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