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