Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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.14k
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
0
76
0
  // 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.84k
  void push_back_nodup(const CapabilityExpr &CapE) {
89
4.84k
    iterator It = std::find_if(begin(), end(),
90
4.84k
                               [=](const CapabilityExpr &CapE2) {
91
1.09k
      return CapE.equals(CapE2);
92
1.09k
    });
93
4.84k
    if (It == end())
94
4.41k
      push_back(CapE);
95
4.84k
  }
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.44k
        Declared(Declrd) {}
126
4.44k
  virtual ~FactEntry() = default;
127
128
2.21k
  LockKind kind() const { return LKind;      }
129
3.04k
  SourceLocation loc() const { return AcquireLoc; }
130
5.43k
  bool asserted() const { return Asserted; }
131
2.46k
  bool declared() const { return Declared; }
132
133
503
  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.74k
  bool isAtLeast(LockKind LK) const {
149
1.74k
    return  (LKind == LK_Exclusive) || 
(LK == LK_Shared)303
;
150
1.74k
  }
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.30k
  FactID newFact(std::unique_ptr<FactEntry> Entry) {
163
4.30k
    Facts.push_back(std::move(Entry));
164
4.30k
    return static_cast<unsigned short>(Facts.size() - 1);
165
4.30k
  }
166
167
25.6k
  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
4.95k
  iterator begin() { return FactIDs.begin(); }
188
15.5k
  const_iterator begin() const { return FactIDs.begin(); }
189
190
7.27k
  iterator end() { return FactIDs.end(); }
191
28.4k
  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
54
  bool isEmpty(FactManager &FactMan) const {
197
54
    for (const auto FID : *this) {
198
30
      if (!FactMan[FID].negative())
199
20
        return false;
200
30
    }
201
54
    
return true34
;
202
54
  }
203
204
0
  void addLockByID(FactID ID) { FactIDs.push_back(ID); }
205
206
4.30k
  FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
207
4.30k
    FactID F = FM.newFact(std::move(Entry));
208
4.30k
    FactIDs.push_back(F);
209
4.30k
    return F;
210
4.30k
  }
211
212
2.42k
  bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
213
2.42k
    unsigned n = FactIDs.size();
214
2.42k
    if (n == 0)
215
0
      return false;
216
2.42k
217
3.13k
    
for (unsigned i = 0; 2.42k
i < n-1;
++i706
) {
218
1.52k
      if (FM[FactIDs[i]].matches(CapE)) {
219
814
        FactIDs[i] = FactIDs[n-1];
220
814
        FactIDs.pop_back();
221
814
        return true;
222
814
      }
223
1.52k
    }
224
2.42k
    
if (1.61k
FM[FactIDs[n-1]].matches(CapE)1.61k
) {
225
1.60k
      FactIDs.pop_back();
226
1.60k
      return true;
227
1.60k
    }
228
4
    return false;
229
4
  }
230
231
2.31k
  iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
232
2.31k
    return std::find_if(begin(), end(), [&](FactID ID) {
233
1.61k
      return FM[ID].matches(CapE);
234
1.61k
    });
235
2.31k
  }
236
237
8.37k
  const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
238
8.37k
    auto I = std::find_if(begin(), end(), [&](FactID ID) {
239
7.61k
      return FM[ID].matches(CapE);
240
7.61k
    });
241
8.37k
    return I != end() ? 
&FM[*I]3.46k
:
nullptr4.90k
;
242
8.37k
  }
243
244
  const FactEntry *findLockUniv(FactManager &FM,
245
2.88k
                                const CapabilityExpr &CapE) const {
246
2.88k
    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
247
2.79k
      return FM[ID].matchesUniv(CapE);
248
2.79k
    });
249
2.88k
    return I != end() ? 
&FM[*I]1.74k
:
nullptr1.14k
;
250
2.88k
  }
251
252
  const FactEntry *findPartialMatch(FactManager &FM,
253
1.14k
                                    const CapabilityExpr &CapE) const {
254
1.14k
    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
255
510
      return FM[ID].partiallyMatches(CapE);
256
510
    });
257
1.14k
    return I != end() ? 
&FM[*I]76
:
nullptr1.06k
;
258
1.14k
  }
259
260
486
  bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
261
486
    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
262
193
      return FM[ID].valueDecl() == Vd;
263
193
    });
264
486
    return I != end();
265
486
  }
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
743
    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
39
  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.02k
      : 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
0
    bool isReference() { return !Exp; }
404
405
  private:
406
    // Create ordinary variable definition
407
    VarDefinition(const NamedDecl *D, const Expr *E, Context C)
408
699
        : Dec(D), Exp(E), Ctx(C) {}
409
410
    // Create reference to previous definition
411
    VarDefinition(const NamedDecl *D, unsigned R, Context C)
412
2.17k
        : 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.14k
  LocalVariableMap() {
423
2.14k
    // index 0 is a placeholder for undefined variables (aka phi-nodes).
424
2.14k
    VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
425
2.14k
  }
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
170
  const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
440
170
    const unsigned *P = Ctx.lookup(D);
441
170
    if (!P)
442
40
      return nullptr;
443
130
444
130
    unsigned i = *P;
445
154
    while (i > 0) {
446
138
      if (VarDefinitions[i].Exp) {
447
114
        Ctx = VarDefinitions[i].Ctx;
448
114
        return VarDefinitions[i].Exp;
449
114
      }
450
24
      i = VarDefinitions[i].Ref;
451
24
    }
452
130
    
return nullptr16
;
453
130
  }
454
455
4.27k
  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.36k
  Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
461
2.36k
    if (SavedContexts[CtxIndex+1].first == S) {
462
713
      CtxIndex++;
463
713
      Context Result = SavedContexts[CtxIndex].second;
464
713
      return Result;
465
713
    }
466
1.64k
    return C;
467
1.64k
  }
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.43k
  unsigned getContextIndex() { return SavedContexts.size()-1; }
520
521
  // Save the current context for later replay
522
10.1k
  void saveContext(const Stmt *S, Context C) {
523
10.1k
    SavedContexts.push_back(std::make_pair(S, C));
524
10.1k
  }
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
571
  Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
529
571
    assert(!Ctx.contains(D));
530
571
    unsigned newID = VarDefinitions.size();
531
571
    Context NewCtx = ContextFactory.add(Ctx, D, newID);
532
571
    VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
533
571
    return NewCtx;
534
571
  }
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
128
  Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
547
128
    if (Ctx.contains(D)) {
548
128
      unsigned newID = VarDefinitions.size();
549
128
      Context NewCtx = ContextFactory.remove(Ctx, D);
550
128
      NewCtx = ContextFactory.add(NewCtx, D, newID);
551
128
      VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
552
128
      return NewCtx;
553
128
    }
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
22
  Context clearDefinition(const NamedDecl *D, Context Ctx) {
560
22
    Context NewCtx = Ctx;
561
22
    if (NewCtx.contains(D)) {
562
22
      NewCtx = ContextFactory.remove(NewCtx, D);
563
22
      NewCtx = ContextFactory.add(NewCtx, D, 0);
564
22
    }
565
22
    return NewCtx;
566
22
  }
567
568
  // Remove a definition entirely frmo the context.
569
13
  Context removeDefinition(const NamedDecl *D, Context Ctx) {
570
13
    Context NewCtx = Ctx;
571
13
    if (NewCtx.contains(D)) {
572
13
      NewCtx = ContextFactory.remove(NewCtx, D);
573
13
    }
574
13
    return NewCtx;
575
13
  }
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.02k
CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
586
2.02k
  return CFGBlockInfo(M.getEmptyContext());
587
2.02k
}
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.43k
      : 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
893
void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
608
893
  bool modifiedCtx = false;
609
893
  const DeclGroupRef DGrp = S->getDeclGroup();
610
893
  for (const auto *D : DGrp) {
611
893
    if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
612
893
      const Expr *E = VD->getInit();
613
893
614
893
      // Add local variables with trivial type to the variable map
615
893
      QualType T = VD->getType();
616
893
      if (T.isTrivialType(VD->getASTContext())) {
617
571
        Ctx = VMap->addDefinition(VD, E, Ctx);
618
571
        modifiedCtx = true;
619
571
      }
620
893
    }
621
893
  }
622
893
  if (modifiedCtx)
623
571
    VMap->saveContext(S, Ctx);
624
893
}
625
626
// Update local variable definitions in variable map
627
1.84k
void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
628
1.84k
  if (!BO->isAssignmentOp())
629
379
    return;
630
1.46k
631
1.46k
  Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
632
1.46k
633
1.46k
  // Update the variable map and current context.
634
1.46k
  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
635
298
    const ValueDecl *VDec = DRE->getDecl();
636
298
    if (Ctx.lookup(VDec)) {
637
142
      if (BO->getOpcode() == BO_Assign)
638
128
        Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
639
14
      else
640
14
        // FIXME -- handle compound assignment operators
641
14
        Ctx = VMap->clearDefinition(VDec, Ctx);
642
142
      VMap->saveContext(BO, Ctx);
643
142
    }
644
298
  }
645
1.46k
}
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
591
LocalVariableMap::intersectContexts(Context C1, Context C2) {
652
591
  Context Result = C1;
653
591
  for (const auto &P : C1) {
654
273
    const NamedDecl *Dec = P.first;
655
273
    const unsigned *i2 = C2.lookup(Dec);
656
273
    if (!i2)             // variable doesn't exist on second path
657
13
      Result = removeDefinition(Dec, Result);
658
260
    else if (*i2 != P.second)  // variable exists, but has different definition
659
8
      Result = clearDefinition(Dec, Result);
660
273
  }
661
591
  return Result;
662
591
}
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
98
  for (const auto &P : C1) {
679
32
    unsigned i1 = P.second;
680
32
    VarDefinition *VDef = &VarDefinitions[i1];
681
32
    assert(VDef->isReference());
682
32
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.02k
                                   std::vector<CFGBlockInfo> &BlockInfo) {
729
2.02k
  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
730
2.02k
731
2.02k
  CtxIndices.resize(CFGraph->getNumBlockIDs());
732
2.02k
733
7.43k
  for (const auto *CurrBlock : *SortedGraph) {
734
7.43k
    unsigned CurrBlockID = CurrBlock->getBlockID();
735
7.43k
    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
736
7.43k
737
7.43k
    VisitedBlocks.insert(CurrBlock);
738
7.43k
739
7.43k
    // Calculate the entry context for the current block
740
7.43k
    bool HasBackEdges = false;
741
7.43k
    bool CtxInit = true;
742
7.43k
    for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
743
13.5k
         PE  = CurrBlock->pred_end(); PI != PE; 
++PI6.09k
) {
744
6.09k
      // if *PI -> CurrBlock is a back edge, so skip it
745
6.09k
      if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
746
106
        HasBackEdges = true;
747
106
        continue;
748
106
      }
749
5.99k
750
5.99k
      unsigned PrevBlockID = (*PI)->getBlockID();
751
5.99k
      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
752
5.99k
753
5.99k
      if (CtxInit) {
754
5.40k
        CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
755
5.40k
        CtxInit = false;
756
5.40k
      }
757
591
      else {
758
591
        CurrBlockInfo->EntryContext =
759
591
          intersectContexts(CurrBlockInfo->EntryContext,
760
591
                            PrevBlockInfo->ExitContext);
761
591
      }
762
5.99k
    }
763
7.43k
764
7.43k
    // Duplicate the context if we have back-edges, so we can call
765
7.43k
    // intersectBackEdges later.
766
7.43k
    if (HasBackEdges)
767
106
      CurrBlockInfo->EntryContext =
768
106
        createReferenceContext(CurrBlockInfo->EntryContext);
769
7.43k
770
7.43k
    // Create a starting context index for the current block
771
7.43k
    saveContext(nullptr, CurrBlockInfo->EntryContext);
772
7.43k
    CurrBlockInfo->EntryIndex = getContextIndex();
773
7.43k
774
7.43k
    // Visit all the statements in the basic block.
775
7.43k
    VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
776
33.9k
    for (const auto &BI : *CurrBlock) {
777
33.9k
      switch (BI.getKind()) {
778
33.9k
        case CFGElement::Statement: {
779
33.6k
          CFGStmt CS = BI.castAs<CFGStmt>();
780
33.6k
          VMapBuilder.Visit(CS.getStmt());
781
33.6k
          break;
782
33.9k
        }
783
33.9k
        default:
784
283
          break;
785
33.9k
      }
786
33.9k
    }
787
7.43k
    CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
788
7.43k
789
7.43k
    // Mark variables on back edges as "unknown" if they've been changed.
790
7.43k
    for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
791
13.5k
         SE  = CurrBlock->succ_end(); SI != SE; 
++SI6.09k
) {
792
6.09k
      // if CurrBlock -> *SI is *not* a back edge
793
6.09k
      if (*SI == nullptr || 
!VisitedBlocks.alreadySet(*SI)6.09k
)
794
5.99k
        continue;
795
98
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.43k
  }
802
2.02k
803
2.02k
  // Put an extra entry at the end of the indexed context array
804
2.02k
  unsigned exitID = CFGraph->getExit().getBlockID();
805
2.02k
  saveContext(nullptr, BlockInfo[exitID].ExitContext);
806
2.02k
}
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.02k
                               std::vector<CFGBlockInfo> &BlockInfo) {
813
7.43k
  for (const auto *CurrBlock : *SortedGraph) {
814
7.43k
    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
815
7.43k
816
7.43k
    // Find the source location of the last statement in the block, if the
817
7.43k
    // block is not empty.
818
7.43k
    if (const Stmt *S = CurrBlock->getTerminatorStmt()) {
819
715
      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
820
6.71k
    } else {
821
6.71k
      for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
822
6.96k
           BE = CurrBlock->rend(); BI != BE; 
++BI254
) {
823
2.81k
        // FIXME: Handle other CFGElement kinds.
824
2.81k
        if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
825
2.56k
          CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
826
2.56k
          break;
827
2.56k
        }
828
2.81k
      }
829
6.71k
    }
830
7.43k
831
7.43k
    if (CurrBlockInfo->ExitLoc.isValid()) {
832
3.27k
      // This block contains at least one statement. Find the source location
833
3.27k
      // of the first statement in the block.
834
3.27k
      for (const auto &BI : *CurrBlock) {
835
3.25k
        // FIXME: Handle other CFGElement kinds.
836
3.25k
        if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
837
3.25k
          CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
838
3.25k
          break;
839
3.25k
        }
840
3.25k
      }
841
4.15k
    } else if (CurrBlock->pred_size() == 1 && 
*CurrBlock->pred_begin()1.91k
&&
842
4.15k
               
CurrBlock != &CFGraph->getExit()1.91k
) {
843
78
      // The block is empty, and has a single predecessor. Use its exit
844
78
      // location.
845
78
      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
846
78
          BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
847
78
    }
848
7.43k
  }
849
2.02k
}
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.22k
      : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
862
863
  void
864
  handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
865
                                SourceLocation JoinLoc, LockErrorKind LEK,
866
1.55k
                                ThreadSafetyHandler &Handler) const override {
867
1.55k
    if (!Managed && 
!asserted()1.53k
&&
!negative()1.50k
&&
!isUniversal()169
) {
868
165
      Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
869
165
                                        LEK);
870
165
    }
871
1.55k
  }
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, llvm::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
218
      : FactEntry(CE, LK_Exclusive, Loc, false) {}
907
908
158
  void addExclusiveLock(const CapabilityExpr &M) {
909
158
    UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
910
158
  }
911
912
28
  void addSharedLock(const CapabilityExpr &M) {
913
28
    UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
914
28
  }
915
916
28
  void addExclusiveUnlock(const CapabilityExpr &M) {
917
28
    UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedExclusive);
918
28
  }
919
920
8
  void addSharedUnlock(const CapabilityExpr &M) {
921
8
    UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedShared);
922
8
  }
923
924
  void
925
  handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
926
                                SourceLocation JoinLoc, LockErrorKind LEK,
927
28
                                ThreadSafetyHandler &Handler) const override {
928
28
    for (const auto &UnderlyingMutex : UnderlyingMutexes) {
929
28
      const auto *Entry = FSet.findLock(
930
28
          FactMan, CapabilityExpr(UnderlyingMutex.getPointer(), false));
931
28
      if ((UnderlyingMutex.getInt() == UCK_Acquired && Entry) ||
932
28
          
(16
UnderlyingMutex.getInt() != UCK_Acquired16
&&
!Entry0
)) {
933
12
        // If this scoped lock manages another mutex, and if the underlying
934
12
        // mutex is still/not held, then warn about the underlying mutex.
935
12
        Handler.handleMutexHeldEndOfScope(
936
12
            "mutex", sx::toString(UnderlyingMutex.getPointer()), loc(), JoinLoc,
937
12
            LEK);
938
12
      }
939
28
    }
940
28
  }
941
942
  void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
943
                  ThreadSafetyHandler &Handler,
944
48
                  StringRef DiagKind) const override {
945
48
    for (const auto &UnderlyingMutex : UnderlyingMutexes) {
946
48
      CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
947
48
948
48
      if (UnderlyingMutex.getInt() == UCK_Acquired)
949
40
        lock(FSet, FactMan, UnderCp, entry.kind(), entry.loc(), &Handler,
950
40
             DiagKind);
951
8
      else
952
8
        unlock(FSet, FactMan, UnderCp, entry.loc(), &Handler, DiagKind);
953
48
    }
954
48
  }
955
956
  void handleUnlock(FactSet &FSet, FactManager &FactMan,
957
                    const CapabilityExpr &Cp, SourceLocation UnlockLoc,
958
                    bool FullyRemove, ThreadSafetyHandler &Handler,
959
294
                    StringRef DiagKind) const override {
960
294
    assert(!Cp.negative() && "Managing object cannot be negative.");
961
298
    for (const auto &UnderlyingMutex : UnderlyingMutexes) {
962
298
      CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
963
298
964
298
      // Remove/lock the underlying mutex if it exists/is still unlocked; warn
965
298
      // on double unlocking/locking if we're not destroying the scoped object.
966
298
      ThreadSafetyHandler *TSHandler = FullyRemove ? 
nullptr194
:
&Handler104
;
967
298
      if (UnderlyingMutex.getInt() == UCK_Acquired) {
968
242
        unlock(FSet, FactMan, UnderCp, UnlockLoc, TSHandler, DiagKind);
969
242
      } else {
970
56
        LockKind kind = UnderlyingMutex.getInt() == UCK_ReleasedShared
971
56
                            ? 
LK_Shared8
972
56
                            : 
LK_Exclusive48
;
973
56
        lock(FSet, FactMan, UnderCp, kind, UnlockLoc, TSHandler, DiagKind);
974
56
      }
975
298
    }
976
294
    if (FullyRemove)
977
190
      FSet.removeLock(FactMan, Cp);
978
294
  }
979
980
private:
981
  void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
982
            LockKind kind, SourceLocation loc, ThreadSafetyHandler *Handler,
983
96
            StringRef DiagKind) const {
984
96
    if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
985
20
      if (Handler)
986
12
        Handler->handleDoubleLock(DiagKind, Cp.toString(), Fact->loc(), loc);
987
76
    } else {
988
76
      FSet.removeLock(FactMan, !Cp);
989
76
      FSet.addLock(FactMan,
990
76
                   llvm::make_unique<LockableFactEntry>(Cp, kind, loc));
991
76
    }
992
96
  }
993
994
  void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
995
              SourceLocation loc, ThreadSafetyHandler *Handler,
996
250
              StringRef DiagKind) const {
997
250
    if (FSet.findLock(FactMan, Cp)) {
998
202
      FSet.removeLock(FactMan, Cp);
999
202
      FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
1000
202
                                !Cp, LK_Exclusive, loc));
1001
202
    } else 
if (48
Handler48
) {
1002
16
      Handler->handleUnmatchedUnlock(DiagKind, Cp.toString(), loc);
1003
16
    }
1004
250
  }
1005
};
1006
1007
/// Class which implements the core thread safety analysis routines.
1008
class ThreadSafetyAnalyzer {
1009
  friend class BuildLockset;
1010
  friend class threadSafety::BeforeSet;
1011
1012
  llvm::BumpPtrAllocator Bpa;
1013
  threadSafety::til::MemRegionRef Arena;
1014
  threadSafety::SExprBuilder SxBuilder;
1015
1016
  ThreadSafetyHandler &Handler;
1017
  const CXXMethodDecl *CurrentMethod;
1018
  LocalVariableMap LocalVarMap;
1019
  FactManager FactMan;
1020
  std::vector<CFGBlockInfo> BlockInfo;
1021
1022
  BeforeSet *GlobalBeforeSet;
1023
1024
public:
1025
  ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
1026
2.14k
      : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
1027
1028
  bool inCurrentScope(const CapabilityExpr &CapE);
1029
1030
  void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
1031
               StringRef DiagKind, bool ReqAttr = false);
1032
  void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
1033
                  SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
1034
                  StringRef DiagKind);
1035
1036
  template <typename AttrType>
1037
  void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1038
                   const NamedDecl *D, VarDecl *SelfDecl = nullptr);
1039
1040
  template <class AttrType>
1041
  void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1042
                   const NamedDecl *D,
1043
                   const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1044
                   Expr *BrE, bool Neg);
1045
1046
  const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1047
                                     bool &Negate);
1048
1049
  void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1050
                      const CFGBlock* PredBlock,
1051
                      const CFGBlock *CurrBlock);
1052
1053
  void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1054
                        SourceLocation JoinLoc,
1055
                        LockErrorKind LEK1, LockErrorKind LEK2,
1056
                        bool Modify=true);
1057
1058
  void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1059
                        SourceLocation JoinLoc, LockErrorKind LEK1,
1060
669
                        bool Modify=true) {
1061
669
    intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
1062
669
  }
1063
1064
  void runAnalysis(AnalysisDeclContext &AC);
1065
};
1066
1067
} // namespace
1068
1069
/// Process acquired_before and acquired_after attributes on Vd.
1070
BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1071
743
    ThreadSafetyAnalyzer& Analyzer) {
1072
743
  // Create a new entry for Vd.
1073
743
  BeforeInfo *Info = nullptr;
1074
743
  {
1075
743
    // Keep InfoPtr in its own scope in case BMap is modified later and the
1076
743
    // reference becomes invalid.
1077
743
    std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1078
743
    if (!InfoPtr)
1079
743
      InfoPtr.reset(new BeforeInfo());
1080
743
    Info = InfoPtr.get();
1081
743
  }
1082
743
1083
743
  for (const auto *At : Vd->attrs()) {
1084
137
    switch (At->getKind()) {
1085
137
      case attr::AcquiredBefore: {
1086
52
        const auto *A = cast<AcquiredBeforeAttr>(At);
1087
52
1088
52
        // Read exprs from the attribute, and add them to BeforeVect.
1089
64
        for (const auto *Arg : A->args()) {
1090
64
          CapabilityExpr Cp =
1091
64
            Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1092
64
          if (const ValueDecl *Cpvd = Cp.valueDecl()) {
1093
60
            Info->Vect.push_back(Cpvd);
1094
60
            const auto It = BMap.find(Cpvd);
1095
60
            if (It == BMap.end())
1096
40
              insertAttrExprs(Cpvd, Analyzer);
1097
60
          }
1098
64
        }
1099
52
        break;
1100
137
      }
1101
137
      case attr::AcquiredAfter: {
1102
85
        const auto *A = cast<AcquiredAfterAttr>(At);
1103
85
1104
85
        // Read exprs from the attribute, and add them to BeforeVect.
1105
93
        for (const auto *Arg : A->args()) {
1106
93
          CapabilityExpr Cp =
1107
93
            Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1108
93
          if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1109
93
            // Get entry for mutex listed in attribute
1110
93
            BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1111
93
            ArgInfo->Vect.push_back(Vd);
1112
93
          }
1113
93
        }
1114
85
        break;
1115
137
      }
1116
137
      default:
1117
0
        break;
1118
137
    }
1119
137
  }
1120
743
1121
743
  return Info;
1122
743
}
1123
1124
BeforeSet::BeforeInfo *
1125
BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1126
2.50k
                                ThreadSafetyAnalyzer &Analyzer) {
1127
2.50k
  auto It = BMap.find(Vd);
1128
2.50k
  BeforeInfo *Info = nullptr;
1129
2.50k
  if (It == BMap.end())
1130
703
    Info = insertAttrExprs(Vd, Analyzer);
1131
1.80k
  else
1132
1.80k
    Info = It->second.get();
1133
2.50k
  assert(Info && "BMap contained nullptr?");
1134
2.50k
  return Info;
1135
2.50k
}
1136
1137
/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1138
void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1139
                                 const FactSet& FSet,
1140
                                 ThreadSafetyAnalyzer& Analyzer,
1141
1.97k
                                 SourceLocation Loc, StringRef CapKind) {
1142
1.97k
  SmallVector<BeforeInfo*, 8> InfoVect;
1143
1.97k
1144
1.97k
  // Do a depth-first traversal of Vd.
1145
1.97k
  // Return true if there are cycles.
1146
2.45k
  std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1147
2.45k
    if (!Vd)
1148
44
      return false;
1149
2.41k
1150
2.41k
    BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
1151
2.41k
1152
2.41k
    if (Info->Visited == 1)
1153
32
      return true;
1154
2.38k
1155
2.38k
    if (Info->Visited == 2)
1156
16
      return false;
1157
2.36k
1158
2.36k
    if (Info->Vect.empty())
1159
1.91k
      return false;
1160
446
1161
446
    InfoVect.push_back(Info);
1162
446
    Info->Visited = 1;
1163
486
    for (const auto *Vdb : Info->Vect) {
1164
486
      // Exclude mutexes in our immediate before set.
1165
486
      if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1166
49
        StringRef L1 = StartVd->getName();
1167
49
        StringRef L2 = Vdb->getName();
1168
49
        Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1169
49
      }
1170
486
      // Transitively search other before sets, and warn on cycles.
1171
486
      if (traverse(Vdb)) {
1172
32
        if (CycMap.find(Vd) == CycMap.end()) {
1173
20
          CycMap.insert(std::make_pair(Vd, true));
1174
20
          StringRef L1 = Vd->getName();
1175
20
          Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1176
20
        }
1177
32
      }
1178
486
    }
1179
446
    Info->Visited = 2;
1180
446
    return false;
1181
446
  };
1182
1.97k
1183
1.97k
  traverse(StartVd);
1184
1.97k
1185
1.97k
  for (auto *Info : InfoVect)
1186
446
    Info->Visited = 0;
1187
1.97k
}
1188
1189
/// Gets the value decl pointer from DeclRefExprs or MemberExprs.
1190
17.6k
static const ValueDecl *getValueDecl(const Expr *Exp) {
1191
17.6k
  if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1192
0
    return getValueDecl(CE->getSubExpr());
1193
17.6k
1194
17.6k
  if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1195
4.87k
    return DR->getDecl();
1196
12.7k
1197
12.7k
  if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1198
8.13k
    return ME->getMemberDecl();
1199
4.64k
1200
4.64k
  return nullptr;
1201
4.64k
}
1202
1203
namespace {
1204
1205
template <typename Ty>
1206
class has_arg_iterator_range {
1207
  using yes = char[1];
1208
  using no = char[2];
1209
1210
  template <typename Inner>
1211
  static yes& test(Inner *I, decltype(I->args()) * = nullptr);
1212
1213
  template <typename>
1214
  static no& test(...);
1215
1216
public:
1217
  static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1218
};
1219
1220
} // namespace
1221
1222
3.96k
static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1223
3.96k
  return A->getName();
1224
3.96k
}
1225
1226
4.48k
static StringRef ClassifyDiagnostic(QualType VDT) {
1227
4.48k
  // We need to look at the declaration of the type of the value to determine
1228
4.48k
  // which it is. The type should either be a record or a typedef, or a pointer
1229
4.48k
  // or reference thereof.
1230
4.48k
  if (const auto *RT = VDT->getAs<RecordType>()) {
1231
4.07k
    if (const auto *RD = RT->getDecl())
1232
4.07k
      if (const auto *CA = RD->getAttr<CapabilityAttr>())
1233
3.92k
        return ClassifyDiagnostic(CA);
1234
413
  } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1235
44
    if (const auto *TD = TT->getDecl())
1236
44
      if (const auto *CA = TD->getAttr<CapabilityAttr>())
1237
44
        return ClassifyDiagnostic(CA);
1238
369
  } else if (VDT->isPointerType() || 
VDT->isReferenceType()6
)
1239
365
    return ClassifyDiagnostic(VDT->getPointeeType());
1240
156
1241
156
  return "mutex";
1242
156
}
1243
1244
4.12k
static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1245
4.12k
  assert(VD && "No ValueDecl passed");
1246
4.12k
1247
4.12k
  // The ValueDecl is the declaration of a mutex or role (hopefully).
1248
4.12k
  return ClassifyDiagnostic(VD->getType());
1249
4.12k
}
1250
1251
template <typename AttrTy>
1252
static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
1253
                               StringRef>::type
1254
2.30k
ClassifyDiagnostic(const AttrTy *A) {
1255
2.30k
  if (const ValueDecl *VD = getValueDecl(A->getArg()))
1256
2.11k
    return ClassifyDiagnostic(VD);
1257
184
  return "mutex";
1258
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
1254
388
ClassifyDiagnostic(const AttrTy *A) {
1255
388
  if (const ValueDecl *VD = getValueDecl(A->getArg()))
1256
388
    return ClassifyDiagnostic(VD);
1257
0
  return "mutex";
1258
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
1254
1.91k
ClassifyDiagnostic(const AttrTy *A) {
1255
1.91k
  if (const ValueDecl *VD = getValueDecl(A->getArg()))
1256
1.72k
    return ClassifyDiagnostic(VD);
1257
184
  return "mutex";
1258
184
}
1259
1260
template <typename AttrTy>
1261
static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
1262
                               StringRef>::type
1263
5.34k
ClassifyDiagnostic(const AttrTy *A) {
1264
5.34k
  for (const auto *Arg : A->args()) {
1265
2.36k
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
2.00k
      return ClassifyDiagnostic(VD);
1267
2.36k
  }
1268
5.34k
  
return "mutex"3.34k
;
1269
5.34k
}
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
1263
1.03k
ClassifyDiagnostic(const AttrTy *A) {
1264
1.06k
  for (const auto *Arg : A->args()) {
1265
1.06k
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
832
      return ClassifyDiagnostic(VD);
1267
1.06k
  }
1268
1.03k
  
return "mutex"202
;
1269
1.03k
}
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
1263
1.96k
ClassifyDiagnostic(const AttrTy *A) {
1264
1.96k
  for (const auto *Arg : A->args()) {
1265
459
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
415
      return ClassifyDiagnostic(VD);
1267
459
  }
1268
1.96k
  
return "mutex"1.55k
;
1269
1.96k
}
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
1263
1.79k
ClassifyDiagnostic(const AttrTy *A) {
1264
1.79k
  for (const auto *Arg : A->args()) {
1265
572
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
516
      return ClassifyDiagnostic(VD);
1267
572
  }
1268
1.79k
  
return "mutex"1.28k
;
1269
1.79k
}
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
1263
168
ClassifyDiagnostic(const AttrTy *A) {
1264
168
  for (const auto *Arg : A->args()) {
1265
52
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
48
      return ClassifyDiagnostic(VD);
1267
52
  }
1268
168
  
return "mutex"120
;
1269
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
1263
156
ClassifyDiagnostic(const AttrTy *A) {
1264
156
  for (const auto *Arg : A->args()) {
1265
44
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
40
      return ClassifyDiagnostic(VD);
1267
44
  }
1268
156
  
return "mutex"116
;
1269
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
1263
12
ClassifyDiagnostic(const AttrTy *A) {
1264
12
  for (const auto *Arg : A->args()) {
1265
8
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
8
      return ClassifyDiagnostic(VD);
1267
8
  }
1268
12
  
return "mutex"4
;
1269
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
1263
34
ClassifyDiagnostic(const AttrTy *A) {
1264
34
  for (const auto *Arg : A->args()) {
1265
10
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
10
      return ClassifyDiagnostic(VD);
1267
10
  }
1268
34
  
return "mutex"24
;
1269
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
1263
10
ClassifyDiagnostic(const AttrTy *A) {
1264
10
  for (const auto *Arg : A->args()) {
1265
8
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
8
      return ClassifyDiagnostic(VD);
1267
8
  }
1268
10
  
return "mutex"2
;
1269
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
1263
44
ClassifyDiagnostic(const AttrTy *A) {
1264
44
  for (const auto *Arg : A->args()) {
1265
18
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
18
      return ClassifyDiagnostic(VD);
1267
18
  }
1268
44
  
return "mutex"26
;
1269
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
1263
126
ClassifyDiagnostic(const AttrTy *A) {
1264
126
  for (const auto *Arg : A->args()) {
1265
126
    if (const ValueDecl *VD = getValueDecl(Arg))
1266
110
      return ClassifyDiagnostic(VD);
1267
126
  }
1268
126
  
return "mutex"16
;
1269
126
}
1270
1271
1.88k
bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1272
1.88k
  if (!CurrentMethod)
1273
913
      return false;
1274
967
  if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1275
807
    const auto *VD = P->clangDecl();
1276
807
    if (VD)
1277
807
      return VD->getDeclContext() == CurrentMethod->getDeclContext();
1278
160
  }
1279
160
  return false;
1280
160
}
1281
1282
/// Add a new lock to the lockset, warning if the lock is already there.
1283
/// \param ReqAttr -- true if this is part of an initial Requires attribute.
1284
void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1285
                                   std::unique_ptr<FactEntry> Entry,
1286
2.63k
                                   StringRef DiagKind, bool ReqAttr) {
1287
2.63k
  if (Entry->shouldIgnore())
1288
0
    return;
1289
2.63k
1290
2.63k
  if (!ReqAttr && 
!Entry->negative()2.13k
) {
1291
2.13k
    // look for the negative capability, and remove it from the fact set.
1292
2.13k
    CapabilityExpr NegC = !*Entry;
1293
2.13k
    const FactEntry *Nen = FSet.findLock(FactMan, NegC);
1294
2.13k
    if (Nen) {
1295
274
      FSet.removeLock(FactMan, NegC);
1296
274
    }
1297
1.85k
    else {
1298
1.85k
      if (inCurrentScope(*Entry) && 
!Entry->asserted()731
)
1299
643
        Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1300
643
                                      NegC.toString(), Entry->loc());
1301
1.85k
    }
1302
2.13k
  }
1303
2.63k
1304
2.63k
  // Check before/after constraints
1305
2.63k
  if (Handler.issueBetaWarnings() &&
1306
2.63k
      
!Entry->asserted()2.55k
&&
!Entry->declared()2.46k
) {
1307
1.97k
    GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1308
1.97k
                                      Entry->loc(), DiagKind);
1309
1.97k
  }
1310
2.63k
1311
2.63k
  // FIXME: Don't always warn when we have support for reentrant locks.
1312
2.63k
  if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
1313
143
    if (!Entry->asserted())
1314
115
      Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind);
1315
2.49k
  } else {
1316
2.49k
    FSet.addLock(FactMan, std::move(Entry));
1317
2.49k
  }
1318
2.63k
}
1319
1320
/// Remove a lock from the lockset, warning if the lock is not there.
1321
/// \param UnlockLoc The source location of the unlock (only used in error msg)
1322
void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
1323
                                      SourceLocation UnlockLoc,
1324
                                      bool FullyRemove, LockKind ReceivedKind,
1325
1.83k
                                      StringRef DiagKind) {
1326
1.83k
  if (Cp.shouldIgnore())
1327
0
    return;
1328
1.83k
1329
1.83k
  const FactEntry *LDat = FSet.findLock(FactMan, Cp);
1330
1.83k
  if (!LDat) {
1331
84
    Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
1332
84
    return;
1333
84
  }
1334
1.75k
1335
1.75k
  // Generic lock removal doesn't care about lock kind mismatches, but
1336
1.75k
  // otherwise diagnose when the lock kinds are mismatched.
1337
1.75k
  if (ReceivedKind != LK_Generic && 
LDat->kind() != ReceivedKind182
) {
1338
18
    Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(), LDat->kind(),
1339
18
                                      ReceivedKind, LDat->loc(), UnlockLoc);
1340
18
  }
1341
1.75k
1342
1.75k
  LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1343
1.75k
                     DiagKind);
1344
1.75k
}
1345
1346
/// Extract the list of mutexIDs from the attribute on an expression,
1347
/// and push them onto Mtxs, discarding any duplicates.
1348
template <typename AttrType>
1349
void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1350
                                       const Expr *Exp, const NamedDecl *D,
1351
4.50k
                                       VarDecl *SelfDecl) {
1352
4.50k
  if (Attr->args_size() == 0) {
1353
2.89k
    // The mutex held is the "this" object.
1354
2.89k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
2.89k
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
2.89k
    //else
1360
2.89k
    if (!Cp.shouldIgnore())
1361
2.89k
      Mtxs.push_back_nodup(Cp);
1362
2.89k
    return;
1363
2.89k
  }
1364
1.60k
1365
1.95k
  
for (const auto *Arg : Attr->args())1.60k
{
1366
1.95k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
1.95k
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
1.95k
    //else
1372
1.95k
    if (!Cp.shouldIgnore())
1373
1.94k
      Mtxs.push_back_nodup(Cp);
1374
1.95k
  }
1375
1.60k
}
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
1351
414
                                       VarDecl *SelfDecl) {
1352
414
  if (Attr->args_size() == 0) {
1353
0
    // The mutex held is the "this" object.
1354
0
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
0
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
0
    //else
1360
0
    if (!Cp.shouldIgnore())
1361
0
      Mtxs.push_back_nodup(Cp);
1362
0
    return;
1363
0
  }
1364
414
1365
466
  
for (const auto *Arg : Attr->args())414
{
1366
466
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
466
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
466
    //else
1372
466
    if (!Cp.shouldIgnore())
1373
466
      Mtxs.push_back_nodup(Cp);
1374
466
  }
1375
414
}
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
1351
2.04k
                                       VarDecl *SelfDecl) {
1352
2.04k
  if (Attr->args_size() == 0) {
1353
1.50k
    // The mutex held is the "this" object.
1354
1.50k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
1.50k
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
1.50k
    //else
1360
1.50k
    if (!Cp.shouldIgnore())
1361
1.50k
      Mtxs.push_back_nodup(Cp);
1362
1.50k
    return;
1363
1.50k
  }
1364
536
1365
696
  
for (const auto *Arg : Attr->args())536
{
1366
696
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
696
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
696
    //else
1372
696
    if (!Cp.shouldIgnore())
1373
692
      Mtxs.push_back_nodup(Cp);
1374
696
  }
1375
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
1351
1.79k
                                       VarDecl *SelfDecl) {
1352
1.79k
  if (Attr->args_size() == 0) {
1353
1.22k
    // The mutex held is the "this" object.
1354
1.22k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
1.22k
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
1.22k
    //else
1360
1.22k
    if (!Cp.shouldIgnore())
1361
1.22k
      Mtxs.push_back_nodup(Cp);
1362
1.22k
    return;
1363
1.22k
  }
1364
572
1365
704
  
for (const auto *Arg : Attr->args())572
{
1366
704
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
704
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
704
    //else
1372
704
    if (!Cp.shouldIgnore())
1373
696
      Mtxs.push_back_nodup(Cp);
1374
704
  }
1375
572
}
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
1351
84
                                       VarDecl *SelfDecl) {
1352
84
  if (Attr->args_size() == 0) {
1353
58
    // The mutex held is the "this" object.
1354
58
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
58
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
58
    //else
1360
58
    if (!Cp.shouldIgnore())
1361
58
      Mtxs.push_back_nodup(Cp);
1362
58
    return;
1363
58
  }
1364
26
1365
26
  for (const auto *Arg : Attr->args()) {
1366
26
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
26
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
26
    //else
1372
26
    if (!Cp.shouldIgnore())
1373
26
      Mtxs.push_back_nodup(Cp);
1374
26
  }
1375
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
1351
78
                                       VarDecl *SelfDecl) {
1352
78
  if (Attr->args_size() == 0) {
1353
56
    // The mutex held is the "this" object.
1354
56
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
56
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
56
    //else
1360
56
    if (!Cp.shouldIgnore())
1361
56
      Mtxs.push_back_nodup(Cp);
1362
56
    return;
1363
56
  }
1364
22
1365
22
  for (const auto *Arg : Attr->args()) {
1366
22
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
22
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
22
    //else
1372
22
    if (!Cp.shouldIgnore())
1373
22
      Mtxs.push_back_nodup(Cp);
1374
22
  }
1375
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
1351
6
                                       VarDecl *SelfDecl) {
1352
6
  if (Attr->args_size() == 0) {
1353
2
    // The mutex held is the "this" object.
1354
2
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
2
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
2
    //else
1360
2
    if (!Cp.shouldIgnore())
1361
2
      Mtxs.push_back_nodup(Cp);
1362
2
    return;
1363
2
  }
1364
4
1365
4
  for (const auto *Arg : Attr->args()) {
1366
4
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
4
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
4
    //else
1372
4
    if (!Cp.shouldIgnore())
1373
4
      Mtxs.push_back_nodup(Cp);
1374
4
  }
1375
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
1351
32
                                       VarDecl *SelfDecl) {
1352
32
  if (Attr->args_size() == 0) {
1353
24
    // The mutex held is the "this" object.
1354
24
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
24
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
24
    //else
1360
24
    if (!Cp.shouldIgnore())
1361
24
      Mtxs.push_back_nodup(Cp);
1362
24
    return;
1363
24
  }
1364
8
1365
10
  
for (const auto *Arg : Attr->args())8
{
1366
10
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
10
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
10
    //else
1372
10
    if (!Cp.shouldIgnore())
1373
10
      Mtxs.push_back_nodup(Cp);
1374
10
  }
1375
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
1351
8
                                       VarDecl *SelfDecl) {
1352
8
  if (Attr->args_size() == 0) {
1353
2
    // The mutex held is the "this" object.
1354
2
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
2
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
2
    //else
1360
2
    if (!Cp.shouldIgnore())
1361
2
      Mtxs.push_back_nodup(Cp);
1362
2
    return;
1363
2
  }
1364
6
1365
8
  
for (const auto *Arg : Attr->args())6
{
1366
8
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
8
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
8
    //else
1372
8
    if (!Cp.shouldIgnore())
1373
8
      Mtxs.push_back_nodup(Cp);
1374
8
  }
1375
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
1351
40
                                       VarDecl *SelfDecl) {
1352
40
  if (Attr->args_size() == 0) {
1353
26
    // The mutex held is the "this" object.
1354
26
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355
26
    if (Cp.isInvalid()) {
1356
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1357
0
       return;
1358
0
    }
1359
26
    //else
1360
26
    if (!Cp.shouldIgnore())
1361
26
      Mtxs.push_back_nodup(Cp);
1362
26
    return;
1363
26
  }
1364
14
1365
18
  
for (const auto *Arg : Attr->args())14
{
1366
18
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367
18
    if (Cp.isInvalid()) {
1368
0
       warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1369
0
       continue;
1370
0
    }
1371
18
    //else
1372
18
    if (!Cp.shouldIgnore())
1373
18
      Mtxs.push_back_nodup(Cp);
1374
18
  }
1375
14
}
1376
1377
/// Extract the list of mutexIDs from a trylock attribute.  If the
1378
/// trylock applies to the given edge, then push them onto Mtxs, discarding
1379
/// any duplicates.
1380
template <class AttrType>
1381
void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1382
                                       const Expr *Exp, const NamedDecl *D,
1383
                                       const CFGBlock *PredBlock,
1384
                                       const CFGBlock *CurrBlock,
1385
336
                                       Expr *BrE, bool Neg) {
1386
336
  // Find out which branch has the lock
1387
336
  bool branch = false;
1388
336
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1389
272
    branch = BLE->getValue();
1390
64
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1391
64
    branch = ILE->getValue().getBoolValue();
1392
336
1393
336
  int branchnum = branch ? 0 : 
10
;
1394
336
  if (Neg)
1395
144
    branchnum = !branchnum;
1396
336
1397
336
  // If we've taken the trylock branch, then add the lock
1398
336
  int i = 0;
1399
336
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1400
1.00k
       SE = PredBlock->succ_end(); SI != SE && 
i < 2672
;
++SI, ++i672
) {
1401
672
    if (*SI == CurrBlock && 
i == branchnum336
)
1402
168
      getMutexIDs(Mtxs, Attr, Exp, D);
1403
672
  }
1404
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
1385
168
                                       Expr *BrE, bool Neg) {
1386
168
  // Find out which branch has the lock
1387
168
  bool branch = false;
1388
168
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1389
136
    branch = BLE->getValue();
1390
32
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1391
32
    branch = ILE->getValue().getBoolValue();
1392
168
1393
168
  int branchnum = branch ? 0 : 
10
;
1394
168
  if (Neg)
1395
72
    branchnum = !branchnum;
1396
168
1397
168
  // If we've taken the trylock branch, then add the lock
1398
168
  int i = 0;
1399
168
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1400
504
       SE = PredBlock->succ_end(); SI != SE && 
i < 2336
;
++SI, ++i336
) {
1401
336
    if (*SI == CurrBlock && 
i == branchnum168
)
1402
84
      getMutexIDs(Mtxs, Attr, Exp, D);
1403
336
  }
1404
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
1385
156
                                       Expr *BrE, bool Neg) {
1386
156
  // Find out which branch has the lock
1387
156
  bool branch = false;
1388
156
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1389
124
    branch = BLE->getValue();
1390
32
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1391
32
    branch = ILE->getValue().getBoolValue();
1392
156
1393
156
  int branchnum = branch ? 0 : 
10
;
1394
156
  if (Neg)
1395
68
    branchnum = !branchnum;
1396
156
1397
156
  // If we've taken the trylock branch, then add the lock
1398
156
  int i = 0;
1399
156
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1400
468
       SE = PredBlock->succ_end(); SI != SE && 
i < 2312
;
++SI, ++i312
) {
1401
312
    if (*SI == CurrBlock && 
i == branchnum156
)
1402
78
      getMutexIDs(Mtxs, Attr, Exp, D);
1403
312
  }
1404
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
1385
12
                                       Expr *BrE, bool Neg) {
1386
12
  // Find out which branch has the lock
1387
12
  bool branch = false;
1388
12
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1389
12
    branch = BLE->getValue();
1390
0
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1391
0
    branch = ILE->getValue().getBoolValue();
1392
12
1393
12
  int branchnum = branch ? 0 : 
10
;
1394
12
  if (Neg)
1395
4
    branchnum = !branchnum;
1396
12
1397
12
  // If we've taken the trylock branch, then add the lock
1398
12
  int i = 0;
1399
12
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1400
36
       SE = PredBlock->succ_end(); SI != SE && 
i < 224
;
++SI, ++i24
) {
1401
24
    if (*SI == CurrBlock && 
i == branchnum12
)
1402
6
      getMutexIDs(Mtxs, Attr, Exp, D);
1403
24
  }
1404
12
}
1405
1406
498
static bool getStaticBooleanValue(Expr *E, bool &TCond) {
1407
498
  if (isa<CXXNullPtrLiteralExpr>(E) || 
isa<GNUNullExpr>(E)490
) {
1408
8
    TCond = false;
1409
8
    return true;
1410
490
  } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1411
16
    TCond = BLE->getValue();
1412
16
    return true;
1413
474
  } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
1414
362
    TCond = ILE->getValue().getBoolValue();
1415
362
    return true;
1416
362
  } else 
if (auto *112
CE112
= dyn_cast<ImplicitCastExpr>(E))
1417
80
    return getStaticBooleanValue(CE->getSubExpr(), TCond);
1418
32
  return false;
1419
32
}
1420
1421
// If Cond can be traced back to a function call, return the call expression.
1422
// The negate variable should be called with false, and will be set to true
1423
// if the function call is negated, e.g. if (!mu.tryLock(...))
1424
const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1425
                                                         LocalVarContext C,
1426
2.86k
                                                         bool &Negate) {
1427
2.86k
  if (!Cond)
1428
56
    return nullptr;
1429
2.80k
1430
2.80k
  if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
1431
784
    if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
1432
16
      return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
1433
768
    return CallExp;
1434
768
  }
1435
2.02k
  else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
1436
32
    return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1437
1.99k
  else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
1438
770
    return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1439
1.22k
  else if (const auto *FE = dyn_cast<FullExpr>(Cond))
1440
8
    return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
1441
1.21k
  else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1442
170
    const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1443
170
    return getTrylockCallExpr(E, C, Negate);
1444
170
  }
1445
1.04k
  else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
1446
160
    if (UOP->getOpcode() == UO_LNot) {
1447
128
      Negate = !Negate;
1448
128
      return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1449
128
    }
1450
32
    return nullptr;
1451
32
  }
1452
882
  else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
1453
474
    if (BOP->getOpcode() == BO_EQ || 
BOP->getOpcode() == BO_NE154
) {
1454
346
      if (BOP->getOpcode() == BO_NE)
1455
26
        Negate = !Negate;
1456
346
1457
346
      bool TCond = false;
1458
346
      if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1459
322
        if (!TCond) 
Negate = !Negate210
;
1460
322
        return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1461
322
      }
1462
24
      TCond = false;
1463
24
      if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1464
16
        if (!TCond) Negate = !Negate;
1465
16
        return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1466
16
      }
1467
8
      return nullptr;
1468
8
    }
1469
128
    if (BOP->getOpcode() == BO_LAnd) {
1470
72
      // LHS must have been evaluated in a different block.
1471
72
      return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1472
72
    }
1473
56
    if (BOP->getOpcode() == BO_LOr)
1474
24
      return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1475
32
    return nullptr;
1476
408
  } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
1477
24
    bool TCond, FCond;
1478
24
    if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
1479
24
        getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
1480
24
      if (TCond && 
!FCond8
)
1481
8
        return getTrylockCallExpr(COP->getCond(), C, Negate);
1482
16
      if (!TCond && FCond) {
1483
16
        Negate = !Negate;
1484
16
        return getTrylockCallExpr(COP->getCond(), C, Negate);
1485
16
      }
1486
384
    }
1487
24
  }
1488
384
  return nullptr;
1489
384
}
1490
1491
/// Find the lockset that holds on the edge between PredBlock
1492
/// and CurrBlock.  The edge set is the exit set of PredBlock (passed
1493
/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1494
void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1495
                                          const FactSet &ExitSet,
1496
                                          const CFGBlock *PredBlock,
1497
5.86k
                                          const CFGBlock *CurrBlock) {
1498
5.86k
  Result = ExitSet;
1499
5.86k
1500
5.86k
  const Stmt *Cond = PredBlock->getTerminatorCondition();
1501
5.86k
  // We don't acquire try-locks on ?: branches, only when its result is used.
1502
5.86k
  if (!Cond || 
isa<ConditionalOperator>(PredBlock->getTerminatorStmt())1.35k
)
1503
4.58k
    return;
1504
1.28k
1505
1.28k
  bool Negate = false;
1506
1.28k
  const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1507
1.28k
  const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1508
1.28k
  StringRef CapDiagKind = "mutex";
1509
1.28k
1510
1.28k
  const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
1511
1.28k
  if (!Exp)
1512
512
    return;
1513
768
1514
768
  auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1515
768
  if(!FunDecl || !FunDecl->hasAttrs())
1516
446
    return;
1517
322
1518
322
  CapExprSet ExclusiveLocksToAdd;
1519
322
  CapExprSet SharedLocksToAdd;
1520
322
1521
322
  // If the condition is a call to a Trylock function, then grab the attributes
1522
338
  for (const auto *Attr : FunDecl->attrs()) {
1523
338
    switch (Attr->getKind()) {
1524
338
      case attr::TryAcquireCapability: {
1525
168
        auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1526
168
        getMutexIDs(A->isShared() ? 
SharedLocksToAdd12
:
ExclusiveLocksToAdd156
, A,
1527
168
                    Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1528
168
                    Negate);
1529
168
        CapDiagKind = ClassifyDiagnostic(A);
1530
168
        break;
1531
338
      };
1532
156
      case attr::ExclusiveTrylockFunction: {
1533
156
        const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
1534
156
        getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1535
156
                    PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1536
156
        CapDiagKind = ClassifyDiagnostic(A);
1537
156
        break;
1538
0
      }
1539
12
      case attr::SharedTrylockFunction: {
1540
12
        const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
1541
12
        getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
1542
12
                    PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1543
12
        CapDiagKind = ClassifyDiagnostic(A);
1544
12
        break;
1545
0
      }
1546
2
      default:
1547
2
        break;
1548
338
    }
1549
338
  }
1550
322
1551
322
  // Add and remove locks.
1552
322
  SourceLocation Loc = Exp->getExprLoc();
1553
322
  for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1554
156
    addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1555
156
                                                         LK_Exclusive, Loc),
1556
156
            CapDiagKind);
1557
322
  for (const auto &SharedLockToAdd : SharedLocksToAdd)
1558
12
    addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1559
12
                                                         LK_Shared, Loc),
1560
12
            CapDiagKind);
1561
322
}
1562
1563
namespace {
1564
1565
/// We use this class to visit different types of expressions in
1566
/// CFGBlocks, and build up the lockset.
1567
/// An expression may cause us to add or remove locks from the lockset, or else
1568
/// output error messages related to missing locks.
1569
/// FIXME: In future, we may be able to not inherit from a visitor.
1570
class BuildLockset : public ConstStmtVisitor<BuildLockset> {
1571
  friend class ThreadSafetyAnalyzer;
1572
1573
  ThreadSafetyAnalyzer *Analyzer;
1574
  FactSet FSet;
1575
  LocalVariableMap::Context LVarCtx;
1576
  unsigned CtxIndex;
1577
1578
  // helper functions
1579
  void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1580
                          Expr *MutexExp, ProtectedOperationKind POK,
1581
                          StringRef DiagKind, SourceLocation Loc);
1582
  void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1583
                       StringRef DiagKind);
1584
1585
  void checkAccess(const Expr *Exp, AccessKind AK,
1586
                   ProtectedOperationKind POK = POK_VarAccess);
1587
  void checkPtAccess(const Expr *Exp, AccessKind AK,
1588
                     ProtectedOperationKind POK = POK_VarAccess);
1589
1590
  void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
1591
  void examineArguments(const FunctionDecl *FD,
1592
                        CallExpr::const_arg_iterator ArgBegin,
1593
                        CallExpr::const_arg_iterator ArgEnd,
1594
                        bool SkipFirstParam = false);
1595
1596
public:
1597
  BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1598
      : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
1599
7.27k
        LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
1600
1601
  void VisitUnaryOperator(const UnaryOperator *UO);
1602
  void VisitBinaryOperator(const BinaryOperator *BO);
1603
  void VisitCastExpr(const CastExpr *CE);
1604
  void VisitCallExpr(const CallExpr *Exp);
1605
  void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1606
  void VisitDeclStmt(const DeclStmt *S);
1607
};
1608
1609
} // namespace
1610
1611
/// Warn if the LSet does not contain a lock sufficient to protect access
1612
/// of at least the passed in AccessKind.
1613
void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1614
                                      AccessKind AK, Expr *MutexExp,
1615
                                      ProtectedOperationKind POK,
1616
2.93k
                                      StringRef DiagKind, SourceLocation Loc) {
1617
2.93k
  LockKind LK = getLockKindFromAccessKind(AK);
1618
2.93k
1619
2.93k
  CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1620
2.93k
  if (Cp.isInvalid()) {
1621
0
    warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1622
0
    return;
1623
2.93k
  } else if (Cp.shouldIgnore()) {
1624
20
    return;
1625
20
  }
1626
2.91k
1627
2.91k
  if (Cp.negative()) {
1628
34
    // Negative capabilities act like locks excluded
1629
34
    const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1630
34
    if (LDat) {
1631
10
      Analyzer->Handler.handleFunExcludesLock(
1632
10
          DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
1633
10
      return;
1634
10
    }
1635
24
1636
24
    // If this does not refer to a negative capability in the same class,
1637
24
    // then stop here.
1638
24
    if (!Analyzer->inCurrentScope(Cp))
1639
10
      return;
1640
14
1641
14
    // Otherwise the negative requirement must be propagated to the caller.
1642
14
    LDat = FSet.findLock(Analyzer->FactMan, Cp);
1643
14
    if (!LDat) {
1644
6
      Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
1645
6
                                           LK_Shared, Loc);
1646
6
    }
1647
14
    return;
1648
14
  }
1649
2.88k
1650
2.88k
  const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
1651
2.88k
  bool NoError = true;
1652
2.88k
  if (!LDat) {
1653
1.14k
    // No exact match found.  Look for a partial match.
1654
1.14k
    LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1655
1.14k
    if (LDat) {
1656
76
      // Warn that there's no precise match.
1657
76
      std::string PartMatchStr = LDat->toString();
1658
76
      StringRef   PartMatchName(PartMatchStr);
1659
76
      Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1660
76
                                           LK, Loc, &PartMatchName);
1661
1.06k
    } else {
1662
1.06k
      // Warn that there's no match at all.
1663
1.06k
      Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1664
1.06k
                                           LK, Loc);
1665
1.06k
    }
1666
1.14k
    NoError = false;
1667
1.14k
  }
1668
2.88k
  // Make sure the mutex we found is the right kind.
1669
2.88k
  if (NoError && 
LDat1.74k
&&
!LDat->isAtLeast(LK)1.74k
) {
1670
28
    Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1671
28
                                         LK, Loc);
1672
28
  }
1673
2.88k
}
1674
1675
/// Warn if the LSet contains the given lock.
1676
void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1677
126
                                   Expr *MutexExp, StringRef DiagKind) {
1678
126
  CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1679
126
  if (Cp.isInvalid()) {
1680
0
    warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1681
0
    return;
1682
126
  } else if (Cp.shouldIgnore()) {
1683
0
    return;
1684
0
  }
1685
126
1686
126
  const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
1687
126
  if (LDat) {
1688
67
    Analyzer->Handler.handleFunExcludesLock(
1689
67
        DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1690
67
  }
1691
126
}
1692
1693
/// Checks guarded_by and pt_guarded_by attributes.
1694
/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1695
/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1696
/// Similarly, we check if the access is to an expression that dereferences
1697
/// a pointer marked with pt_guarded_by.
1698
void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1699
8.53k
                               ProtectedOperationKind POK) {
1700
8.53k
  Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
1701
8.53k
1702
8.53k
  SourceLocation Loc = Exp->getExprLoc();
1703
8.53k
1704
8.53k
  // Local variables of reference type cannot be re-assigned;
1705
8.53k
  // map them to their initializer.
1706
8.57k
  while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1707
3.55k
    const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1708
3.55k
    if (VD && VD->isLocalVarDecl() && 
VD->getType()->isReferenceType()1.67k
) {
1709
44
      if (const auto *E = VD->getInit()) {
1710
44
        // Guard against self-initialization. e.g., int &i = i;
1711
44
        if (E == Exp)
1712
0
          break;
1713
44
        Exp = E;
1714
44
        continue;
1715
44
      }
1716
44
    }
1717
3.51k
    break;
1718
3.51k
  }
1719
8.53k
1720
8.53k
  if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
1721
250
    // For dereferences
1722
250
    if (UO->getOpcode() == UO_Deref)
1723
250
      checkPtAccess(UO->getSubExpr(), AK, POK);
1724
250
    return;
1725
250
  }
1726
8.28k
1727
8.28k
  if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1728
68
    checkPtAccess(AE->getLHS(), AK, POK);
1729
68
    return;
1730
68
  }
1731
8.21k
1732
8.21k
  if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
1733
4.22k
    if (ME->isArrow())
1734
3.42k
      checkPtAccess(ME->getBase(), AK, POK);
1735
799
    else
1736
799
      checkAccess(ME->getBase(), AK, POK);
1737
4.22k
  }
1738
8.21k
1739
8.21k
  const ValueDecl *D = getValueDecl(Exp);
1740
8.21k
  if (!D || 
!D->hasAttrs()7.73k
)
1741
5.75k
    return;
1742
2.46k
1743
2.46k
  if (D->hasAttr<GuardedVarAttr>() && 
FSet.isEmpty(Analyzer->FactMan)44
) {
1744
25
    Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
1745
25
  }
1746
2.46k
1747
2.46k
  for (const auto *I : D->specific_attrs<GuardedByAttr>())
1748
1.91k
    warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
1749
1.91k
                       ClassifyDiagnostic(I), Loc);
1750
2.46k
}
1751
1752
/// Checks pt_guarded_by and pt_guarded_var attributes.
1753
/// POK is the same  operationKind that was passed to checkAccess.
1754
void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1755
4.83k
                                 ProtectedOperationKind POK) {
1756
6.01k
  while (true) {
1757
6.01k
    if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
1758
4
      Exp = PE->getSubExpr();
1759
4
      continue;
1760
4
    }
1761
6.00k
    if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
1762
1.23k
      if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1763
60
        // If it's an actual array, and not a pointer, then it's elements
1764
60
        // are protected by GUARDED_BY, not PT_GUARDED_BY;
1765
60
        checkAccess(CE->getSubExpr(), AK, POK);
1766
60
        return;
1767
60
      }
1768
1.17k
      Exp = CE->getSubExpr();
1769
1.17k
      continue;
1770
1.17k
    }
1771
4.77k
    break;
1772
4.77k
  }
1773
4.83k
1774
4.83k
  // Pass by reference warnings are under a different flag.
1775
4.83k
  ProtectedOperationKind PtPOK = POK_VarDereference;
1776
4.77k
  if (POK == POK_PassByRef) 
PtPOK = POK_PtPassByRef130
;
1777
4.77k
1778
4.77k
  const ValueDecl *D = getValueDecl(Exp);
1779
4.77k
  if (!D || 
!D->hasAttrs()1.14k
)
1780
4.33k
    return;
1781
442
1782
442
  if (D->hasAttr<PtGuardedVarAttr>() && 
FSet.isEmpty(Analyzer->FactMan)10
)
1783
9
    Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
1784
9
                                        Exp->getExprLoc());
1785
442
1786
442
  for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1787
388
    warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
1788
388
                       ClassifyDiagnostic(I), Exp->getExprLoc());
1789
442
}
1790
1791
/// Process a function call, method call, constructor call,
1792
/// or destructor call.  This involves looking at the attributes on the
1793
/// corresponding function/method/constructor/destructor, issuing warnings,
1794
/// and updating the locksets accordingly.
1795
///
1796
/// FIXME: For classes annotated with one of the guarded annotations, we need
1797
/// to treat const method calls as reads and non-const method calls as writes,
1798
/// and check that the appropriate locks are held. Non-const method calls with
1799
/// the same signature as const method calls can be also treated as reads.
1800
///
1801
void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1802
4.29k
                              VarDecl *VD) {
1803
4.29k
  SourceLocation Loc = Exp->getExprLoc();
1804
4.29k
  CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1805
4.29k
  CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1806
4.29k
  CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
1807
4.29k
  StringRef CapDiagKind = "mutex";
1808
4.29k
1809
4.29k
  // Figure out if we're constructing an object of scoped lockable class
1810
4.29k
  bool isScopedVar = false;
1811
4.29k
  if (VD) {
1812
239
    if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1813
239
      const CXXRecordDecl* PD = CD->getParent();
1814
239
      if (PD && PD->hasAttr<ScopedLockableAttr>())
1815
218
        isScopedVar = true;
1816
239
    }
1817
239
  }
1818
4.29k
1819
4.64k
  for(const Attr *At : D->attrs()) {
1820
4.64k
    switch (At->getKind()) {
1821
4.64k
      // When we encounter a lock function, we need to add the lock to our
1822
4.64k
      // lockset.
1823
4.64k
      case attr::AcquireCapability: {
1824
1.70k
        const auto *A = cast<AcquireCapabilityAttr>(At);
1825
1.70k
        Analyzer->getMutexIDs(A->isShared() ? 
SharedLocksToAdd193
1826
1.70k
                                            : 
ExclusiveLocksToAdd1.51k
,
1827
1.70k
                              A, Exp, D, VD);
1828
1.70k
1829
1.70k
        CapDiagKind = ClassifyDiagnostic(A);
1830
1.70k
        break;
1831
4.64k
      }
1832
4.64k
1833
4.64k
      // An assert will add a lock to the lockset, but will not generate
1834
4.64k
      // a warning if it is already there, and will not generate a warning
1835
4.64k
      // if it is not removed.
1836
4.64k
      case attr::AssertExclusiveLock: {
1837
32
        const auto *A = cast<AssertExclusiveLockAttr>(At);
1838
32
1839
32
        CapExprSet AssertLocks;
1840
32
        Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1841
32
        for (const auto &AssertLock : AssertLocks)
1842
34
          Analyzer->addLock(FSet,
1843
34
                            llvm::make_unique<LockableFactEntry>(
1844
34
                                AssertLock, LK_Exclusive, Loc, false, true),
1845
34
                            ClassifyDiagnostic(A));
1846
32
        break;
1847
4.64k
      }
1848
4.64k
      case attr::AssertSharedLock: {
1849
8
        const auto *A = cast<AssertSharedLockAttr>(At);
1850
8
1851
8
        CapExprSet AssertLocks;
1852
8
        Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1853
8
        for (const auto &AssertLock : AssertLocks)
1854
10
          Analyzer->addLock(FSet,
1855
10
                            llvm::make_unique<LockableFactEntry>(
1856
10
                                AssertLock, LK_Shared, Loc, false, true),
1857
10
                            ClassifyDiagnostic(A));
1858
8
        break;
1859
4.64k
      }
1860
4.64k
1861
4.64k
      case attr::AssertCapability: {
1862
40
        const auto *A = cast<AssertCapabilityAttr>(At);
1863
40
        CapExprSet AssertLocks;
1864
40
        Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1865
40
        for (const auto &AssertLock : AssertLocks)
1866
44
          Analyzer->addLock(FSet,
1867
44
                            llvm::make_unique<LockableFactEntry>(
1868
44
                                AssertLock,
1869
44
                                A->isShared() ? 
LK_Shared10
:
LK_Exclusive34
, Loc,
1870
44
                                false, true),
1871
44
                            ClassifyDiagnostic(A));
1872
40
        break;
1873
4.64k
      }
1874
4.64k
1875
4.64k
      // When we encounter an unlock function, we need to remove unlocked
1876
4.64k
      // mutexes from the lockset, and flag a warning if they are not there.
1877
4.64k
      case attr::ReleaseCapability: {
1878
1.88k
        const auto *A = cast<ReleaseCapabilityAttr>(At);
1879
1.88k
        if (A->isGeneric())
1880
1.70k
          Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1881
188
        else if (A->isShared())
1882
38
          Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1883
150
        else
1884
150
          Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
1885
1.88k
1886
1.88k
        CapDiagKind = ClassifyDiagnostic(A);
1887
1.88k
        break;
1888
4.64k
      }
1889
4.64k
1890
4.64k
      case attr::RequiresCapability: {
1891
572
        const auto *A = cast<RequiresCapabilityAttr>(At);
1892
636
        for (auto *Arg : A->args()) {
1893
636
          warnIfMutexNotHeld(D, Exp, A->isShared() ? 
AK_Read111
:
AK_Written525
, Arg,
1894
636
                             POK_FunctionCall, ClassifyDiagnostic(A),
1895
636
                             Exp->getExprLoc());
1896
636
          // use for adopting a lock
1897
636
          if (isScopedVar) {
1898
16
            Analyzer->getMutexIDs(A->isShared() ? 
ScopedSharedReqs8
1899
16
                                                : 
ScopedExclusiveReqs8
,
1900
16
                                  A, Exp, D, VD);
1901
16
          }
1902
636
        }
1903
572
        break;
1904
4.64k
      }
1905
4.64k
1906
4.64k
      case attr::LocksExcluded: {
1907
116
        const auto *A = cast<LocksExcludedAttr>(At);
1908
116
        for (auto *Arg : A->args())
1909
126
          warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
1910
116
        break;
1911
4.64k
      }
1912
4.64k
1913
4.64k
      // Ignore attributes unrelated to thread-safety
1914
4.64k
      default:
1915
276
        break;
1916
4.64k
    }
1917
4.64k
  }
1918
4.29k
1919
4.29k
  // Remove locks first to allow lock upgrading/downgrading.
1920
4.29k
  // FIXME -- should only fully remove if the attribute refers to 'this'.
1921
4.29k
  bool Dtor = isa<CXXDestructorDecl>(D);
1922
4.29k
  for (const auto &M : ExclusiveLocksToRemove)
1923
150
    Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1924
4.29k
  for (const auto &M : SharedLocksToRemove)
1925
38
    Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1926
4.29k
  for (const auto &M : GenericLocksToRemove)
1927
1.64k
    Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1928
4.29k
1929
4.29k
  // Add locks.
1930
4.29k
  for (const auto &M : ExclusiveLocksToAdd)
1931
1.47k
    Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1932
1.47k
                                M, LK_Exclusive, Loc, isScopedVar),
1933
1.47k
                      CapDiagKind);
1934
4.29k
  for (const auto &M : SharedLocksToAdd)
1935
181
    Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1936
181
                                M, LK_Shared, Loc, isScopedVar),
1937
181
                      CapDiagKind);
1938
4.29k
1939
4.29k
  if (isScopedVar) {
1940
218
    // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1941
218
    SourceLocation MLoc = VD->getLocation();
1942
218
    DeclRefExpr DRE(VD->getASTContext(), VD, false, VD->getType(), VK_LValue,
1943
218
                    VD->getLocation());
1944
218
    // FIXME: does this store a pointer to DRE?
1945
218
    CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
1946
218
1947
218
    auto ScopedEntry = llvm::make_unique<ScopedLockableFactEntry>(Scp, MLoc);
1948
218
    for (const auto &M : ExclusiveLocksToAdd)
1949
150
      ScopedEntry->addExclusiveLock(M);
1950
218
    for (const auto &M : ScopedExclusiveReqs)
1951
8
      ScopedEntry->addExclusiveLock(M);
1952
218
    for (const auto &M : SharedLocksToAdd)
1953
20
      ScopedEntry->addSharedLock(M);
1954
218
    for (const auto &M : ScopedSharedReqs)
1955
8
      ScopedEntry->addSharedLock(M);
1956
218
    for (const auto &M : ExclusiveLocksToRemove)
1957
28
      ScopedEntry->addExclusiveUnlock(M);
1958
218
    for (const auto &M : SharedLocksToRemove)
1959
8
      ScopedEntry->addSharedUnlock(M);
1960
218
    Analyzer->addLock(FSet, std::move(ScopedEntry), CapDiagKind);
1961
218
  }
1962
4.29k
}
1963
1964
/// For unary operations which read and write a variable, we need to
1965
/// check whether we hold any required mutexes. Reads are checked in
1966
/// VisitCastExpr.
1967
728
void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
1968
728
  switch (UO->getOpcode()) {
1969
728
    case UO_PostDec:
1970
28
    case UO_PostInc:
1971
28
    case UO_PreDec:
1972
28
    case UO_PreInc:
1973
28
      checkAccess(UO->getSubExpr(), AK_Written);
1974
28
      break;
1975
700
    default:
1976
700
      break;
1977
728
  }
1978
728
}
1979
1980
/// For binary operations which assign to a variable (writes), we need to check
1981
/// whether we hold any required mutexes.
1982
/// FIXME: Deal with non-primitive types.
1983
1.84k
void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
1984
1.84k
  if (!BO->isAssignmentOp())
1985
379
    return;
1986
1.46k
1987
1.46k
  // adjust the context
1988
1.46k
  LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1989
1.46k
1990
1.46k
  checkAccess(BO->getLHS(), AK_Written);
1991
1.46k
}
1992
1993
/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1994
/// need to ensure we hold any required mutexes.
1995
/// FIXME: Deal with non-primitive types.
1996
4.69k
void BuildLockset::VisitCastExpr(const CastExpr *CE) {
1997
4.69k
  if (CE->getCastKind() != CK_LValueToRValue)
1998
2.43k
    return;
1999
2.26k
  checkAccess(CE->getSubExpr(), AK_Read);
2000
2.26k
}
2001
2002
void BuildLockset::examineArguments(const FunctionDecl *FD,
2003
                                    CallExpr::const_arg_iterator ArgBegin,
2004
                                    CallExpr::const_arg_iterator ArgEnd,
2005
5.77k
                                    bool SkipFirstParam) {
2006
5.77k
  // Currently we can't do anything if we don't know the function declaration.
2007
5.77k
  if (!FD)
2008
12
    return;
2009
5.75k
2010
5.75k
  // NO_THREAD_SAFETY_ANALYSIS does double duty here.  Normally it
2011
5.75k
  // only turns off checking within the body of a function, but we also
2012
5.75k
  // use it to turn off checking in arguments to the function.  This
2013
5.75k
  // could result in some false negatives, but the alternative is to
2014
5.75k
  // create yet another attribute.
2015
5.75k
  if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
2016
40
    return;
2017
5.71k
2018
5.71k
  const ArrayRef<ParmVarDecl *> Params = FD->parameters();
2019
5.71k
  auto Param = Params.begin();
2020
5.71k
  if (SkipFirstParam)
2021
12
    ++Param;
2022
5.71k
2023
5.71k
  // There can be default arguments, so we stop when one iterator is at end().
2024
6.98k
  for (auto Arg = ArgBegin; Param != Params.end() && 
Arg != ArgEnd1.26k
;
2025
5.71k
       
++Param, ++Arg1.26k
) {
2026
1.26k
    QualType Qt = (*Param)->getType();
2027
1.26k
    if (Qt->isReferenceType())
2028
253
      checkAccess(*Arg, AK_Read, POK_PassByRef);
2029
1.26k
  }
2030
5.71k
}
2031
2032
5.25k
void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
2033
5.25k
  if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2034
3.92k
    const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
2035
3.92k
    // ME can be null when calling a method pointer
2036
3.92k
    const CXXMethodDecl *MD = CE->getMethodDecl();
2037
3.92k
2038
3.92k
    if (ME && 
MD3.92k
) {
2039
3.92k
      if (ME->isArrow()) {
2040
752
        if (MD->isConst())
2041
16
          checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2042
736
        else // FIXME -- should be AK_Written
2043
736
          checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2044
3.16k
      } else {
2045
3.16k
        if (MD->isConst())
2046
137
          checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2047
3.03k
        else     // FIXME -- should be AK_Written
2048
3.03k
          checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2049
3.16k
      }
2050
3.92k
    }
2051
3.92k
2052
3.92k
    examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
2053
3.92k
  } else 
if (const auto *1.33k
OE1.33k
= dyn_cast<CXXOperatorCallExpr>(Exp)) {
2054
432
    auto OEop = OE->getOperator();
2055
432
    switch (OEop) {
2056
432
      case OO_Equal: {
2057
32
        const Expr *Target = OE->getArg(0);
2058
32
        const Expr *Source = OE->getArg(1);
2059
32
        checkAccess(Target, AK_Written);
2060
32
        checkAccess(Source, AK_Read);
2061
32
        break;
2062
432
      }
2063
432
      case OO_Star:
2064
344
      case OO_Arrow:
2065
344
      case OO_Subscript:
2066
344
        if (!(OEop == OO_Star && 
OE->getNumArgs() > 1116
)) {
2067
340
          // Grrr.  operator* can be multiplication...
2068
340
          checkPtAccess(OE->getArg(0), AK_Read);
2069
340
        }
2070
344
        LLVM_FALLTHROUGH;
2071
400
      default: {
2072
400
        // TODO: get rid of this, and rely on pass-by-ref instead.
2073
400
        const Expr *Obj = OE->getArg(0);
2074
400
        checkAccess(Obj, AK_Read);
2075
400
        // Check the remaining arguments. For method operators, the first
2076
400
        // argument is the implicit self argument, and doesn't appear in the
2077
400
        // FunctionDecl, but for non-methods it does.
2078
400
        const FunctionDecl *FD = OE->getDirectCallee();
2079
400
        examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
2080
400
                         /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
2081
400
        break;
2082
900
      }
2083
900
    }
2084
900
  } else {
2085
900
    examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
2086
900
  }
2087
5.25k
2088
5.25k
  auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2089
5.25k
  if(!D || !D->hasAttrs())
2090
1.41k
    return;
2091
3.84k
  handleCall(Exp, D);
2092
3.84k
}
2093
2094
577
void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
2095
577
  const CXXConstructorDecl *D = Exp->getConstructor();
2096
577
  if (D && D->isCopyConstructor()) {
2097
31
    const Expr* Source = Exp->getArg(0);
2098
31
    checkAccess(Source, AK_Read);
2099
546
  } else {
2100
546
    examineArguments(D, Exp->arg_begin(), Exp->arg_end());
2101
546
  }
2102
577
}
2103
2104
static CXXConstructorDecl *
2105
2
findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2106
2
  // Prefer a move constructor over a copy constructor. If there's more than
2107
2
  // one copy constructor or more than one move constructor, we arbitrarily
2108
2
  // pick the first declared such constructor rather than trying to guess which
2109
2
  // one is more appropriate.
2110
2
  CXXConstructorDecl *CopyCtor = nullptr;
2111
4
  for (auto *Ctor : RD->ctors()) {
2112
4
    if (Ctor->isDeleted())
2113
0
      continue;
2114
4
    if (Ctor->isMoveConstructor())
2115
2
      return Ctor;
2116
2
    if (!CopyCtor && Ctor->isCopyConstructor())
2117
0
      CopyCtor = Ctor;
2118
2
  }
2119
2
  
return CopyCtor0
;
2120
2
}
2121
2122
static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2123
2
                               SourceLocation Loc) {
2124
2
  ASTContext &Ctx = CD->getASTContext();
2125
2
  return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2126
2
                                  CD, true, Args, false, false, false, false,
2127
2
                                  CXXConstructExpr::CK_Complete,
2128
2
                                  SourceRange(Loc, Loc));
2129
2
}
2130
2131
893
void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
2132
893
  // adjust the context
2133
893
  LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2134
893
2135
893
  for (auto *D : S->getDeclGroup()) {
2136
893
    if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2137
893
      Expr *E = VD->getInit();
2138
893
      if (!E)
2139
96
        continue;
2140
797
      E = E->IgnoreParens();
2141
797
2142
797
      // handle constructors that involve temporaries
2143
797
      if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2144
29
        E = EWC->getSubExpr();
2145
797
      if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2146
2
        E = BTE->getSubExpr();
2147
797
2148
797
      if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2149
460
        const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2150
460
        if (!CtorD || !CtorD->hasAttrs())
2151
223
          continue;
2152
237
        handleCall(E, CtorD, VD);
2153
337
      } else if (isa<CallExpr>(E) && 
E->isRValue()71
) {
2154
71
        // If the object is initialized by a function call that returns a
2155
71
        // scoped lockable by value, use the attributes on the copy or move
2156
71
        // constructor to figure out what effect that should have on the
2157
71
        // lockset.
2158
71
        // FIXME: Is this really the best way to handle this situation?
2159
71
        auto *RD = E->getType()->getAsCXXRecordDecl();
2160
71
        if (!RD || 
!RD->hasAttr<ScopedLockableAttr>()2
)
2161
69
          continue;
2162
2
        CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2163
2
        if (!CtorD || !CtorD->hasAttrs())
2164
0
          continue;
2165
2
        handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
2166
2
      }
2167
797
    }
2168
893
  }
2169
893
}
2170
2171
/// Compute the intersection of two locksets and issue warnings for any
2172
/// locks in the symmetric difference.
2173
///
2174
/// This function is used at a merge point in the CFG when comparing the lockset
2175
/// of each branch being merged. For example, given the following sequence:
2176
/// A; if () then B; else C; D; we need to check that the lockset after B and C
2177
/// are the same. In the event of a difference, we use the intersection of these
2178
/// two locksets at the start of D.
2179
///
2180
/// \param FSet1 The first lockset.
2181
/// \param FSet2 The second lockset.
2182
/// \param JoinLoc The location of the join point for error reporting
2183
/// \param LEK1 The error message to report if a mutex is missing from LSet1
2184
/// \param LEK2 The error message to report if a mutex is missing from Lset2
2185
void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2186
                                            const FactSet &FSet2,
2187
                                            SourceLocation JoinLoc,
2188
                                            LockErrorKind LEK1,
2189
                                            LockErrorKind LEK2,
2190
2.63k
                                            bool Modify) {
2191
2.63k
  FactSet FSet1Orig = FSet1;
2192
2.63k
2193
2.63k
  // Find locks in FSet2 that conflict or are not in FSet1, and warn.
2194
2.63k
  for (const auto &Fact : FSet2) {
2195
2.31k
    const FactEntry *LDat1 = nullptr;
2196
2.31k
    const FactEntry *LDat2 = &FactMan[Fact];
2197
2.31k
    FactSet::iterator Iter1  = FSet1.findLockIter(FactMan, *LDat2);
2198
2.31k
    if (Iter1 != FSet1.end()) 
LDat1 = &FactMan[*Iter1]979
;
2199
2.31k
2200
2.31k
    if (LDat1) {
2201
979
      if (LDat1->kind() != LDat2->kind()) {
2202
20
        Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2203
20
                                         LDat2->loc(), LDat1->loc());
2204
20
        if (Modify && 
LDat1->kind() != LK_Exclusive12
) {
2205
8
          // Take the exclusive lock, which is the one in FSet2.
2206
8
          *Iter1 = Fact;
2207
8
        }
2208
20
      }
2209
959
      else if (Modify && 
LDat1->asserted()457
&&
!LDat2->asserted()12
) {
2210
8
        // The non-asserted lock in FSet2 is the one we want to track.
2211
8
        *Iter1 = Fact;
2212
8
      }
2213
1.34k
    } else {
2214
1.34k
      LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2215
1.34k
                                           Handler);
2216
1.34k
    }
2217
2.31k
  }
2218
2.63k
2219
2.63k
  // Find locks in FSet1 that are not in FSet2, and remove them.
2220
2.63k
  for (const auto &Fact : FSet1Orig) {
2221
1.22k
    const FactEntry *LDat1 = &FactMan[Fact];
2222
1.22k
    const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
2223
1.22k
2224
1.22k
    if (!LDat2) {
2225
244
      LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2226
244
                                           Handler);
2227
244
      if (Modify)
2228
156
        FSet1.removeLock(FactMan, *LDat1);
2229
244
    }
2230
1.22k
  }
2231
2.63k
}
2232
2233
// Return true if block B never continues to its successors.
2234
5.89k
static bool neverReturns(const CFGBlock *B) {
2235
5.89k
  if (B->hasNoReturnElement())
2236
24
    return true;
2237
5.86k
  if (B->empty())
2238
2.00k
    return false;
2239
3.86k
2240
3.86k
  CFGElement Last = B->back();
2241
3.86k
  if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2242
3.62k
    if (isa<CXXThrowExpr>(S->getStmt()))
2243
4
      return true;
2244
3.85k
  }
2245
3.85k
  return false;
2246
3.85k
}
2247
2248
/// Check a function's CFG for thread-safety violations.
2249
///
2250
/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2251
/// at the end of each block, and issue warnings for thread safety violations.
2252
/// Each block in the CFG is traversed exactly once.
2253
2.14k
void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2254
2.14k
  // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2255
2.14k
  // For now, we just use the walker to set things up.
2256
2.14k
  threadSafety::CFGWalker walker;
2257
2.14k
  if (!walker.init(AC))
2258
3
    return;
2259
2.14k
2260
2.14k
  // AC.dumpCFG(true);
2261
2.14k
  // threadSafety::printSCFG(walker);
2262
2.14k
2263
2.14k
  CFG *CFGraph = walker.getGraph();
2264
2.14k
  const NamedDecl *D = walker.getDecl();
2265
2.14k
  const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
2266
2.14k
  CurrentMethod = dyn_cast<CXXMethodDecl>(D);
2267
2.14k
2268
2.14k
  if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
2269
36
    return;
2270
2.10k
2271
2.10k
  // FIXME: Do something a bit more intelligent inside constructor and
2272
2.10k
  // destructor code.  Constructors and destructors must assume unique access
2273
2.10k
  // to 'this', so checks on member variable access is disabled, but we should
2274
2.10k
  // still enable checks on other objects.
2275
2.10k
  if (isa<CXXConstructorDecl>(D))
2276
51
    return;  // Don't check inside constructors.
2277
2.05k
  if (isa<CXXDestructorDecl>(D))
2278
26
    return;  // Don't check inside destructors.
2279
2.02k
2280
2.02k
  Handler.enterFunction(CurrentFunction);
2281
2.02k
2282
2.02k
  BlockInfo.resize(CFGraph->getNumBlockIDs(),
2283
2.02k
    CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2284
2.02k
2285
2.02k
  // We need to explore the CFG via a "topological" ordering.
2286
2.02k
  // That way, we will be guaranteed to have information about required
2287
2.02k
  // predecessor locksets when exploring a new block.
2288
2.02k
  const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
2289
2.02k
  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2290
2.02k
2291
2.02k
  // Mark entry block as reachable
2292
2.02k
  BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2293
2.02k
2294
2.02k
  // Compute SSA names for local variables
2295
2.02k
  LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2296
2.02k
2297
2.02k
  // Fill in source locations for all CFGBlocks.
2298
2.02k
  findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2299
2.02k
2300
2.02k
  CapExprSet ExclusiveLocksAcquired;
2301
2.02k
  CapExprSet SharedLocksAcquired;
2302
2.02k
  CapExprSet LocksReleased;
2303
2.02k
2304
2.02k
  // Add locks from exclusive_locks_required and shared_locks_required
2305
2.02k
  // to initial lockset. Also turn off checking for lock and unlock functions.
2306
2.02k
  // FIXME: is there a more intelligent way to check lock/unlock functions?
2307
2.02k
  if (!SortedGraph->empty() && D->hasAttrs()) {
2308
542
    const CFGBlock *FirstBlock = *SortedGraph->begin();
2309
542
    FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2310
542
2311
542
    CapExprSet ExclusiveLocksToAdd;
2312
542
    CapExprSet SharedLocksToAdd;
2313
542
    StringRef CapDiagKind = "mutex";
2314
542
2315
542
    SourceLocation Loc = D->getLocation();
2316
672
    for (const auto *Attr : D->attrs()) {
2317
672
      Loc = Attr->getLocation();
2318
672
      if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2319
398
        getMutexIDs(A->isShared() ? 
SharedLocksToAdd59
:
ExclusiveLocksToAdd339
, A,
2320
398
                    nullptr, D);
2321
398
        CapDiagKind = ClassifyDiagnostic(A);
2322
398
      } else 
if (const auto *274
A274
= dyn_cast<ReleaseCapabilityAttr>(Attr)) {
2323
91
        // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2324
91
        // We must ignore such methods.
2325
91
        if (A->args_size() == 0)
2326
14
          return;
2327
77
        getMutexIDs(A->isShared() ? 
SharedLocksToAdd8
:
ExclusiveLocksToAdd69
, A,
2328
77
                    nullptr, D);
2329
77
        getMutexIDs(LocksReleased, A, nullptr, D);
2330
77
        CapDiagKind = ClassifyDiagnostic(A);
2331
183
      } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
2332
106
        if (A->args_size() == 0)
2333
18
          return;
2334
88
        getMutexIDs(A->isShared() ? 
SharedLocksAcquired28
2335
88
                                  : 
ExclusiveLocksAcquired60
,
2336
88
                    A, nullptr, D);
2337
88
        CapDiagKind = ClassifyDiagnostic(A);
2338
88
      } else 
if (77
isa<ExclusiveTrylockFunctionAttr>(Attr)77
) {
2339
4
        // Don't try to check trylock functions for now.
2340
4
        return;
2341
73
      } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2342
2
        // Don't try to check trylock functions for now.
2343
2
        return;
2344
71
      } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2345
6
        // Don't try to check trylock functions for now.
2346
6
        return;
2347
6
      }
2348
672
    }
2349
542
2350
542
    // FIXME -- Loc can be wrong here.
2351
542
    
for (const auto &Mu : ExclusiveLocksToAdd)498
{
2352
420
      auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2353
420
      Entry->setDeclared(true);
2354
420
      addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2355
420
    }
2356
498
    for (const auto &Mu : SharedLocksToAdd) {
2357
83
      auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2358
83
      Entry->setDeclared(true);
2359
83
      addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2360
83
    }
2361
498
  }
2362
2.02k
2363
7.29k
  
for (const auto *CurrBlock : *SortedGraph)1.98k
{
2364
7.29k
    unsigned CurrBlockID = CurrBlock->getBlockID();
2365
7.29k
    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2366
7.29k
2367
7.29k
    // Use the default initial lockset in case there are no predecessors.
2368
7.29k
    VisitedBlocks.insert(CurrBlock);
2369
7.29k
2370
7.29k
    // Iterate through the predecessor blocks and warn if the lockset for all
2371
7.29k
    // predecessors is not the same. We take the entry lockset of the current
2372
7.29k
    // block to be the intersection of all previous locksets.
2373
7.29k
    // FIXME: By keeping the intersection, we may output more errors in future
2374
7.29k
    // for a lock which is not in the intersection, but was in the union. We
2375
7.29k
    // may want to also keep the union in future. As an example, let's say
2376
7.29k
    // the intersection contains Mutex L, and the union contains L and M.
2377
7.29k
    // Later we unlock M. At this point, we would output an error because we
2378
7.29k
    // never locked M; although the real error is probably that we forgot to
2379
7.29k
    // lock M on all code paths. Conversely, let's say that later we lock M.
2380
7.29k
    // In this case, we should compare against the intersection instead of the
2381
7.29k
    // union because the real error is probably that we forgot to unlock M on
2382
7.29k
    // all code paths.
2383
7.29k
    bool LocksetInitialized = false;
2384
7.29k
    SmallVector<CFGBlock *, 8> SpecialBlocks;
2385
7.29k
    for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2386
13.2k
         PE  = CurrBlock->pred_end(); PI != PE; 
++PI5.99k
) {
2387
5.99k
      // if *PI -> CurrBlock is a back edge
2388
5.99k
      if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
2389
106
        continue;
2390
5.89k
2391
5.89k
      unsigned PrevBlockID = (*PI)->getBlockID();
2392
5.89k
      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2393
5.89k
2394
5.89k
      // Ignore edges from blocks that can't return.
2395
5.89k
      if (neverReturns(*PI) || 
!PrevBlockInfo->Reachable5.86k
)
2396
28
        continue;
2397
5.86k
2398
5.86k
      // Okay, we can reach this block from the entry.
2399
5.86k
      CurrBlockInfo->Reachable = true;
2400
5.86k
2401
5.86k
      // If the previous block ended in a 'continue' or 'break' statement, then
2402
5.86k
      // a difference in locksets is probably due to a bug in that block, rather
2403
5.86k
      // than in some other predecessor. In that case, keep the other
2404
5.86k
      // predecessor's lockset.
2405
5.86k
      if (const Stmt *Terminator = (*PI)->getTerminatorStmt()) {
2406
1.38k
        if (isa<ContinueStmt>(Terminator) || 
isa<BreakStmt>(Terminator)1.36k
) {
2407
26
          SpecialBlocks.push_back(*PI);
2408
26
          continue;
2409
26
        }
2410
5.83k
      }
2411
5.83k
2412
5.83k
      FactSet PrevLockset;
2413
5.83k
      getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2414
5.83k
2415
5.83k
      if (!LocksetInitialized) {
2416
5.29k
        CurrBlockInfo->EntrySet = PrevLockset;
2417
5.29k
        LocksetInitialized = true;
2418
5.29k
      } else {
2419
545
        intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2420
545
                         CurrBlockInfo->EntryLoc,
2421
545
                         LEK_LockedSomePredecessors);
2422
545
      }
2423
5.83k
    }
2424
7.29k
2425
7.29k
    // Skip rest of block if it's not reachable.
2426
7.29k
    if (!CurrBlockInfo->Reachable)
2427
16
      continue;
2428
7.27k
2429
7.27k
    // Process continue and break blocks. Assume that the lockset for the
2430
7.27k
    // resulting block is unaffected by any discrepancies in them.
2431
7.27k
    for (const auto *PrevBlock : SpecialBlocks) {
2432
26
      unsigned PrevBlockID = PrevBlock->getBlockID();
2433
26
      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2434
26
2435
26
      if (!LocksetInitialized) {
2436
0
        CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2437
0
        LocksetInitialized = true;
2438
26
      } else {
2439
26
        // Determine whether this edge is a loop terminator for diagnostic
2440
26
        // purposes. FIXME: A 'break' statement might be a loop terminator, but
2441
26
        // it might also be part of a switch. Also, a subsequent destructor
2442
26
        // might add to the lockset, in which case the real issue might be a
2443
26
        // double lock on the other path.
2444
26
        const Stmt *Terminator = PrevBlock->getTerminatorStmt();
2445
26
        bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2446
26
2447
26
        FactSet PrevLockset;
2448
26
        getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2449
26
                       PrevBlock, CurrBlock);
2450
26
2451
26
        // Do not update EntrySet.
2452
26
        intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2453
26
                         PrevBlockInfo->ExitLoc,
2454
26
                         IsLoop ? 
LEK_LockedSomeLoopIterations16
2455
26
                                : 
LEK_LockedSomePredecessors10
,
2456
26
                         false);
2457
26
      }
2458
26
    }
2459
7.27k
2460
7.27k
    BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2461
7.27k
2462
7.27k
    // Visit all the statements in the basic block.
2463
33.7k
    for (const auto &BI : *CurrBlock) {
2464
33.7k
      switch (BI.getKind()) {
2465
33.7k
        case CFGElement::Statement: {
2466
33.4k
          CFGStmt CS = BI.castAs<CFGStmt>();
2467
33.4k
          LocksetBuilder.Visit(CS.getStmt());
2468
33.4k
          break;
2469
33.7k
        }
2470
33.7k
        // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2471
33.7k
        case CFGElement::AutomaticObjectDtor: {
2472
254
          CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
2473
254
          const auto *DD = AD.getDestructorDecl(AC.getASTContext());
2474
254
          if (!DD->hasAttrs())
2475
39
            break;
2476
215
2477
215
          // Create a dummy expression,
2478
215
          auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
2479
215
          DeclRefExpr DRE(VD->getASTContext(), VD, false,
2480
215
                          VD->getType().getNonReferenceType(), VK_LValue,
2481
215
                          AD.getTriggerStmt()->getEndLoc());
2482
215
          LocksetBuilder.handleCall(&DRE, DD);
2483
215
          break;
2484
215
        }
2485
215
        default:
2486
29
          break;
2487
33.7k
      }
2488
33.7k
    }
2489
7.27k
    CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2490
7.27k
2491
7.27k
    // For every back edge from CurrBlock (the end of the loop) to another block
2492
7.27k
    // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2493
7.27k
    // the one held at the beginning of FirstLoopBlock. We can look up the
2494
7.27k
    // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2495
7.27k
    for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2496
13.2k
         SE  = CurrBlock->succ_end(); SI != SE; 
++SI5.99k
) {
2497
5.99k
      // if CurrBlock -> *SI is *not* a back edge
2498
5.99k
      if (*SI == nullptr || 
!VisitedBlocks.alreadySet(*SI)5.99k
)
2499
5.89k
        continue;
2500
98
2501
98
      CFGBlock *FirstLoopBlock = *SI;
2502
98
      CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2503
98
      CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2504
98
      intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2505
98
                       PreLoop->EntryLoc,
2506
98
                       LEK_LockedSomeLoopIterations,
2507
98
                       false);
2508
98
    }
2509
7.27k
  }
2510
1.98k
2511
1.98k
  CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2512
1.98k
  CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
2513
1.98k
2514
1.98k
  // Skip the final check if the exit block is unreachable.
2515
1.98k
  if (!Final->Reachable)
2516
20
    return;
2517
1.96k
2518
1.96k
  // By default, we expect all locks held on entry to be held on exit.
2519
1.96k
  FactSet ExpectedExitSet = Initial->EntrySet;
2520
1.96k
2521
1.96k
  // Adjust the expected exit set by adding or removing locks, as declared
2522
1.96k
  // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
2523
1.96k
  // issue the appropriate warning.
2524
1.96k
  // FIXME: the location here is not quite right.
2525
1.96k
  for (const auto &Lock : ExclusiveLocksAcquired)
2526
52
    ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2527
52
                                         Lock, LK_Exclusive, D->getLocation()));
2528
1.96k
  for (const auto &Lock : SharedLocksAcquired)
2529
24
    ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2530
24
                                         Lock, LK_Shared, D->getLocation()));
2531
1.96k
  for (const auto &Lock : LocksReleased)
2532
69
    ExpectedExitSet.removeLock(FactMan, Lock);
2533
1.96k
2534
1.96k
  // FIXME: Should we call this function for all blocks which exit the function?
2535
1.96k
  intersectAndWarn(ExpectedExitSet, Final->ExitSet,
2536
1.96k
                   Final->ExitLoc,
2537
1.96k
                   LEK_LockedAtEndOfFunction,
2538
1.96k
                   LEK_NotLockedAtEndOfFunction,
2539
1.96k
                   false);
2540
1.96k
2541
1.96k
  Handler.leaveFunction(CurrentFunction);
2542
1.96k
}
2543
2544
/// Check a function's CFG for thread-safety violations.
2545
///
2546
/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2547
/// at the end of each block, and issue warnings for thread safety violations.
2548
/// Each block in the CFG is traversed exactly once.
2549
void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2550
                                           ThreadSafetyHandler &Handler,
2551
2.14k
                                           BeforeSet **BSet) {
2552
2.14k
  if (!*BSet)
2553
39
    *BSet = new BeforeSet;
2554
2.14k
  ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
2555
2.14k
  Analyzer.runAnalysis(AC);
2556
2.14k
}
2557
2558
32.9k
void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
2559
2560
/// Helper function that returns a LockKind required for the given level
2561
/// of access.
2562
2.97k
LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
2563
2.97k
  switch (AK) {
2564
2.97k
    case AK_Read :
2565
1.20k
      return LK_Shared;
2566
2.97k
    case AK_Written :
2567
1.76k
      return LK_Exclusive;
2568
0
  }
2569
0
  llvm_unreachable("Unknown AccessKind");
2570
0
}