clang  8.0.0svn
Consumed.cpp
Go to the documentation of this file.
1 //===- Consumed.cpp -------------------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // A intra-procedural analysis for checking consumed properties. This is based,
11 // in part, on research on linear types.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/AST/Type.h"
26 #include "clang/Analysis/CFG.h"
27 #include "clang/Basic/LLVM.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include <cassert>
37 #include <memory>
38 #include <utility>
39 
40 // TODO: Adjust states of args to constructors in the same way that arguments to
41 // function calls are handled.
42 // TODO: Use information from tests in for- and while-loop conditional.
43 // TODO: Add notes about the actual and expected state for
44 // TODO: Correctly identify unreachable blocks when chaining boolean operators.
45 // TODO: Adjust the parser and AttributesList class to support lists of
46 // identifiers.
47 // TODO: Warn about unreachable code.
48 // TODO: Switch to using a bitmap to track unreachable blocks.
49 // TODO: Handle variable definitions, e.g. bool valid = x.isValid();
50 // if (valid) ...; (Deferred)
51 // TODO: Take notes on state transitions to provide better warning messages.
52 // (Deferred)
53 // TODO: Test nested conditionals: A) Checking the same value multiple times,
54 // and 2) Checking different values. (Deferred)
55 
56 using namespace clang;
57 using namespace consumed;
58 
59 // Key method definition
61 
62 static SourceLocation getFirstStmtLoc(const CFGBlock *Block) {
63  // Find the source location of the first statement in the block, if the block
64  // is not empty.
65  for (const auto &B : *Block)
66  if (Optional<CFGStmt> CS = B.getAs<CFGStmt>())
67  return CS->getStmt()->getBeginLoc();
68 
69  // Block is empty.
70  // If we have one successor, return the first statement in that block
71  if (Block->succ_size() == 1 && *Block->succ_begin())
72  return getFirstStmtLoc(*Block->succ_begin());
73 
74  return {};
75 }
76 
77 static SourceLocation getLastStmtLoc(const CFGBlock *Block) {
78  // Find the source location of the last statement in the block, if the block
79  // is not empty.
80  if (const Stmt *StmtNode = Block->getTerminator()) {
81  return StmtNode->getBeginLoc();
82  } else {
83  for (CFGBlock::const_reverse_iterator BI = Block->rbegin(),
84  BE = Block->rend(); BI != BE; ++BI) {
85  if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>())
86  return CS->getStmt()->getBeginLoc();
87  }
88  }
89 
90  // If we have one successor, return the first statement in that block
91  SourceLocation Loc;
92  if (Block->succ_size() == 1 && *Block->succ_begin())
93  Loc = getFirstStmtLoc(*Block->succ_begin());
94  if (Loc.isValid())
95  return Loc;
96 
97  // If we have one predecessor, return the last statement in that block
98  if (Block->pred_size() == 1 && *Block->pred_begin())
99  return getLastStmtLoc(*Block->pred_begin());
100 
101  return Loc;
102 }
103 
105  switch (State) {
106  case CS_Unconsumed:
107  return CS_Consumed;
108  case CS_Consumed:
109  return CS_Unconsumed;
110  case CS_None:
111  return CS_None;
112  case CS_Unknown:
113  return CS_Unknown;
114  }
115  llvm_unreachable("invalid enum");
116 }
117 
118 static bool isCallableInState(const CallableWhenAttr *CWAttr,
120  for (const auto &S : CWAttr->callableStates()) {
121  ConsumedState MappedAttrState = CS_None;
122 
123  switch (S) {
125  MappedAttrState = CS_Unknown;
126  break;
127 
128  case CallableWhenAttr::Unconsumed:
129  MappedAttrState = CS_Unconsumed;
130  break;
131 
132  case CallableWhenAttr::Consumed:
133  MappedAttrState = CS_Consumed;
134  break;
135  }
136 
137  if (MappedAttrState == State)
138  return true;
139  }
140 
141  return false;
142 }
143 
144 static bool isConsumableType(const QualType &QT) {
145  if (QT->isPointerType() || QT->isReferenceType())
146  return false;
147 
148  if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl())
149  return RD->hasAttr<ConsumableAttr>();
150 
151  return false;
152 }
153 
154 static bool isAutoCastType(const QualType &QT) {
155  if (QT->isPointerType() || QT->isReferenceType())
156  return false;
157 
158  if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl())
159  return RD->hasAttr<ConsumableAutoCastAttr>();
160 
161  return false;
162 }
163 
164 static bool isSetOnReadPtrType(const QualType &QT) {
165  if (const CXXRecordDecl *RD = QT->getPointeeCXXRecordDecl())
166  return RD->hasAttr<ConsumableSetOnReadAttr>();
167  return false;
168 }
169 
171  switch (State) {
172  case CS_Unconsumed:
173  case CS_Consumed:
174  return true;
175  case CS_None:
176  case CS_Unknown:
177  return false;
178  }
179  llvm_unreachable("invalid enum");
180 }
181 
182 static bool isRValueRef(QualType ParamType) {
183  return ParamType->isRValueReferenceType();
184 }
185 
186 static bool isTestingFunction(const FunctionDecl *FunDecl) {
187  return FunDecl->hasAttr<TestTypestateAttr>();
188 }
189 
190 static bool isPointerOrRef(QualType ParamType) {
191  return ParamType->isPointerType() || ParamType->isReferenceType();
192 }
193 
195  assert(isConsumableType(QT));
196 
197  const ConsumableAttr *CAttr =
198  QT->getAsCXXRecordDecl()->getAttr<ConsumableAttr>();
199 
200  switch (CAttr->getDefaultState()) {
202  return CS_Unknown;
203  case ConsumableAttr::Unconsumed:
204  return CS_Unconsumed;
205  case ConsumableAttr::Consumed:
206  return CS_Consumed;
207  }
208  llvm_unreachable("invalid enum");
209 }
210 
211 static ConsumedState
212 mapParamTypestateAttrState(const ParamTypestateAttr *PTAttr) {
213  switch (PTAttr->getParamState()) {
215  return CS_Unknown;
216  case ParamTypestateAttr::Unconsumed:
217  return CS_Unconsumed;
218  case ParamTypestateAttr::Consumed:
219  return CS_Consumed;
220  }
221  llvm_unreachable("invalid_enum");
222 }
223 
224 static ConsumedState
225 mapReturnTypestateAttrState(const ReturnTypestateAttr *RTSAttr) {
226  switch (RTSAttr->getState()) {
228  return CS_Unknown;
229  case ReturnTypestateAttr::Unconsumed:
230  return CS_Unconsumed;
231  case ReturnTypestateAttr::Consumed:
232  return CS_Consumed;
233  }
234  llvm_unreachable("invalid enum");
235 }
236 
237 static ConsumedState mapSetTypestateAttrState(const SetTypestateAttr *STAttr) {
238  switch (STAttr->getNewState()) {
240  return CS_Unknown;
241  case SetTypestateAttr::Unconsumed:
242  return CS_Unconsumed;
243  case SetTypestateAttr::Consumed:
244  return CS_Consumed;
245  }
246  llvm_unreachable("invalid_enum");
247 }
248 
249 static StringRef stateToString(ConsumedState State) {
250  switch (State) {
251  case consumed::CS_None:
252  return "none";
253 
255  return "unknown";
256 
258  return "unconsumed";
259 
261  return "consumed";
262  }
263  llvm_unreachable("invalid enum");
264 }
265 
266 static ConsumedState testsFor(const FunctionDecl *FunDecl) {
267  assert(isTestingFunction(FunDecl));
268  switch (FunDecl->getAttr<TestTypestateAttr>()->getTestState()) {
269  case TestTypestateAttr::Unconsumed:
270  return CS_Unconsumed;
271  case TestTypestateAttr::Consumed:
272  return CS_Consumed;
273  }
274  llvm_unreachable("invalid enum");
275 }
276 
277 namespace {
278 
279 struct VarTestResult {
280  const VarDecl *Var;
281  ConsumedState TestsFor;
282 };
283 
284 } // namespace
285 
286 namespace clang {
287 namespace consumed {
288 
292 };
293 
295  enum {
296  IT_None,
297  IT_State,
298  IT_VarTest,
299  IT_BinTest,
300  IT_Var,
301  IT_Tmp
302  } InfoType = IT_None;
303 
304  struct BinTestTy {
305  const BinaryOperator *Source;
306  EffectiveOp EOp;
307  VarTestResult LTest;
308  VarTestResult RTest;
309  };
310 
311  union {
313  VarTestResult VarTest;
314  const VarDecl *Var;
316  BinTestTy BinTest;
317  };
318 
319 public:
320  PropagationInfo() = default;
321  PropagationInfo(const VarTestResult &VarTest)
322  : InfoType(IT_VarTest), VarTest(VarTest) {}
323 
324  PropagationInfo(const VarDecl *Var, ConsumedState TestsFor)
325  : InfoType(IT_VarTest) {
326  VarTest.Var = Var;
327  VarTest.TestsFor = TestsFor;
328  }
329 
331  const VarTestResult &LTest, const VarTestResult &RTest)
332  : InfoType(IT_BinTest) {
333  BinTest.Source = Source;
334  BinTest.EOp = EOp;
335  BinTest.LTest = LTest;
336  BinTest.RTest = RTest;
337  }
338 
340  const VarDecl *LVar, ConsumedState LTestsFor,
341  const VarDecl *RVar, ConsumedState RTestsFor)
342  : InfoType(IT_BinTest) {
343  BinTest.Source = Source;
344  BinTest.EOp = EOp;
345  BinTest.LTest.Var = LVar;
346  BinTest.LTest.TestsFor = LTestsFor;
347  BinTest.RTest.Var = RVar;
348  BinTest.RTest.TestsFor = RTestsFor;
349  }
350 
352  : InfoType(IT_State), State(State) {}
353  PropagationInfo(const VarDecl *Var) : InfoType(IT_Var), Var(Var) {}
355  : InfoType(IT_Tmp), Tmp(Tmp) {}
356 
357  const ConsumedState &getState() const {
358  assert(InfoType == IT_State);
359  return State;
360  }
361 
362  const VarTestResult &getVarTest() const {
363  assert(InfoType == IT_VarTest);
364  return VarTest;
365  }
366 
367  const VarTestResult &getLTest() const {
368  assert(InfoType == IT_BinTest);
369  return BinTest.LTest;
370  }
371 
372  const VarTestResult &getRTest() const {
373  assert(InfoType == IT_BinTest);
374  return BinTest.RTest;
375  }
376 
377  const VarDecl *getVar() const {
378  assert(InfoType == IT_Var);
379  return Var;
380  }
381 
382  const CXXBindTemporaryExpr *getTmp() const {
383  assert(InfoType == IT_Tmp);
384  return Tmp;
385  }
386 
387  ConsumedState getAsState(const ConsumedStateMap *StateMap) const {
388  assert(isVar() || isTmp() || isState());
389 
390  if (isVar())
391  return StateMap->getState(Var);
392  else if (isTmp())
393  return StateMap->getState(Tmp);
394  else if (isState())
395  return State;
396  else
397  return CS_None;
398  }
399 
401  assert(InfoType == IT_BinTest);
402  return BinTest.EOp;
403  }
404 
405  const BinaryOperator * testSourceNode() const {
406  assert(InfoType == IT_BinTest);
407  return BinTest.Source;
408  }
409 
410  bool isValid() const { return InfoType != IT_None; }
411  bool isState() const { return InfoType == IT_State; }
412  bool isVarTest() const { return InfoType == IT_VarTest; }
413  bool isBinTest() const { return InfoType == IT_BinTest; }
414  bool isVar() const { return InfoType == IT_Var; }
415  bool isTmp() const { return InfoType == IT_Tmp; }
416 
417  bool isTest() const {
418  return InfoType == IT_VarTest || InfoType == IT_BinTest;
419  }
420 
421  bool isPointerToValue() const {
422  return InfoType == IT_Var || InfoType == IT_Tmp;
423  }
424 
426  assert(InfoType == IT_VarTest || InfoType == IT_BinTest);
427 
428  if (InfoType == IT_VarTest) {
429  return PropagationInfo(VarTest.Var,
430  invertConsumedUnconsumed(VarTest.TestsFor));
431 
432  } else if (InfoType == IT_BinTest) {
433  return PropagationInfo(BinTest.Source,
434  BinTest.EOp == EO_And ? EO_Or : EO_And,
435  BinTest.LTest.Var, invertConsumedUnconsumed(BinTest.LTest.TestsFor),
436  BinTest.RTest.Var, invertConsumedUnconsumed(BinTest.RTest.TestsFor));
437  } else {
438  return {};
439  }
440  }
441 };
442 
443 } // namespace consumed
444 } // namespace clang
445 
446 static void
449  assert(PInfo.isVar() || PInfo.isTmp());
450 
451  if (PInfo.isVar())
452  StateMap->setState(PInfo.getVar(), State);
453  else
454  StateMap->setState(PInfo.getTmp(), State);
455 }
456 
457 namespace clang {
458 namespace consumed {
459 
460 class ConsumedStmtVisitor : public ConstStmtVisitor<ConsumedStmtVisitor> {
461  using MapType = llvm::DenseMap<const Stmt *, PropagationInfo>;
462  using PairType= std::pair<const Stmt *, PropagationInfo>;
463  using InfoEntry = MapType::iterator;
464  using ConstInfoEntry = MapType::const_iterator;
465 
467  ConsumedAnalyzer &Analyzer;
468  ConsumedStateMap *StateMap;
469  MapType PropagationMap;
470 
471  InfoEntry findInfo(const Expr *E) {
472  if (const auto Cleanups = dyn_cast<ExprWithCleanups>(E))
473  if (!Cleanups->cleanupsHaveSideEffects())
474  E = Cleanups->getSubExpr();
475  return PropagationMap.find(E->IgnoreParens());
476  }
477 
478  ConstInfoEntry findInfo(const Expr *E) const {
479  if (const auto Cleanups = dyn_cast<ExprWithCleanups>(E))
480  if (!Cleanups->cleanupsHaveSideEffects())
481  E = Cleanups->getSubExpr();
482  return PropagationMap.find(E->IgnoreParens());
483  }
484 
485  void insertInfo(const Expr *E, const PropagationInfo &PI) {
486  PropagationMap.insert(PairType(E->IgnoreParens(), PI));
487  }
488 
489  void forwardInfo(const Expr *From, const Expr *To);
490  void copyInfo(const Expr *From, const Expr *To, ConsumedState CS);
491  ConsumedState getInfo(const Expr *From);
492  void setInfo(const Expr *To, ConsumedState NS);
493  void propagateReturnType(const Expr *Call, const FunctionDecl *Fun);
494 
495 public:
496  void checkCallability(const PropagationInfo &PInfo,
497  const FunctionDecl *FunDecl,
498  SourceLocation BlameLoc);
499  bool handleCall(const CallExpr *Call, const Expr *ObjArg,
500  const FunctionDecl *FunD);
501 
502  void VisitBinaryOperator(const BinaryOperator *BinOp);
503  void VisitCallExpr(const CallExpr *Call);
504  void VisitCastExpr(const CastExpr *Cast);
505  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Temp);
506  void VisitCXXConstructExpr(const CXXConstructExpr *Call);
507  void VisitCXXMemberCallExpr(const CXXMemberCallExpr *Call);
508  void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *Call);
509  void VisitDeclRefExpr(const DeclRefExpr *DeclRef);
510  void VisitDeclStmt(const DeclStmt *DelcS);
511  void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Temp);
512  void VisitMemberExpr(const MemberExpr *MExpr);
513  void VisitParmVarDecl(const ParmVarDecl *Param);
514  void VisitReturnStmt(const ReturnStmt *Ret);
515  void VisitUnaryOperator(const UnaryOperator *UOp);
516  void VisitVarDecl(const VarDecl *Var);
517 
519  ConsumedStateMap *StateMap)
520  : AC(AC), Analyzer(Analyzer), StateMap(StateMap) {}
521 
522  PropagationInfo getInfo(const Expr *StmtNode) const {
523  ConstInfoEntry Entry = findInfo(StmtNode);
524 
525  if (Entry != PropagationMap.end())
526  return Entry->second;
527  else
528  return {};
529  }
530 
531  void reset(ConsumedStateMap *NewStateMap) {
532  StateMap = NewStateMap;
533  }
534 };
535 
536 } // namespace consumed
537 } // namespace clang
538 
539 void ConsumedStmtVisitor::forwardInfo(const Expr *From, const Expr *To) {
540  InfoEntry Entry = findInfo(From);
541  if (Entry != PropagationMap.end())
542  insertInfo(To, Entry->second);
543 }
544 
545 // Create a new state for To, which is initialized to the state of From.
546 // If NS is not CS_None, sets the state of From to NS.
547 void ConsumedStmtVisitor::copyInfo(const Expr *From, const Expr *To,
548  ConsumedState NS) {
549  InfoEntry Entry = findInfo(From);
550  if (Entry != PropagationMap.end()) {
551  PropagationInfo& PInfo = Entry->second;
552  ConsumedState CS = PInfo.getAsState(StateMap);
553  if (CS != CS_None)
554  insertInfo(To, PropagationInfo(CS));
555  if (NS != CS_None && PInfo.isPointerToValue())
556  setStateForVarOrTmp(StateMap, PInfo, NS);
557  }
558 }
559 
560 // Get the ConsumedState for From
561 ConsumedState ConsumedStmtVisitor::getInfo(const Expr *From) {
562  InfoEntry Entry = findInfo(From);
563  if (Entry != PropagationMap.end()) {
564  PropagationInfo& PInfo = Entry->second;
565  return PInfo.getAsState(StateMap);
566  }
567  return CS_None;
568 }
569 
570 // If we already have info for To then update it, otherwise create a new entry.
571 void ConsumedStmtVisitor::setInfo(const Expr *To, ConsumedState NS) {
572  InfoEntry Entry = findInfo(To);
573  if (Entry != PropagationMap.end()) {
574  PropagationInfo& PInfo = Entry->second;
575  if (PInfo.isPointerToValue())
576  setStateForVarOrTmp(StateMap, PInfo, NS);
577  } else if (NS != CS_None) {
578  insertInfo(To, PropagationInfo(NS));
579  }
580 }
581 
583  const FunctionDecl *FunDecl,
584  SourceLocation BlameLoc) {
585  assert(!PInfo.isTest());
586 
587  const CallableWhenAttr *CWAttr = FunDecl->getAttr<CallableWhenAttr>();
588  if (!CWAttr)
589  return;
590 
591  if (PInfo.isVar()) {
592  ConsumedState VarState = StateMap->getState(PInfo.getVar());
593 
594  if (VarState == CS_None || isCallableInState(CWAttr, VarState))
595  return;
596 
597  Analyzer.WarningsHandler.warnUseInInvalidState(
598  FunDecl->getNameAsString(), PInfo.getVar()->getNameAsString(),
599  stateToString(VarState), BlameLoc);
600  } else {
601  ConsumedState TmpState = PInfo.getAsState(StateMap);
602 
603  if (TmpState == CS_None || isCallableInState(CWAttr, TmpState))
604  return;
605 
606  Analyzer.WarningsHandler.warnUseOfTempInInvalidState(
607  FunDecl->getNameAsString(), stateToString(TmpState), BlameLoc);
608  }
609 }
610 
611 // Factors out common behavior for function, method, and operator calls.
612 // Check parameters and set parameter state if necessary.
613 // Returns true if the state of ObjArg is set, or false otherwise.
614 bool ConsumedStmtVisitor::handleCall(const CallExpr *Call, const Expr *ObjArg,
615  const FunctionDecl *FunD) {
616  unsigned Offset = 0;
617  if (isa<CXXOperatorCallExpr>(Call) && isa<CXXMethodDecl>(FunD))
618  Offset = 1; // first argument is 'this'
619 
620  // check explicit parameters
621  for (unsigned Index = Offset; Index < Call->getNumArgs(); ++Index) {
622  // Skip variable argument lists.
623  if (Index - Offset >= FunD->getNumParams())
624  break;
625 
626  const ParmVarDecl *Param = FunD->getParamDecl(Index - Offset);
627  QualType ParamType = Param->getType();
628 
629  InfoEntry Entry = findInfo(Call->getArg(Index));
630 
631  if (Entry == PropagationMap.end() || Entry->second.isTest())
632  continue;
633  PropagationInfo PInfo = Entry->second;
634 
635  // Check that the parameter is in the correct state.
636  if (ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>()) {
637  ConsumedState ParamState = PInfo.getAsState(StateMap);
638  ConsumedState ExpectedState = mapParamTypestateAttrState(PTA);
639 
640  if (ParamState != ExpectedState)
641  Analyzer.WarningsHandler.warnParamTypestateMismatch(
642  Call->getArg(Index)->getExprLoc(),
643  stateToString(ExpectedState), stateToString(ParamState));
644  }
645 
646  if (!(Entry->second.isVar() || Entry->second.isTmp()))
647  continue;
648 
649  // Adjust state on the caller side.
650  if (isRValueRef(ParamType))
651  setStateForVarOrTmp(StateMap, PInfo, consumed::CS_Consumed);
652  else if (ReturnTypestateAttr *RT = Param->getAttr<ReturnTypestateAttr>())
653  setStateForVarOrTmp(StateMap, PInfo, mapReturnTypestateAttrState(RT));
654  else if (isPointerOrRef(ParamType) &&
655  (!ParamType->getPointeeType().isConstQualified() ||
656  isSetOnReadPtrType(ParamType)))
657  setStateForVarOrTmp(StateMap, PInfo, consumed::CS_Unknown);
658  }
659 
660  if (!ObjArg)
661  return false;
662 
663  // check implicit 'self' parameter, if present
664  InfoEntry Entry = findInfo(ObjArg);
665  if (Entry != PropagationMap.end()) {
666  PropagationInfo PInfo = Entry->second;
667  checkCallability(PInfo, FunD, Call->getExprLoc());
668 
669  if (SetTypestateAttr *STA = FunD->getAttr<SetTypestateAttr>()) {
670  if (PInfo.isVar()) {
671  StateMap->setState(PInfo.getVar(), mapSetTypestateAttrState(STA));
672  return true;
673  }
674  else if (PInfo.isTmp()) {
675  StateMap->setState(PInfo.getTmp(), mapSetTypestateAttrState(STA));
676  return true;
677  }
678  }
679  else if (isTestingFunction(FunD) && PInfo.isVar()) {
680  PropagationMap.insert(PairType(Call,
681  PropagationInfo(PInfo.getVar(), testsFor(FunD))));
682  }
683  }
684  return false;
685 }
686 
687 void ConsumedStmtVisitor::propagateReturnType(const Expr *Call,
688  const FunctionDecl *Fun) {
689  QualType RetType = Fun->getCallResultType();
690  if (RetType->isReferenceType())
691  RetType = RetType->getPointeeType();
692 
693  if (isConsumableType(RetType)) {
694  ConsumedState ReturnState;
695  if (ReturnTypestateAttr *RTA = Fun->getAttr<ReturnTypestateAttr>())
696  ReturnState = mapReturnTypestateAttrState(RTA);
697  else
698  ReturnState = mapConsumableAttrState(RetType);
699 
700  PropagationMap.insert(PairType(Call, PropagationInfo(ReturnState)));
701  }
702 }
703 
705  switch (BinOp->getOpcode()) {
706  case BO_LAnd:
707  case BO_LOr : {
708  InfoEntry LEntry = findInfo(BinOp->getLHS()),
709  REntry = findInfo(BinOp->getRHS());
710 
711  VarTestResult LTest, RTest;
712 
713  if (LEntry != PropagationMap.end() && LEntry->second.isVarTest()) {
714  LTest = LEntry->second.getVarTest();
715  } else {
716  LTest.Var = nullptr;
717  LTest.TestsFor = CS_None;
718  }
719 
720  if (REntry != PropagationMap.end() && REntry->second.isVarTest()) {
721  RTest = REntry->second.getVarTest();
722  } else {
723  RTest.Var = nullptr;
724  RTest.TestsFor = CS_None;
725  }
726 
727  if (!(LTest.Var == nullptr && RTest.Var == nullptr))
728  PropagationMap.insert(PairType(BinOp, PropagationInfo(BinOp,
729  static_cast<EffectiveOp>(BinOp->getOpcode() == BO_LOr), LTest, RTest)));
730  break;
731  }
732 
733  case BO_PtrMemD:
734  case BO_PtrMemI:
735  forwardInfo(BinOp->getLHS(), BinOp);
736  break;
737 
738  default:
739  break;
740  }
741 }
742 
744  const FunctionDecl *FunDecl = Call->getDirectCallee();
745  if (!FunDecl)
746  return;
747 
748  // Special case for the std::move function.
749  // TODO: Make this more specific. (Deferred)
750  if (Call->isCallToStdMove()) {
751  copyInfo(Call->getArg(0), Call, CS_Consumed);
752  return;
753  }
754 
755  handleCall(Call, nullptr, FunDecl);
756  propagateReturnType(Call, FunDecl);
757 }
758 
760  forwardInfo(Cast->getSubExpr(), Cast);
761 }
762 
764  const CXXBindTemporaryExpr *Temp) {
765 
766  InfoEntry Entry = findInfo(Temp->getSubExpr());
767 
768  if (Entry != PropagationMap.end() && !Entry->second.isTest()) {
769  StateMap->setState(Temp, Entry->second.getAsState(StateMap));
770  PropagationMap.insert(PairType(Temp, PropagationInfo(Temp)));
771  }
772 }
773 
775  CXXConstructorDecl *Constructor = Call->getConstructor();
776 
777  ASTContext &CurrContext = AC.getASTContext();
778  QualType ThisType = Constructor->getThisType(CurrContext)->getPointeeType();
779 
780  if (!isConsumableType(ThisType))
781  return;
782 
783  // FIXME: What should happen if someone annotates the move constructor?
784  if (ReturnTypestateAttr *RTA = Constructor->getAttr<ReturnTypestateAttr>()) {
785  // TODO: Adjust state of args appropriately.
787  PropagationMap.insert(PairType(Call, PropagationInfo(RetState)));
788  } else if (Constructor->isDefaultConstructor()) {
789  PropagationMap.insert(PairType(Call,
791  } else if (Constructor->isMoveConstructor()) {
792  copyInfo(Call->getArg(0), Call, CS_Consumed);
793  } else if (Constructor->isCopyConstructor()) {
794  // Copy state from arg. If setStateOnRead then set arg to CS_Unknown.
795  ConsumedState NS =
796  isSetOnReadPtrType(Constructor->getThisType(CurrContext)) ?
798  copyInfo(Call->getArg(0), Call, NS);
799  } else {
800  // TODO: Adjust state of args appropriately.
801  ConsumedState RetState = mapConsumableAttrState(ThisType);
802  PropagationMap.insert(PairType(Call, PropagationInfo(RetState)));
803  }
804 }
805 
807  const CXXMemberCallExpr *Call) {
808  CXXMethodDecl* MD = Call->getMethodDecl();
809  if (!MD)
810  return;
811 
812  handleCall(Call, Call->getImplicitObjectArgument(), MD);
813  propagateReturnType(Call, MD);
814 }
815 
817  const CXXOperatorCallExpr *Call) {
818  const auto *FunDecl = dyn_cast_or_null<FunctionDecl>(Call->getDirectCallee());
819  if (!FunDecl) return;
820 
821  if (Call->getOperator() == OO_Equal) {
822  ConsumedState CS = getInfo(Call->getArg(1));
823  if (!handleCall(Call, Call->getArg(0), FunDecl))
824  setInfo(Call->getArg(0), CS);
825  return;
826  }
827 
828  if (const auto *MCall = dyn_cast<CXXMemberCallExpr>(Call))
829  handleCall(MCall, MCall->getImplicitObjectArgument(), FunDecl);
830  else
831  handleCall(Call, Call->getArg(0), FunDecl);
832 
833  propagateReturnType(Call, FunDecl);
834 }
835 
837  if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclRef->getDecl()))
838  if (StateMap->getState(Var) != consumed::CS_None)
839  PropagationMap.insert(PairType(DeclRef, PropagationInfo(Var)));
840 }
841 
843  for (const auto *DI : DeclS->decls())
844  if (isa<VarDecl>(DI))
845  VisitVarDecl(cast<VarDecl>(DI));
846 
847  if (DeclS->isSingleDecl())
848  if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl()))
849  PropagationMap.insert(PairType(DeclS, PropagationInfo(Var)));
850 }
851 
853  const MaterializeTemporaryExpr *Temp) {
854  forwardInfo(Temp->GetTemporaryExpr(), Temp);
855 }
856 
858  forwardInfo(MExpr->getBase(), MExpr);
859 }
860 
862  QualType ParamType = Param->getType();
863  ConsumedState ParamState = consumed::CS_None;
864 
865  if (const ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>())
866  ParamState = mapParamTypestateAttrState(PTA);
867  else if (isConsumableType(ParamType))
868  ParamState = mapConsumableAttrState(ParamType);
869  else if (isRValueRef(ParamType) &&
870  isConsumableType(ParamType->getPointeeType()))
871  ParamState = mapConsumableAttrState(ParamType->getPointeeType());
872  else if (ParamType->isReferenceType() &&
873  isConsumableType(ParamType->getPointeeType()))
874  ParamState = consumed::CS_Unknown;
875 
876  if (ParamState != CS_None)
877  StateMap->setState(Param, ParamState);
878 }
879 
881  ConsumedState ExpectedState = Analyzer.getExpectedReturnState();
882 
883  if (ExpectedState != CS_None) {
884  InfoEntry Entry = findInfo(Ret->getRetValue());
885 
886  if (Entry != PropagationMap.end()) {
887  ConsumedState RetState = Entry->second.getAsState(StateMap);
888 
889  if (RetState != ExpectedState)
890  Analyzer.WarningsHandler.warnReturnTypestateMismatch(
891  Ret->getReturnLoc(), stateToString(ExpectedState),
892  stateToString(RetState));
893  }
894  }
895 
896  StateMap->checkParamsForReturnTypestate(Ret->getBeginLoc(),
897  Analyzer.WarningsHandler);
898 }
899 
901  InfoEntry Entry = findInfo(UOp->getSubExpr());
902  if (Entry == PropagationMap.end()) return;
903 
904  switch (UOp->getOpcode()) {
905  case UO_AddrOf:
906  PropagationMap.insert(PairType(UOp, Entry->second));
907  break;
908 
909  case UO_LNot:
910  if (Entry->second.isTest())
911  PropagationMap.insert(PairType(UOp, Entry->second.invertTest()));
912  break;
913 
914  default:
915  break;
916  }
917 }
918 
919 // TODO: See if I need to check for reference types here.
921  if (isConsumableType(Var->getType())) {
922  if (Var->hasInit()) {
923  MapType::iterator VIT = findInfo(Var->getInit()->IgnoreImplicit());
924  if (VIT != PropagationMap.end()) {
925  PropagationInfo PInfo = VIT->second;
926  ConsumedState St = PInfo.getAsState(StateMap);
927 
928  if (St != consumed::CS_None) {
929  StateMap->setState(Var, St);
930  return;
931  }
932  }
933  }
934  // Otherwise
935  StateMap->setState(Var, consumed::CS_Unknown);
936  }
937 }
938 
939 static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test,
940  ConsumedStateMap *ThenStates,
941  ConsumedStateMap *ElseStates) {
942  ConsumedState VarState = ThenStates->getState(Test.Var);
943 
944  if (VarState == CS_Unknown) {
945  ThenStates->setState(Test.Var, Test.TestsFor);
946  ElseStates->setState(Test.Var, invertConsumedUnconsumed(Test.TestsFor));
947  } else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) {
948  ThenStates->markUnreachable();
949  } else if (VarState == Test.TestsFor) {
950  ElseStates->markUnreachable();
951  }
952 }
953 
954 static void splitVarStateForIfBinOp(const PropagationInfo &PInfo,
955  ConsumedStateMap *ThenStates,
956  ConsumedStateMap *ElseStates) {
957  const VarTestResult &LTest = PInfo.getLTest(),
958  &RTest = PInfo.getRTest();
959 
960  ConsumedState LState = LTest.Var ? ThenStates->getState(LTest.Var) : CS_None,
961  RState = RTest.Var ? ThenStates->getState(RTest.Var) : CS_None;
962 
963  if (LTest.Var) {
964  if (PInfo.testEffectiveOp() == EO_And) {
965  if (LState == CS_Unknown) {
966  ThenStates->setState(LTest.Var, LTest.TestsFor);
967  } else if (LState == invertConsumedUnconsumed(LTest.TestsFor)) {
968  ThenStates->markUnreachable();
969  } else if (LState == LTest.TestsFor && isKnownState(RState)) {
970  if (RState == RTest.TestsFor)
971  ElseStates->markUnreachable();
972  else
973  ThenStates->markUnreachable();
974  }
975  } else {
976  if (LState == CS_Unknown) {
977  ElseStates->setState(LTest.Var,
978  invertConsumedUnconsumed(LTest.TestsFor));
979  } else if (LState == LTest.TestsFor) {
980  ElseStates->markUnreachable();
981  } else if (LState == invertConsumedUnconsumed(LTest.TestsFor) &&
982  isKnownState(RState)) {
983  if (RState == RTest.TestsFor)
984  ElseStates->markUnreachable();
985  else
986  ThenStates->markUnreachable();
987  }
988  }
989  }
990 
991  if (RTest.Var) {
992  if (PInfo.testEffectiveOp() == EO_And) {
993  if (RState == CS_Unknown)
994  ThenStates->setState(RTest.Var, RTest.TestsFor);
995  else if (RState == invertConsumedUnconsumed(RTest.TestsFor))
996  ThenStates->markUnreachable();
997  } else {
998  if (RState == CS_Unknown)
999  ElseStates->setState(RTest.Var,
1000  invertConsumedUnconsumed(RTest.TestsFor));
1001  else if (RState == RTest.TestsFor)
1002  ElseStates->markUnreachable();
1003  }
1004  }
1005 }
1006 
1008  const CFGBlock *TargetBlock) {
1009  assert(CurrBlock && "Block pointer must not be NULL");
1010  assert(TargetBlock && "TargetBlock pointer must not be NULL");
1011 
1012  unsigned int CurrBlockOrder = VisitOrder[CurrBlock->getBlockID()];
1013  for (CFGBlock::const_pred_iterator PI = TargetBlock->pred_begin(),
1014  PE = TargetBlock->pred_end(); PI != PE; ++PI) {
1015  if (*PI && CurrBlockOrder < VisitOrder[(*PI)->getBlockID()] )
1016  return false;
1017  }
1018  return true;
1019 }
1020 
1022  const CFGBlock *Block, ConsumedStateMap *StateMap,
1023  std::unique_ptr<ConsumedStateMap> &OwnedStateMap) {
1024  assert(Block && "Block pointer must not be NULL");
1025 
1026  auto &Entry = StateMapsArray[Block->getBlockID()];
1027 
1028  if (Entry) {
1029  Entry->intersect(*StateMap);
1030  } else if (OwnedStateMap)
1031  Entry = std::move(OwnedStateMap);
1032  else
1033  Entry = llvm::make_unique<ConsumedStateMap>(*StateMap);
1034 }
1035 
1037  std::unique_ptr<ConsumedStateMap> StateMap) {
1038  assert(Block && "Block pointer must not be NULL");
1039 
1040  auto &Entry = StateMapsArray[Block->getBlockID()];
1041 
1042  if (Entry) {
1043  Entry->intersect(*StateMap);
1044  } else {
1045  Entry = std::move(StateMap);
1046  }
1047 }
1048 
1050  assert(Block && "Block pointer must not be NULL");
1051  assert(StateMapsArray[Block->getBlockID()] && "Block has no block info");
1052 
1053  return StateMapsArray[Block->getBlockID()].get();
1054 }
1055 
1057  StateMapsArray[Block->getBlockID()] = nullptr;
1058 }
1059 
1060 std::unique_ptr<ConsumedStateMap>
1062  assert(Block && "Block pointer must not be NULL");
1063 
1064  auto &Entry = StateMapsArray[Block->getBlockID()];
1065  return isBackEdgeTarget(Block) ? llvm::make_unique<ConsumedStateMap>(*Entry)
1066  : std::move(Entry);
1067 }
1068 
1069 bool ConsumedBlockInfo::isBackEdge(const CFGBlock *From, const CFGBlock *To) {
1070  assert(From && "From block must not be NULL");
1071  assert(To && "From block must not be NULL");
1072 
1073  return VisitOrder[From->getBlockID()] > VisitOrder[To->getBlockID()];
1074 }
1075 
1077  assert(Block && "Block pointer must not be NULL");
1078 
1079  // Anything with less than two predecessors can't be the target of a back
1080  // edge.
1081  if (Block->pred_size() < 2)
1082  return false;
1083 
1084  unsigned int BlockVisitOrder = VisitOrder[Block->getBlockID()];
1085  for (CFGBlock::const_pred_iterator PI = Block->pred_begin(),
1086  PE = Block->pred_end(); PI != PE; ++PI) {
1087  if (*PI && BlockVisitOrder < VisitOrder[(*PI)->getBlockID()])
1088  return true;
1089  }
1090  return false;
1091 }
1092 
1094  ConsumedWarningsHandlerBase &WarningsHandler) const {
1095 
1096  for (const auto &DM : VarMap) {
1097  if (isa<ParmVarDecl>(DM.first)) {
1098  const auto *Param = cast<ParmVarDecl>(DM.first);
1099  const ReturnTypestateAttr *RTA = Param->getAttr<ReturnTypestateAttr>();
1100 
1101  if (!RTA)
1102  continue;
1103 
1104  ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA);
1105  if (DM.second != ExpectedState)
1106  WarningsHandler.warnParamReturnTypestateMismatch(BlameLoc,
1107  Param->getNameAsString(), stateToString(ExpectedState),
1108  stateToString(DM.second));
1109  }
1110  }
1111 }
1112 
1114  TmpMap.clear();
1115 }
1116 
1118  VarMapType::const_iterator Entry = VarMap.find(Var);
1119 
1120  if (Entry != VarMap.end())
1121  return Entry->second;
1122 
1123  return CS_None;
1124 }
1125 
1128  TmpMapType::const_iterator Entry = TmpMap.find(Tmp);
1129 
1130  if (Entry != TmpMap.end())
1131  return Entry->second;
1132 
1133  return CS_None;
1134 }
1135 
1137  ConsumedState LocalState;
1138 
1139  if (this->From && this->From == Other.From && !Other.Reachable) {
1140  this->markUnreachable();
1141  return;
1142  }
1143 
1144  for (const auto &DM : Other.VarMap) {
1145  LocalState = this->getState(DM.first);
1146 
1147  if (LocalState == CS_None)
1148  continue;
1149 
1150  if (LocalState != DM.second)
1151  VarMap[DM.first] = CS_Unknown;
1152  }
1153 }
1154 
1156  const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates,
1157  ConsumedWarningsHandlerBase &WarningsHandler) {
1158 
1159  ConsumedState LocalState;
1160  SourceLocation BlameLoc = getLastStmtLoc(LoopBack);
1161 
1162  for (const auto &DM : LoopBackStates->VarMap) {
1163  LocalState = this->getState(DM.first);
1164 
1165  if (LocalState == CS_None)
1166  continue;
1167 
1168  if (LocalState != DM.second) {
1169  VarMap[DM.first] = CS_Unknown;
1170  WarningsHandler.warnLoopStateMismatch(BlameLoc,
1171  DM.first->getNameAsString());
1172  }
1173  }
1174 }
1175 
1177  this->Reachable = false;
1178  VarMap.clear();
1179  TmpMap.clear();
1180 }
1181 
1183  VarMap[Var] = State;
1184 }
1185 
1187  ConsumedState State) {
1188  TmpMap[Tmp] = State;
1189 }
1190 
1192  TmpMap.erase(Tmp);
1193 }
1194 
1196  for (const auto &DM : Other->VarMap)
1197  if (this->getState(DM.first) != DM.second)
1198  return true;
1199  return false;
1200 }
1201 
1202 void ConsumedAnalyzer::determineExpectedReturnState(AnalysisDeclContext &AC,
1203  const FunctionDecl *D) {
1204  QualType ReturnType;
1205  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1206  ASTContext &CurrContext = AC.getASTContext();
1207  ReturnType = Constructor->getThisType(CurrContext)->getPointeeType();
1208  } else
1209  ReturnType = D->getCallResultType();
1210 
1211  if (const ReturnTypestateAttr *RTSAttr = D->getAttr<ReturnTypestateAttr>()) {
1212  const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1213  if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1214  // FIXME: This should be removed when template instantiation propagates
1215  // attributes at template specialization definition, not
1216  // declaration. When it is removed the test needs to be enabled
1217  // in SemaDeclAttr.cpp.
1218  WarningsHandler.warnReturnTypestateForUnconsumableType(
1219  RTSAttr->getLocation(), ReturnType.getAsString());
1220  ExpectedReturnState = CS_None;
1221  } else
1222  ExpectedReturnState = mapReturnTypestateAttrState(RTSAttr);
1223  } else if (isConsumableType(ReturnType)) {
1224  if (isAutoCastType(ReturnType)) // We can auto-cast the state to the
1225  ExpectedReturnState = CS_None; // expected state.
1226  else
1227  ExpectedReturnState = mapConsumableAttrState(ReturnType);
1228  }
1229  else
1230  ExpectedReturnState = CS_None;
1231 }
1232 
1233 bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock,
1234  const ConsumedStmtVisitor &Visitor) {
1235  std::unique_ptr<ConsumedStateMap> FalseStates(
1236  new ConsumedStateMap(*CurrStates));
1237  PropagationInfo PInfo;
1238 
1239  if (const auto *IfNode =
1240  dyn_cast_or_null<IfStmt>(CurrBlock->getTerminator().getStmt())) {
1241  const Expr *Cond = IfNode->getCond();
1242 
1243  PInfo = Visitor.getInfo(Cond);
1244  if (!PInfo.isValid() && isa<BinaryOperator>(Cond))
1245  PInfo = Visitor.getInfo(cast<BinaryOperator>(Cond)->getRHS());
1246 
1247  if (PInfo.isVarTest()) {
1248  CurrStates->setSource(Cond);
1249  FalseStates->setSource(Cond);
1250  splitVarStateForIf(IfNode, PInfo.getVarTest(), CurrStates.get(),
1251  FalseStates.get());
1252  } else if (PInfo.isBinTest()) {
1253  CurrStates->setSource(PInfo.testSourceNode());
1254  FalseStates->setSource(PInfo.testSourceNode());
1255  splitVarStateForIfBinOp(PInfo, CurrStates.get(), FalseStates.get());
1256  } else {
1257  return false;
1258  }
1259  } else if (const auto *BinOp =
1260  dyn_cast_or_null<BinaryOperator>(CurrBlock->getTerminator().getStmt())) {
1261  PInfo = Visitor.getInfo(BinOp->getLHS());
1262  if (!PInfo.isVarTest()) {
1263  if ((BinOp = dyn_cast_or_null<BinaryOperator>(BinOp->getLHS()))) {
1264  PInfo = Visitor.getInfo(BinOp->getRHS());
1265 
1266  if (!PInfo.isVarTest())
1267  return false;
1268  } else {
1269  return false;
1270  }
1271  }
1272 
1273  CurrStates->setSource(BinOp);
1274  FalseStates->setSource(BinOp);
1275 
1276  const VarTestResult &Test = PInfo.getVarTest();
1277  ConsumedState VarState = CurrStates->getState(Test.Var);
1278 
1279  if (BinOp->getOpcode() == BO_LAnd) {
1280  if (VarState == CS_Unknown)
1281  CurrStates->setState(Test.Var, Test.TestsFor);
1282  else if (VarState == invertConsumedUnconsumed(Test.TestsFor))
1283  CurrStates->markUnreachable();
1284 
1285  } else if (BinOp->getOpcode() == BO_LOr) {
1286  if (VarState == CS_Unknown)
1287  FalseStates->setState(Test.Var,
1288  invertConsumedUnconsumed(Test.TestsFor));
1289  else if (VarState == Test.TestsFor)
1290  FalseStates->markUnreachable();
1291  }
1292  } else {
1293  return false;
1294  }
1295 
1296  CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin();
1297 
1298  if (*SI)
1299  BlockInfo.addInfo(*SI, std::move(CurrStates));
1300  else
1301  CurrStates = nullptr;
1302 
1303  if (*++SI)
1304  BlockInfo.addInfo(*SI, std::move(FalseStates));
1305 
1306  return true;
1307 }
1308 
1310  const auto *D = dyn_cast_or_null<FunctionDecl>(AC.getDecl());
1311  if (!D)
1312  return;
1313 
1314  CFG *CFGraph = AC.getCFG();
1315  if (!CFGraph)
1316  return;
1317 
1318  determineExpectedReturnState(AC, D);
1319 
1320  PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
1321  // AC.getCFG()->viewCFG(LangOptions());
1322 
1323  BlockInfo = ConsumedBlockInfo(CFGraph->getNumBlockIDs(), SortedGraph);
1324 
1325  CurrStates = llvm::make_unique<ConsumedStateMap>();
1326  ConsumedStmtVisitor Visitor(AC, *this, CurrStates.get());
1327 
1328  // Add all trackable parameters to the state map.
1329  for (const auto *PI : D->parameters())
1330  Visitor.VisitParmVarDecl(PI);
1331 
1332  // Visit all of the function's basic blocks.
1333  for (const auto *CurrBlock : *SortedGraph) {
1334  if (!CurrStates)
1335  CurrStates = BlockInfo.getInfo(CurrBlock);
1336 
1337  if (!CurrStates) {
1338  continue;
1339  } else if (!CurrStates->isReachable()) {
1340  CurrStates = nullptr;
1341  continue;
1342  }
1343 
1344  Visitor.reset(CurrStates.get());
1345 
1346  // Visit all of the basic block's statements.
1347  for (const auto &B : *CurrBlock) {
1348  switch (B.getKind()) {
1349  case CFGElement::Statement:
1350  Visitor.Visit(B.castAs<CFGStmt>().getStmt());
1351  break;
1352 
1354  const CFGTemporaryDtor &DTor = B.castAs<CFGTemporaryDtor>();
1355  const CXXBindTemporaryExpr *BTE = DTor.getBindTemporaryExpr();
1356 
1357  Visitor.checkCallability(PropagationInfo(BTE),
1358  DTor.getDestructorDecl(AC.getASTContext()),
1359  BTE->getExprLoc());
1360  CurrStates->remove(BTE);
1361  break;
1362  }
1363 
1365  const CFGAutomaticObjDtor &DTor = B.castAs<CFGAutomaticObjDtor>();
1366  SourceLocation Loc = DTor.getTriggerStmt()->getEndLoc();
1367  const VarDecl *Var = DTor.getVarDecl();
1368 
1369  Visitor.checkCallability(PropagationInfo(Var),
1370  DTor.getDestructorDecl(AC.getASTContext()),
1371  Loc);
1372  break;
1373  }
1374 
1375  default:
1376  break;
1377  }
1378  }
1379 
1380  // TODO: Handle other forms of branching with precision, including while-
1381  // and for-loops. (Deferred)
1382  if (!splitState(CurrBlock, Visitor)) {
1383  CurrStates->setSource(nullptr);
1384 
1385  if (CurrBlock->succ_size() > 1 ||
1386  (CurrBlock->succ_size() == 1 &&
1387  (*CurrBlock->succ_begin())->pred_size() > 1)) {
1388 
1389  auto *RawState = CurrStates.get();
1390 
1391  for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1392  SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1393  if (*SI == nullptr) continue;
1394 
1395  if (BlockInfo.isBackEdge(CurrBlock, *SI)) {
1396  BlockInfo.borrowInfo(*SI)->intersectAtLoopHead(
1397  *SI, CurrBlock, RawState, WarningsHandler);
1398 
1399  if (BlockInfo.allBackEdgesVisited(CurrBlock, *SI))
1400  BlockInfo.discardInfo(*SI);
1401  } else {
1402  BlockInfo.addInfo(*SI, RawState, CurrStates);
1403  }
1404  }
1405 
1406  CurrStates = nullptr;
1407  }
1408  }
1409 
1410  if (CurrBlock == &AC.getCFG()->getExit() &&
1411  D->getCallResultType()->isVoidType())
1412  CurrStates->checkParamsForReturnTypestate(D->getLocation(),
1413  WarningsHandler);
1414  } // End of block iterator.
1415 
1416  // Delete the last existing state map.
1417  CurrStates = nullptr;
1418 
1419  WarningsHandler.emitDiagnostics();
1420 }
void VisitDeclStmt(const DeclStmt *DelcS)
Definition: Consumed.cpp:842
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
bool isCallToStdMove() const
Definition: Expr.h:2518
Represents a function declaration or definition.
Definition: Decl.h:1732
const ConsumedState & getState() const
Definition: Consumed.cpp:357
SourceLocation getBeginLoc() const
Definition: Stmt.h:2067
pred_iterator pred_end()
Definition: CFG.h:734
A (possibly-)qualified type.
Definition: Type.h:642
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2441
AdjacentBlocks::const_iterator const_pred_iterator
Definition: CFG.h:720
const Stmt * getStmt() const
Definition: CFG.h:133
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
succ_iterator succ_begin()
Definition: CFG.h:751
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2429
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1252
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:497
C Language Family Type Representation.
Expr * getBase() const
Definition: Expr.h:2644
unsigned getBlockID() const
Definition: CFG.h:856
Expr * getImplicitObjectArgument() const
Retrieves the implicit object argument for the member call.
Definition: ExprCXX.cpp:505
virtual void warnParamReturnTypestateMismatch(SourceLocation Loc, StringRef VariableName, StringRef ExpectedState, StringRef ObservedState)
Warn about parameter typestate mismatches upon return.
Definition: Consumed.h:83
Opcode getOpcode() const
Definition: Expr.h:3234
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2312
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
Definition: CFG.h:99
bool isBackEdge(const CFGBlock *From, const CFGBlock *To)
Definition: Consumed.cpp:1069
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2478
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4068
static ConsumedState testsFor(const FunctionDecl *FunDecl)
Definition: Consumed.cpp:266
unsigned succ_size() const
Definition: CFG.h:769
const CXXDestructorDecl * getDestructorDecl(ASTContext &astContext) const
Definition: CFG.cpp:4667
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2346
void VisitBinaryOperator(const BinaryOperator *BinOp)
Definition: Consumed.cpp:704
Represents a variable declaration or definition.
Definition: Decl.h:812
ASTContext & getASTContext() const
static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test, ConsumedStateMap *ThenStates, ConsumedStateMap *ElseStates)
Definition: Consumed.cpp:939
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:746
const CXXBindTemporaryExpr * getTmp() const
Definition: Consumed.cpp:382
const Stmt * getTriggerStmt() const
Definition: CFG.h:394
void VisitParmVarDecl(const ParmVarDecl *Param)
Definition: Consumed.cpp:861
Represents a parameter to a function.
Definition: Decl.h:1551
Defines the clang::Expr interface and subclasses for C++ expressions.
PropagationInfo(const VarTestResult &VarTest)
Definition: Consumed.cpp:321
PropagationInfo(const VarDecl *Var)
Definition: Consumed.cpp:353
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4109
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
LineState State
ConsumedStmtVisitor(AnalysisDeclContext &AC, ConsumedAnalyzer &Analyzer, ConsumedStateMap *StateMap)
Definition: Consumed.cpp:518
ConsumedState getState(const VarDecl *Var) const
Get the consumed state of a given variable.
Definition: Consumed.cpp:1117
AnalysisDeclContext contains the context data for the function or method under analysis.
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:384
const BinaryOperator * testSourceNode() const
Definition: Consumed.cpp:405
const VarTestResult & getRTest() const
Definition: Consumed.cpp:372
bool isReferenceType() const
Definition: Type.h:6294
PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp, const VarDecl *LVar, ConsumedState LTestsFor, const VarDecl *RVar, ConsumedState RTestsFor)
Definition: Consumed.cpp:339
PropagationInfo(const CXXBindTemporaryExpr *Tmp)
Definition: Consumed.cpp:354
static ConsumedState mapReturnTypestateAttrState(const ReturnTypestateAttr *RTSAttr)
Definition: Consumed.cpp:225
Expr * getSubExpr()
Definition: Expr.h:2942
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2250
AdjacentBlocks::const_iterator const_succ_iterator
Definition: CFG.h:727
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:2176
EffectiveOp testEffectiveOp() const
Definition: Consumed.cpp:400
bool operator!=(const ConsumedStateMap *Other) const
Tests to see if there is a mismatch in the states stored in two maps.
Definition: Consumed.cpp:1195
uint32_t Offset
Definition: CacheTokens.cpp:43
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
void intersectAtLoopHead(const CFGBlock *LoopHead, const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates, ConsumedWarningsHandlerBase &WarningsHandler)
Definition: Consumed.cpp:1155
const CXXBindTemporaryExpr * Tmp
Definition: Consumed.cpp:315
const VarTestResult & getVarTest() const
Definition: Consumed.cpp:362
T * getAnalysis()
Return the specified analysis object, lazily running the analysis if necessary.
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3193
bool isRValueReferenceType() const
Definition: Type.h:6302
const VarDecl * getVarDecl() const
Definition: CFG.h:389
bool isBackEdgeTarget(const CFGBlock *Block)
Definition: Consumed.cpp:1076
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2877
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1217
void VisitCXXMemberCallExpr(const CXXMemberCallExpr *Call)
Definition: Consumed.cpp:806
reverse_iterator rend()
Definition: CFG.h:709
static void splitVarStateForIfBinOp(const PropagationInfo &PInfo, ConsumedStateMap *ThenStates, ConsumedStateMap *ElseStates)
Definition: Consumed.cpp:954
static bool isConsumableType(const QualType &QT)
Definition: Consumed.cpp:144
void remove(const CXXBindTemporaryExpr *Tmp)
Remove the temporary value from our state map.
Definition: Consumed.cpp:1191
bool hasAttr() const
Definition: DeclBase.h:531
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1605
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1325
const CXXBindTemporaryExpr * getBindTemporaryExpr() const
Definition: CFG.h:482
Represents a single basic block in a source-level CFG.
Definition: CFG.h:552
virtual void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName)
Warn that a variable&#39;s state doesn&#39;t match at the entry and exit of a loop.
Definition: Consumed.h:71
static bool isPointerOrRef(QualType ParamType)
Definition: Consumed.cpp:190
This represents one expression.
Definition: Expr.h:106
static StringRef stateToString(ConsumedState State)
Definition: Consumed.cpp:249
void discardInfo(const CFGBlock *Block)
Definition: Consumed.cpp:1056
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
Definition: CFG.h:1003
std::unique_ptr< ConsumedStateMap > getInfo(const CFGBlock *Block)
Definition: Consumed.cpp:1061
void VisitMemberExpr(const MemberExpr *MExpr)
Definition: Consumed.cpp:857
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to...
Definition: Type.cpp:1590
const VarDecl * getVar() const
Definition: Consumed.cpp:377
Defines an enumeration for C++ overloaded operators.
bool allBackEdgesVisited(const CFGBlock *CurrBlock, const CFGBlock *TargetBlock)
Definition: Consumed.cpp:1007
void setState(const VarDecl *Var, ConsumedState State)
Set the consumed state of a given variable.
Definition: Consumed.cpp:1182
void VisitCastExpr(const CastExpr *Cast)
Definition: Consumed.cpp:759
PropagationInfo(ConsumedState State)
Definition: Consumed.cpp:351
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2008
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1871
CXXMethodDecl * getMethodDecl() const
Retrieves the declaration of the called method.
Definition: ExprCXX.cpp:517
void VisitReturnStmt(const ReturnStmt *Ret)
Definition: Consumed.cpp:880
ValueDecl * getDecl()
Definition: Expr.h:1119
const Expr * getSubExpr() const
Definition: ExprCXX.h:1240
reverse_iterator rbegin()
Definition: CFG.h:708
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:293
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6117
void addInfo(const CFGBlock *Block, ConsumedStateMap *StateMap, std::unique_ptr< ConsumedStateMap > &OwnedStateMap)
Definition: Consumed.cpp:1021
static ConsumedState mapConsumableAttrState(const QualType QT)
Definition: Consumed.cpp:194
static void setStateForVarOrTmp(ConsumedStateMap *StateMap, const PropagationInfo &PInfo, ConsumedState State)
Definition: Consumed.cpp:447
PropagationInfo invertTest() const
Definition: Consumed.cpp:425
CFGTerminator getTerminator()
Definition: CFG.h:840
void checkParamsForReturnTypestate(SourceLocation BlameLoc, ConsumedWarningsHandlerBase &WarningsHandler) const
Warn if any of the parameters being tracked are not in the state they were declared to be in upon ret...
Definition: Consumed.cpp:1093
Encodes a location in the source.
Expr * getRetValue()
Definition: Stmt.h:2041
Expr * getSubExpr() const
Definition: Expr.h:1898
void VisitDeclRefExpr(const DeclRefExpr *DeclRef)
Definition: Consumed.cpp:836
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:291
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:164
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:708
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
static bool isTestingFunction(const FunctionDecl *FunDecl)
Definition: Consumed.cpp:186
static bool isKnownState(ConsumedState State)
Definition: Consumed.cpp:170
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2273
PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp, const VarTestResult &LTest, const VarTestResult &RTest)
Definition: Consumed.cpp:330
const Decl * getDecl() const
void VisitUnaryOperator(const UnaryOperator *UOp)
Definition: Consumed.cpp:900
static bool isSetOnReadPtrType(const QualType &QT)
Definition: Consumed.cpp:164
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Definition: CFG.h:1169
const VarTestResult & getLTest() const
Definition: Consumed.cpp:367
void intersect(const ConsumedStateMap &Other)
Merge this state map with another map.
Definition: Consumed.cpp:1136
void VisitVarDecl(const VarDecl *Var)
Definition: Consumed.cpp:920
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
Expr * getLHS() const
Definition: Expr.h:3237
void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *Call)
Definition: Consumed.cpp:816
pred_iterator pred_begin()
Definition: CFG.h:733
void checkCallability(const PropagationInfo &PInfo, const FunctionDecl *FunDecl, SourceLocation BlameLoc)
Definition: Consumed.cpp:582
void reset(ConsumedStateMap *NewStateMap)
Definition: Consumed.cpp:531
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
void clearTemporaries()
Clear the TmpMap.
Definition: Consumed.cpp:1113
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:106
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1277
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Temp)
Definition: Consumed.cpp:852
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2355
const Expr * getInit() const
Definition: Decl.h:1219
unsigned pred_size() const
Definition: CFG.h:772
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:975
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition: DeclCXX.cpp:2360
const Decl * getSingleDecl() const
Definition: Stmt.h:723
A class that handles the analysis of uniqueness violations.
Definition: Consumed.h:241
ConsumedStateMap * borrowInfo(const CFGBlock *Block)
Definition: Consumed.cpp:1049
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl. ...
Definition: Stmt.h:721
Stmt * getStmt()
Definition: CFG.h:510
static bool isRValueRef(QualType ParamType)
Definition: Consumed.cpp:182
void markUnreachable()
Mark the block as unreachable.
Definition: Consumed.cpp:1176
static const TypeInfo & getInfo(unsigned id)
Definition: Types.cpp:34
PropagationInfo getInfo(const Expr *StmtNode) const
Definition: Consumed.cpp:522
T * getAttr() const
Definition: DeclBase.h:527
PropagationInfo(const VarDecl *Var, ConsumedState TestsFor)
Definition: Consumed.cpp:324
Opcode getOpcode() const
Definition: Expr.h:1895
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1388
void VisitCallExpr(const CallExpr *Call)
Definition: Consumed.cpp:743
decl_range decls()
Definition: Stmt.h:751
ConsumedState getAsState(const ConsumedStateMap *StateMap) const
Definition: Consumed.cpp:387
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
static SourceLocation getFirstStmtLoc(const CFGBlock *Block)
Definition: Consumed.cpp:62
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2554
Defines the clang::SourceLocation class and associated facilities.
void VisitCXXConstructExpr(const CXXConstructExpr *Call)
Definition: Consumed.cpp:774
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool handleCall(const CallExpr *Call, const Expr *ObjArg, const FunctionDecl *FunD)
Definition: Consumed.cpp:614
bool isVoidType() const
Definition: Type.h:6530
static bool isAutoCastType(const QualType &QT)
Definition: Consumed.cpp:154
void run(AnalysisDeclContext &AC)
Check a function&#39;s CFG for consumed violations.
Definition: Consumed.cpp:1309
Represents a top-level expression in a basic block.
Definition: CFG.h:56
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2372
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition: StmtVisitor.h:46
static ConsumedState mapParamTypestateAttrState(const ParamTypestateAttr *PTAttr)
Definition: Consumed.cpp:212
static bool isCallableInState(const CallableWhenAttr *CWAttr, ConsumedState State)
Definition: Consumed.cpp:118
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1036
Expr * getRHS() const
Definition: Expr.h:3239
bool isPointerType() const
Definition: Type.h:6282
static SourceLocation getLastStmtLoc(const CFGBlock *Block)
Definition: Consumed.cpp:77
QualType getType() const
Definition: Decl.h:647
static ConsumedState mapSetTypestateAttrState(const SetTypestateAttr *STAttr)
Definition: Consumed.cpp:237
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3042
bool hasInit() const
Definition: Decl.cpp:2164
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition: CFG.h:477
SourceLocation getReturnLoc() const
Definition: Stmt.h:2064
SourceLocation getLocation() const
Definition: DeclBase.h:418
static ConsumedState invertConsumedUnconsumed(ConsumedState State)
Definition: Consumed.cpp:104
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2540
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Temp)
Definition: Consumed.cpp:763
CFGBlock & getExit()
Definition: CFG.h:1095