Coverage Report

Created: 2021-01-23 06:44

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