Coverage Report

Created: 2022-01-18 06:27

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