1 //===- Consumed.cpp --------------------------------------------*- C++ --*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // A intra-procedural analysis for checking consumed properties. This is based,
11 // in part, on research on linear types.
13 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Analysis/Analyses/Consumed.h"
24 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
25 #include "clang/Analysis/AnalysisContext.h"
26 #include "clang/Analysis/CFG.h"
27 #include "clang/Basic/OperatorKinds.h"
28 #include "clang/Basic/SourceLocation.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"
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
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.
48 // TODO: Test nested conditionals: A) Checking the same value multiple times,
49 // and 2) Checking different values. (Deferred)
51 using namespace clang;
52 using namespace consumed;
54 // Key method definition
55 ConsumedWarningsHandlerBase::~ConsumedWarningsHandlerBase() {}
57 static SourceLocation getFirstStmtLoc(const CFGBlock *Block) {
58 // Find the source location of the first statement in the block, if the block
60 for (const auto &B : *Block)
61 if (Optional<CFGStmt> CS = B.getAs<CFGStmt>())
62 return CS->getStmt()->getLocStart();
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());
69 return SourceLocation();
72 static SourceLocation getLastStmtLoc(const CFGBlock *Block) {
73 // Find the source location of the last statement in the block, if the block
75 if (const Stmt *StmtNode = Block->getTerminator()) {
76 return StmtNode->getLocStart();
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();
85 // If we have one successor, return the first statement in that block
87 if (Block->succ_size() == 1 && *Block->succ_begin())
88 Loc = getFirstStmtLoc(*Block->succ_begin());
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());
99 static ConsumedState invertConsumedUnconsumed(ConsumedState State) {
104 return CS_Unconsumed;
110 llvm_unreachable("invalid enum");
113 static bool isCallableInState(const CallableWhenAttr *CWAttr,
114 ConsumedState State) {
116 for (const auto &S : CWAttr->callableStates()) {
117 ConsumedState MappedAttrState = CS_None;
120 case CallableWhenAttr::Unknown:
121 MappedAttrState = CS_Unknown;
124 case CallableWhenAttr::Unconsumed:
125 MappedAttrState = CS_Unconsumed;
128 case CallableWhenAttr::Consumed:
129 MappedAttrState = CS_Consumed;
133 if (MappedAttrState == State)
141 static bool isConsumableType(const QualType &QT) {
142 if (QT->isPointerType() || QT->isReferenceType())
145 if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl())
146 return RD->hasAttr<ConsumableAttr>();
151 static bool isAutoCastType(const QualType &QT) {
152 if (QT->isPointerType() || QT->isReferenceType())
155 if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl())
156 return RD->hasAttr<ConsumableAutoCastAttr>();
161 static bool isSetOnReadPtrType(const QualType &QT) {
162 if (const CXXRecordDecl *RD = QT->getPointeeCXXRecordDecl())
163 return RD->hasAttr<ConsumableSetOnReadAttr>();
168 static bool isKnownState(ConsumedState State) {
177 llvm_unreachable("invalid enum");
180 static bool isRValueRef(QualType ParamType) {
181 return ParamType->isRValueReferenceType();
184 static bool isTestingFunction(const FunctionDecl *FunDecl) {
185 return FunDecl->hasAttr<TestTypestateAttr>();
188 static bool isPointerOrRef(QualType ParamType) {
189 return ParamType->isPointerType() || ParamType->isReferenceType();
192 static ConsumedState mapConsumableAttrState(const QualType QT) {
193 assert(isConsumableType(QT));
195 const ConsumableAttr *CAttr =
196 QT->getAsCXXRecordDecl()->getAttr<ConsumableAttr>();
198 switch (CAttr->getDefaultState()) {
199 case ConsumableAttr::Unknown:
201 case ConsumableAttr::Unconsumed:
202 return CS_Unconsumed;
203 case ConsumableAttr::Consumed:
206 llvm_unreachable("invalid enum");
210 mapParamTypestateAttrState(const ParamTypestateAttr *PTAttr) {
211 switch (PTAttr->getParamState()) {
212 case ParamTypestateAttr::Unknown:
214 case ParamTypestateAttr::Unconsumed:
215 return CS_Unconsumed;
216 case ParamTypestateAttr::Consumed:
219 llvm_unreachable("invalid_enum");
223 mapReturnTypestateAttrState(const ReturnTypestateAttr *RTSAttr) {
224 switch (RTSAttr->getState()) {
225 case ReturnTypestateAttr::Unknown:
227 case ReturnTypestateAttr::Unconsumed:
228 return CS_Unconsumed;
229 case ReturnTypestateAttr::Consumed:
232 llvm_unreachable("invalid enum");
235 static ConsumedState mapSetTypestateAttrState(const SetTypestateAttr *STAttr) {
236 switch (STAttr->getNewState()) {
237 case SetTypestateAttr::Unknown:
239 case SetTypestateAttr::Unconsumed:
240 return CS_Unconsumed;
241 case SetTypestateAttr::Consumed:
244 llvm_unreachable("invalid_enum");
247 static StringRef stateToString(ConsumedState State) {
249 case consumed::CS_None:
252 case consumed::CS_Unknown:
255 case consumed::CS_Unconsumed:
258 case consumed::CS_Consumed:
261 llvm_unreachable("invalid enum");
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:
272 llvm_unreachable("invalid enum");
276 struct VarTestResult {
278 ConsumedState TestsFor;
280 } // end anonymous::VarTestResult
290 class PropagationInfo {
301 const BinaryOperator *Source;
309 VarTestResult VarTest;
311 const CXXBindTemporaryExpr *Tmp;
316 PropagationInfo() : InfoType(IT_None) {}
318 PropagationInfo(const VarTestResult &VarTest)
319 : InfoType(IT_VarTest), VarTest(VarTest) {}
321 PropagationInfo(const VarDecl *Var, ConsumedState TestsFor)
322 : InfoType(IT_VarTest) {
325 VarTest.TestsFor = TestsFor;
328 PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp,
329 const VarTestResult <est, const VarTestResult &RTest)
330 : InfoType(IT_BinTest) {
332 BinTest.Source = Source;
334 BinTest.LTest = LTest;
335 BinTest.RTest = RTest;
338 PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp,
339 const VarDecl *LVar, ConsumedState LTestsFor,
340 const VarDecl *RVar, ConsumedState RTestsFor)
341 : InfoType(IT_BinTest) {
343 BinTest.Source = Source;
345 BinTest.LTest.Var = LVar;
346 BinTest.LTest.TestsFor = LTestsFor;
347 BinTest.RTest.Var = RVar;
348 BinTest.RTest.TestsFor = RTestsFor;
351 PropagationInfo(ConsumedState State)
352 : InfoType(IT_State), State(State) {}
354 PropagationInfo(const VarDecl *Var) : InfoType(IT_Var), Var(Var) {}
355 PropagationInfo(const CXXBindTemporaryExpr *Tmp)
356 : InfoType(IT_Tmp), Tmp(Tmp) {}
358 const ConsumedState & getState() const {
359 assert(InfoType == IT_State);
363 const VarTestResult & getVarTest() const {
364 assert(InfoType == IT_VarTest);
368 const VarTestResult & getLTest() const {
369 assert(InfoType == IT_BinTest);
370 return BinTest.LTest;
373 const VarTestResult & getRTest() const {
374 assert(InfoType == IT_BinTest);
375 return BinTest.RTest;
378 const VarDecl * getVar() const {
379 assert(InfoType == IT_Var);
383 const CXXBindTemporaryExpr * getTmp() const {
384 assert(InfoType == IT_Tmp);
388 ConsumedState getAsState(const ConsumedStateMap *StateMap) const {
389 assert(isVar() || isTmp() || isState());
392 return StateMap->getState(Var);
394 return StateMap->getState(Tmp);
401 EffectiveOp testEffectiveOp() const {
402 assert(InfoType == IT_BinTest);
406 const BinaryOperator * testSourceNode() const {
407 assert(InfoType == IT_BinTest);
408 return BinTest.Source;
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; }
418 bool isTest() const {
419 return InfoType == IT_VarTest || InfoType == IT_BinTest;
422 bool isPointerToValue() const {
423 return InfoType == IT_Var || InfoType == IT_Tmp;
426 PropagationInfo invertTest() const {
427 assert(InfoType == IT_VarTest || InfoType == IT_BinTest);
429 if (InfoType == IT_VarTest) {
430 return PropagationInfo(VarTest.Var,
431 invertConsumedUnconsumed(VarTest.TestsFor));
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));
439 return PropagationInfo();
445 setStateForVarOrTmp(ConsumedStateMap *StateMap, const PropagationInfo &PInfo,
446 ConsumedState State) {
448 assert(PInfo.isVar() || PInfo.isTmp());
451 StateMap->setState(PInfo.getVar(), State);
453 StateMap->setState(PInfo.getTmp(), State);
456 class ConsumedStmtVisitor : public ConstStmtVisitor<ConsumedStmtVisitor> {
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;
463 AnalysisDeclContext &AC;
464 ConsumedAnalyzer &Analyzer;
465 ConsumedStateMap *StateMap;
466 MapType PropagationMap;
468 InfoEntry findInfo(const Expr *E) {
469 if (auto Cleanups = dyn_cast<ExprWithCleanups>(E))
470 if (!Cleanups->cleanupsHaveSideEffects())
471 E = Cleanups->getSubExpr();
472 return PropagationMap.find(E->IgnoreParens());
474 ConstInfoEntry findInfo(const Expr *E) const {
475 if (auto Cleanups = dyn_cast<ExprWithCleanups>(E))
476 if (!Cleanups->cleanupsHaveSideEffects())
477 E = Cleanups->getSubExpr();
478 return PropagationMap.find(E->IgnoreParens());
480 void insertInfo(const Expr *E, const PropagationInfo &PI) {
481 PropagationMap.insert(PairType(E->IgnoreParens(), PI));
484 void forwardInfo(const Expr *From, const Expr *To);
485 void copyInfo(const Expr *From, const Expr *To, ConsumedState CS);
486 ConsumedState getInfo(const Expr *From);
487 void setInfo(const Expr *To, ConsumedState NS);
488 void propagateReturnType(const Expr *Call, const FunctionDecl *Fun);
491 void checkCallability(const PropagationInfo &PInfo,
492 const FunctionDecl *FunDecl,
493 SourceLocation BlameLoc);
494 bool handleCall(const CallExpr *Call, const Expr *ObjArg,
495 const FunctionDecl *FunD);
497 void VisitBinaryOperator(const BinaryOperator *BinOp);
498 void VisitCallExpr(const CallExpr *Call);
499 void VisitCastExpr(const CastExpr *Cast);
500 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Temp);
501 void VisitCXXConstructExpr(const CXXConstructExpr *Call);
502 void VisitCXXMemberCallExpr(const CXXMemberCallExpr *Call);
503 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *Call);
504 void VisitDeclRefExpr(const DeclRefExpr *DeclRef);
505 void VisitDeclStmt(const DeclStmt *DelcS);
506 void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Temp);
507 void VisitMemberExpr(const MemberExpr *MExpr);
508 void VisitParmVarDecl(const ParmVarDecl *Param);
509 void VisitReturnStmt(const ReturnStmt *Ret);
510 void VisitUnaryOperator(const UnaryOperator *UOp);
511 void VisitVarDecl(const VarDecl *Var);
513 ConsumedStmtVisitor(AnalysisDeclContext &AC, ConsumedAnalyzer &Analyzer,
514 ConsumedStateMap *StateMap)
515 : AC(AC), Analyzer(Analyzer), StateMap(StateMap) {}
517 PropagationInfo getInfo(const Expr *StmtNode) const {
518 ConstInfoEntry Entry = findInfo(StmtNode);
520 if (Entry != PropagationMap.end())
521 return Entry->second;
523 return PropagationInfo();
526 void reset(ConsumedStateMap *NewStateMap) {
527 StateMap = NewStateMap;
532 void ConsumedStmtVisitor::forwardInfo(const Expr *From, const Expr *To) {
533 InfoEntry Entry = findInfo(From);
534 if (Entry != PropagationMap.end())
535 insertInfo(To, Entry->second);
539 // Create a new state for To, which is initialized to the state of From.
540 // If NS is not CS_None, sets the state of From to NS.
541 void ConsumedStmtVisitor::copyInfo(const Expr *From, const Expr *To,
543 InfoEntry Entry = findInfo(From);
544 if (Entry != PropagationMap.end()) {
545 PropagationInfo& PInfo = Entry->second;
546 ConsumedState CS = PInfo.getAsState(StateMap);
548 insertInfo(To, PropagationInfo(CS));
549 if (NS != CS_None && PInfo.isPointerToValue())
550 setStateForVarOrTmp(StateMap, PInfo, NS);
555 // Get the ConsumedState for From
556 ConsumedState ConsumedStmtVisitor::getInfo(const Expr *From) {
557 InfoEntry Entry = findInfo(From);
558 if (Entry != PropagationMap.end()) {
559 PropagationInfo& PInfo = Entry->second;
560 return PInfo.getAsState(StateMap);
566 // If we already have info for To then update it, otherwise create a new entry.
567 void ConsumedStmtVisitor::setInfo(const Expr *To, ConsumedState NS) {
568 InfoEntry Entry = findInfo(To);
569 if (Entry != PropagationMap.end()) {
570 PropagationInfo& PInfo = Entry->second;
571 if (PInfo.isPointerToValue())
572 setStateForVarOrTmp(StateMap, PInfo, NS);
573 } else if (NS != CS_None) {
574 insertInfo(To, PropagationInfo(NS));
580 void ConsumedStmtVisitor::checkCallability(const PropagationInfo &PInfo,
581 const FunctionDecl *FunDecl,
582 SourceLocation BlameLoc) {
583 assert(!PInfo.isTest());
585 const CallableWhenAttr *CWAttr = FunDecl->getAttr<CallableWhenAttr>();
590 ConsumedState VarState = StateMap->getState(PInfo.getVar());
592 if (VarState == CS_None || isCallableInState(CWAttr, VarState))
595 Analyzer.WarningsHandler.warnUseInInvalidState(
596 FunDecl->getNameAsString(), PInfo.getVar()->getNameAsString(),
597 stateToString(VarState), BlameLoc);
600 ConsumedState TmpState = PInfo.getAsState(StateMap);
602 if (TmpState == CS_None || isCallableInState(CWAttr, TmpState))
605 Analyzer.WarningsHandler.warnUseOfTempInInvalidState(
606 FunDecl->getNameAsString(), stateToString(TmpState), BlameLoc);
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) {
617 if (isa<CXXOperatorCallExpr>(Call) && isa<CXXMethodDecl>(FunD))
618 Offset = 1; // first argument is 'this'
620 // check explicit parameters
621 for (unsigned Index = Offset; Index < Call->getNumArgs(); ++Index) {
622 // Skip variable argument lists.
623 if (Index - Offset >= FunD->getNumParams())
626 const ParmVarDecl *Param = FunD->getParamDecl(Index - Offset);
627 QualType ParamType = Param->getType();
629 InfoEntry Entry = findInfo(Call->getArg(Index));
631 if (Entry == PropagationMap.end() || Entry->second.isTest())
633 PropagationInfo PInfo = Entry->second;
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);
640 if (ParamState != ExpectedState)
641 Analyzer.WarningsHandler.warnParamTypestateMismatch(
642 Call->getArg(Index)->getExprLoc(),
643 stateToString(ExpectedState), stateToString(ParamState));
646 if (!(Entry->second.isVar() || Entry->second.isTmp()))
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);
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());
669 if (SetTypestateAttr *STA = FunD->getAttr<SetTypestateAttr>()) {
671 StateMap->setState(PInfo.getVar(), mapSetTypestateAttrState(STA));
674 else if (PInfo.isTmp()) {
675 StateMap->setState(PInfo.getTmp(), mapSetTypestateAttrState(STA));
679 else if (isTestingFunction(FunD) && PInfo.isVar()) {
680 PropagationMap.insert(PairType(Call,
681 PropagationInfo(PInfo.getVar(), testsFor(FunD))));
688 void ConsumedStmtVisitor::propagateReturnType(const Expr *Call,
689 const FunctionDecl *Fun) {
690 QualType RetType = Fun->getCallResultType();
691 if (RetType->isReferenceType())
692 RetType = RetType->getPointeeType();
694 if (isConsumableType(RetType)) {
695 ConsumedState ReturnState;
696 if (ReturnTypestateAttr *RTA = Fun->getAttr<ReturnTypestateAttr>())
697 ReturnState = mapReturnTypestateAttrState(RTA);
699 ReturnState = mapConsumableAttrState(RetType);
701 PropagationMap.insert(PairType(Call, PropagationInfo(ReturnState)));
706 void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) {
707 switch (BinOp->getOpcode()) {
710 InfoEntry LEntry = findInfo(BinOp->getLHS()),
711 REntry = findInfo(BinOp->getRHS());
713 VarTestResult LTest, RTest;
715 if (LEntry != PropagationMap.end() && LEntry->second.isVarTest()) {
716 LTest = LEntry->second.getVarTest();
720 LTest.TestsFor = CS_None;
723 if (REntry != PropagationMap.end() && REntry->second.isVarTest()) {
724 RTest = REntry->second.getVarTest();
728 RTest.TestsFor = CS_None;
731 if (!(LTest.Var == nullptr && RTest.Var == nullptr))
732 PropagationMap.insert(PairType(BinOp, PropagationInfo(BinOp,
733 static_cast<EffectiveOp>(BinOp->getOpcode() == BO_LOr), LTest, RTest)));
740 forwardInfo(BinOp->getLHS(), BinOp);
748 void ConsumedStmtVisitor::VisitCallExpr(const CallExpr *Call) {
749 const FunctionDecl *FunDecl = Call->getDirectCallee();
753 // Special case for the std::move function.
754 // TODO: Make this more specific. (Deferred)
755 if (Call->getNumArgs() == 1 && FunDecl->getNameAsString() == "move" &&
756 FunDecl->isInStdNamespace()) {
757 copyInfo(Call->getArg(0), Call, CS_Consumed);
761 handleCall(Call, nullptr, FunDecl);
762 propagateReturnType(Call, FunDecl);
765 void ConsumedStmtVisitor::VisitCastExpr(const CastExpr *Cast) {
766 forwardInfo(Cast->getSubExpr(), Cast);
769 void ConsumedStmtVisitor::VisitCXXBindTemporaryExpr(
770 const CXXBindTemporaryExpr *Temp) {
772 InfoEntry Entry = findInfo(Temp->getSubExpr());
774 if (Entry != PropagationMap.end() && !Entry->second.isTest()) {
775 StateMap->setState(Temp, Entry->second.getAsState(StateMap));
776 PropagationMap.insert(PairType(Temp, PropagationInfo(Temp)));
780 void ConsumedStmtVisitor::VisitCXXConstructExpr(const CXXConstructExpr *Call) {
781 CXXConstructorDecl *Constructor = Call->getConstructor();
783 ASTContext &CurrContext = AC.getASTContext();
784 QualType ThisType = Constructor->getThisType(CurrContext)->getPointeeType();
786 if (!isConsumableType(ThisType))
789 // FIXME: What should happen if someone annotates the move constructor?
790 if (ReturnTypestateAttr *RTA = Constructor->getAttr<ReturnTypestateAttr>()) {
791 // TODO: Adjust state of args appropriately.
792 ConsumedState RetState = mapReturnTypestateAttrState(RTA);
793 PropagationMap.insert(PairType(Call, PropagationInfo(RetState)));
794 } else if (Constructor->isDefaultConstructor()) {
795 PropagationMap.insert(PairType(Call,
796 PropagationInfo(consumed::CS_Consumed)));
797 } else if (Constructor->isMoveConstructor()) {
798 copyInfo(Call->getArg(0), Call, CS_Consumed);
799 } else if (Constructor->isCopyConstructor()) {
800 // Copy state from arg. If setStateOnRead then set arg to CS_Unknown.
802 isSetOnReadPtrType(Constructor->getThisType(CurrContext)) ?
803 CS_Unknown : CS_None;
804 copyInfo(Call->getArg(0), Call, NS);
806 // TODO: Adjust state of args appropriately.
807 ConsumedState RetState = mapConsumableAttrState(ThisType);
808 PropagationMap.insert(PairType(Call, PropagationInfo(RetState)));
813 void ConsumedStmtVisitor::VisitCXXMemberCallExpr(
814 const CXXMemberCallExpr *Call) {
815 CXXMethodDecl* MD = Call->getMethodDecl();
819 handleCall(Call, Call->getImplicitObjectArgument(), MD);
820 propagateReturnType(Call, MD);
824 void ConsumedStmtVisitor::VisitCXXOperatorCallExpr(
825 const CXXOperatorCallExpr *Call) {
827 const FunctionDecl *FunDecl =
828 dyn_cast_or_null<FunctionDecl>(Call->getDirectCallee());
829 if (!FunDecl) return;
831 if (Call->getOperator() == OO_Equal) {
832 ConsumedState CS = getInfo(Call->getArg(1));
833 if (!handleCall(Call, Call->getArg(0), FunDecl))
834 setInfo(Call->getArg(0), CS);
838 if (const CXXMemberCallExpr *MCall = dyn_cast<CXXMemberCallExpr>(Call))
839 handleCall(MCall, MCall->getImplicitObjectArgument(), FunDecl);
841 handleCall(Call, Call->getArg(0), FunDecl);
843 propagateReturnType(Call, FunDecl);
846 void ConsumedStmtVisitor::VisitDeclRefExpr(const DeclRefExpr *DeclRef) {
847 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(DeclRef->getDecl()))
848 if (StateMap->getState(Var) != consumed::CS_None)
849 PropagationMap.insert(PairType(DeclRef, PropagationInfo(Var)));
852 void ConsumedStmtVisitor::VisitDeclStmt(const DeclStmt *DeclS) {
853 for (const auto *DI : DeclS->decls())
854 if (isa<VarDecl>(DI))
855 VisitVarDecl(cast<VarDecl>(DI));
857 if (DeclS->isSingleDecl())
858 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl()))
859 PropagationMap.insert(PairType(DeclS, PropagationInfo(Var)));
862 void ConsumedStmtVisitor::VisitMaterializeTemporaryExpr(
863 const MaterializeTemporaryExpr *Temp) {
865 forwardInfo(Temp->GetTemporaryExpr(), Temp);
868 void ConsumedStmtVisitor::VisitMemberExpr(const MemberExpr *MExpr) {
869 forwardInfo(MExpr->getBase(), MExpr);
873 void ConsumedStmtVisitor::VisitParmVarDecl(const ParmVarDecl *Param) {
874 QualType ParamType = Param->getType();
875 ConsumedState ParamState = consumed::CS_None;
877 if (const ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>())
878 ParamState = mapParamTypestateAttrState(PTA);
879 else if (isConsumableType(ParamType))
880 ParamState = mapConsumableAttrState(ParamType);
881 else if (isRValueRef(ParamType) &&
882 isConsumableType(ParamType->getPointeeType()))
883 ParamState = mapConsumableAttrState(ParamType->getPointeeType());
884 else if (ParamType->isReferenceType() &&
885 isConsumableType(ParamType->getPointeeType()))
886 ParamState = consumed::CS_Unknown;
888 if (ParamState != CS_None)
889 StateMap->setState(Param, ParamState);
892 void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) {
893 ConsumedState ExpectedState = Analyzer.getExpectedReturnState();
895 if (ExpectedState != CS_None) {
896 InfoEntry Entry = findInfo(Ret->getRetValue());
898 if (Entry != PropagationMap.end()) {
899 ConsumedState RetState = Entry->second.getAsState(StateMap);
901 if (RetState != ExpectedState)
902 Analyzer.WarningsHandler.warnReturnTypestateMismatch(
903 Ret->getReturnLoc(), stateToString(ExpectedState),
904 stateToString(RetState));
908 StateMap->checkParamsForReturnTypestate(Ret->getLocStart(),
909 Analyzer.WarningsHandler);
912 void ConsumedStmtVisitor::VisitUnaryOperator(const UnaryOperator *UOp) {
913 InfoEntry Entry = findInfo(UOp->getSubExpr());
914 if (Entry == PropagationMap.end()) return;
916 switch (UOp->getOpcode()) {
918 PropagationMap.insert(PairType(UOp, Entry->second));
922 if (Entry->second.isTest())
923 PropagationMap.insert(PairType(UOp, Entry->second.invertTest()));
931 // TODO: See if I need to check for reference types here.
932 void ConsumedStmtVisitor::VisitVarDecl(const VarDecl *Var) {
933 if (isConsumableType(Var->getType())) {
934 if (Var->hasInit()) {
935 MapType::iterator VIT = findInfo(Var->getInit()->IgnoreImplicit());
936 if (VIT != PropagationMap.end()) {
937 PropagationInfo PInfo = VIT->second;
938 ConsumedState St = PInfo.getAsState(StateMap);
940 if (St != consumed::CS_None) {
941 StateMap->setState(Var, St);
947 StateMap->setState(Var, consumed::CS_Unknown);
950 }} // end clang::consumed::ConsumedStmtVisitor
955 static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test,
956 ConsumedStateMap *ThenStates,
957 ConsumedStateMap *ElseStates) {
958 ConsumedState VarState = ThenStates->getState(Test.Var);
960 if (VarState == CS_Unknown) {
961 ThenStates->setState(Test.Var, Test.TestsFor);
962 ElseStates->setState(Test.Var, invertConsumedUnconsumed(Test.TestsFor));
964 } else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) {
965 ThenStates->markUnreachable();
967 } else if (VarState == Test.TestsFor) {
968 ElseStates->markUnreachable();
972 static void splitVarStateForIfBinOp(const PropagationInfo &PInfo,
973 ConsumedStateMap *ThenStates,
974 ConsumedStateMap *ElseStates) {
975 const VarTestResult <est = PInfo.getLTest(),
976 &RTest = PInfo.getRTest();
978 ConsumedState LState = LTest.Var ? ThenStates->getState(LTest.Var) : CS_None,
979 RState = RTest.Var ? ThenStates->getState(RTest.Var) : CS_None;
982 if (PInfo.testEffectiveOp() == EO_And) {
983 if (LState == CS_Unknown) {
984 ThenStates->setState(LTest.Var, LTest.TestsFor);
986 } else if (LState == invertConsumedUnconsumed(LTest.TestsFor)) {
987 ThenStates->markUnreachable();
989 } else if (LState == LTest.TestsFor && isKnownState(RState)) {
990 if (RState == RTest.TestsFor)
991 ElseStates->markUnreachable();
993 ThenStates->markUnreachable();
997 if (LState == CS_Unknown) {
998 ElseStates->setState(LTest.Var,
999 invertConsumedUnconsumed(LTest.TestsFor));
1001 } else if (LState == LTest.TestsFor) {
1002 ElseStates->markUnreachable();
1004 } else if (LState == invertConsumedUnconsumed(LTest.TestsFor) &&
1005 isKnownState(RState)) {
1007 if (RState == RTest.TestsFor)
1008 ElseStates->markUnreachable();
1010 ThenStates->markUnreachable();
1016 if (PInfo.testEffectiveOp() == EO_And) {
1017 if (RState == CS_Unknown)
1018 ThenStates->setState(RTest.Var, RTest.TestsFor);
1019 else if (RState == invertConsumedUnconsumed(RTest.TestsFor))
1020 ThenStates->markUnreachable();
1023 if (RState == CS_Unknown)
1024 ElseStates->setState(RTest.Var,
1025 invertConsumedUnconsumed(RTest.TestsFor));
1026 else if (RState == RTest.TestsFor)
1027 ElseStates->markUnreachable();
1032 bool ConsumedBlockInfo::allBackEdgesVisited(const CFGBlock *CurrBlock,
1033 const CFGBlock *TargetBlock) {
1035 assert(CurrBlock && "Block pointer must not be NULL");
1036 assert(TargetBlock && "TargetBlock pointer must not be NULL");
1038 unsigned int CurrBlockOrder = VisitOrder[CurrBlock->getBlockID()];
1039 for (CFGBlock::const_pred_iterator PI = TargetBlock->pred_begin(),
1040 PE = TargetBlock->pred_end(); PI != PE; ++PI) {
1041 if (*PI && CurrBlockOrder < VisitOrder[(*PI)->getBlockID()] )
1047 void ConsumedBlockInfo::addInfo(
1048 const CFGBlock *Block, ConsumedStateMap *StateMap,
1049 std::unique_ptr<ConsumedStateMap> &OwnedStateMap) {
1051 assert(Block && "Block pointer must not be NULL");
1053 auto &Entry = StateMapsArray[Block->getBlockID()];
1056 Entry->intersect(*StateMap);
1057 } else if (OwnedStateMap)
1058 Entry = std::move(OwnedStateMap);
1060 Entry = llvm::make_unique<ConsumedStateMap>(*StateMap);
1063 void ConsumedBlockInfo::addInfo(const CFGBlock *Block,
1064 std::unique_ptr<ConsumedStateMap> StateMap) {
1066 assert(Block && "Block pointer must not be NULL");
1068 auto &Entry = StateMapsArray[Block->getBlockID()];
1071 Entry->intersect(*StateMap);
1073 Entry = std::move(StateMap);
1077 ConsumedStateMap* ConsumedBlockInfo::borrowInfo(const CFGBlock *Block) {
1078 assert(Block && "Block pointer must not be NULL");
1079 assert(StateMapsArray[Block->getBlockID()] && "Block has no block info");
1081 return StateMapsArray[Block->getBlockID()].get();
1084 void ConsumedBlockInfo::discardInfo(const CFGBlock *Block) {
1085 StateMapsArray[Block->getBlockID()] = nullptr;
1088 std::unique_ptr<ConsumedStateMap>
1089 ConsumedBlockInfo::getInfo(const CFGBlock *Block) {
1090 assert(Block && "Block pointer must not be NULL");
1092 auto &Entry = StateMapsArray[Block->getBlockID()];
1093 return isBackEdgeTarget(Block) ? llvm::make_unique<ConsumedStateMap>(*Entry)
1097 bool ConsumedBlockInfo::isBackEdge(const CFGBlock *From, const CFGBlock *To) {
1098 assert(From && "From block must not be NULL");
1099 assert(To && "From block must not be NULL");
1101 return VisitOrder[From->getBlockID()] > VisitOrder[To->getBlockID()];
1104 bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) {
1105 assert(Block && "Block pointer must not be NULL");
1107 // Anything with less than two predecessors can't be the target of a back
1109 if (Block->pred_size() < 2)
1112 unsigned int BlockVisitOrder = VisitOrder[Block->getBlockID()];
1113 for (CFGBlock::const_pred_iterator PI = Block->pred_begin(),
1114 PE = Block->pred_end(); PI != PE; ++PI) {
1115 if (*PI && BlockVisitOrder < VisitOrder[(*PI)->getBlockID()])
1121 void ConsumedStateMap::checkParamsForReturnTypestate(SourceLocation BlameLoc,
1122 ConsumedWarningsHandlerBase &WarningsHandler) const {
1124 for (const auto &DM : VarMap) {
1125 if (isa<ParmVarDecl>(DM.first)) {
1126 const ParmVarDecl *Param = cast<ParmVarDecl>(DM.first);
1127 const ReturnTypestateAttr *RTA = Param->getAttr<ReturnTypestateAttr>();
1132 ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA);
1133 if (DM.second != ExpectedState)
1134 WarningsHandler.warnParamReturnTypestateMismatch(BlameLoc,
1135 Param->getNameAsString(), stateToString(ExpectedState),
1136 stateToString(DM.second));
1141 void ConsumedStateMap::clearTemporaries() {
1145 ConsumedState ConsumedStateMap::getState(const VarDecl *Var) const {
1146 VarMapType::const_iterator Entry = VarMap.find(Var);
1148 if (Entry != VarMap.end())
1149 return Entry->second;
1155 ConsumedStateMap::getState(const CXXBindTemporaryExpr *Tmp) const {
1156 TmpMapType::const_iterator Entry = TmpMap.find(Tmp);
1158 if (Entry != TmpMap.end())
1159 return Entry->second;
1164 void ConsumedStateMap::intersect(const ConsumedStateMap &Other) {
1165 ConsumedState LocalState;
1167 if (this->From && this->From == Other.From && !Other.Reachable) {
1168 this->markUnreachable();
1172 for (const auto &DM : Other.VarMap) {
1173 LocalState = this->getState(DM.first);
1175 if (LocalState == CS_None)
1178 if (LocalState != DM.second)
1179 VarMap[DM.first] = CS_Unknown;
1183 void ConsumedStateMap::intersectAtLoopHead(const CFGBlock *LoopHead,
1184 const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates,
1185 ConsumedWarningsHandlerBase &WarningsHandler) {
1187 ConsumedState LocalState;
1188 SourceLocation BlameLoc = getLastStmtLoc(LoopBack);
1190 for (const auto &DM : LoopBackStates->VarMap) {
1191 LocalState = this->getState(DM.first);
1193 if (LocalState == CS_None)
1196 if (LocalState != DM.second) {
1197 VarMap[DM.first] = CS_Unknown;
1198 WarningsHandler.warnLoopStateMismatch(BlameLoc,
1199 DM.first->getNameAsString());
1204 void ConsumedStateMap::markUnreachable() {
1205 this->Reachable = false;
1210 void ConsumedStateMap::setState(const VarDecl *Var, ConsumedState State) {
1211 VarMap[Var] = State;
1214 void ConsumedStateMap::setState(const CXXBindTemporaryExpr *Tmp,
1215 ConsumedState State) {
1216 TmpMap[Tmp] = State;
1219 void ConsumedStateMap::remove(const CXXBindTemporaryExpr *Tmp) {
1223 bool ConsumedStateMap::operator!=(const ConsumedStateMap *Other) const {
1224 for (const auto &DM : Other->VarMap)
1225 if (this->getState(DM.first) != DM.second)
1230 void ConsumedAnalyzer::determineExpectedReturnState(AnalysisDeclContext &AC,
1231 const FunctionDecl *D) {
1232 QualType ReturnType;
1233 if (const CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1234 ASTContext &CurrContext = AC.getASTContext();
1235 ReturnType = Constructor->getThisType(CurrContext)->getPointeeType();
1237 ReturnType = D->getCallResultType();
1239 if (const ReturnTypestateAttr *RTSAttr = D->getAttr<ReturnTypestateAttr>()) {
1240 const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1241 if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1242 // FIXME: This should be removed when template instantiation propagates
1243 // attributes at template specialization definition, not
1244 // declaration. When it is removed the test needs to be enabled
1245 // in SemaDeclAttr.cpp.
1246 WarningsHandler.warnReturnTypestateForUnconsumableType(
1247 RTSAttr->getLocation(), ReturnType.getAsString());
1248 ExpectedReturnState = CS_None;
1250 ExpectedReturnState = mapReturnTypestateAttrState(RTSAttr);
1251 } else if (isConsumableType(ReturnType)) {
1252 if (isAutoCastType(ReturnType)) // We can auto-cast the state to the
1253 ExpectedReturnState = CS_None; // expected state.
1255 ExpectedReturnState = mapConsumableAttrState(ReturnType);
1258 ExpectedReturnState = CS_None;
1261 bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock,
1262 const ConsumedStmtVisitor &Visitor) {
1264 std::unique_ptr<ConsumedStateMap> FalseStates(
1265 new ConsumedStateMap(*CurrStates));
1266 PropagationInfo PInfo;
1268 if (const IfStmt *IfNode =
1269 dyn_cast_or_null<IfStmt>(CurrBlock->getTerminator().getStmt())) {
1271 const Expr *Cond = IfNode->getCond();
1273 PInfo = Visitor.getInfo(Cond);
1274 if (!PInfo.isValid() && isa<BinaryOperator>(Cond))
1275 PInfo = Visitor.getInfo(cast<BinaryOperator>(Cond)->getRHS());
1277 if (PInfo.isVarTest()) {
1278 CurrStates->setSource(Cond);
1279 FalseStates->setSource(Cond);
1280 splitVarStateForIf(IfNode, PInfo.getVarTest(), CurrStates.get(),
1283 } else if (PInfo.isBinTest()) {
1284 CurrStates->setSource(PInfo.testSourceNode());
1285 FalseStates->setSource(PInfo.testSourceNode());
1286 splitVarStateForIfBinOp(PInfo, CurrStates.get(), FalseStates.get());
1292 } else if (const BinaryOperator *BinOp =
1293 dyn_cast_or_null<BinaryOperator>(CurrBlock->getTerminator().getStmt())) {
1295 PInfo = Visitor.getInfo(BinOp->getLHS());
1296 if (!PInfo.isVarTest()) {
1297 if ((BinOp = dyn_cast_or_null<BinaryOperator>(BinOp->getLHS()))) {
1298 PInfo = Visitor.getInfo(BinOp->getRHS());
1300 if (!PInfo.isVarTest())
1308 CurrStates->setSource(BinOp);
1309 FalseStates->setSource(BinOp);
1311 const VarTestResult &Test = PInfo.getVarTest();
1312 ConsumedState VarState = CurrStates->getState(Test.Var);
1314 if (BinOp->getOpcode() == BO_LAnd) {
1315 if (VarState == CS_Unknown)
1316 CurrStates->setState(Test.Var, Test.TestsFor);
1317 else if (VarState == invertConsumedUnconsumed(Test.TestsFor))
1318 CurrStates->markUnreachable();
1320 } else if (BinOp->getOpcode() == BO_LOr) {
1321 if (VarState == CS_Unknown)
1322 FalseStates->setState(Test.Var,
1323 invertConsumedUnconsumed(Test.TestsFor));
1324 else if (VarState == Test.TestsFor)
1325 FalseStates->markUnreachable();
1332 CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin();
1335 BlockInfo.addInfo(*SI, std::move(CurrStates));
1337 CurrStates = nullptr;
1340 BlockInfo.addInfo(*SI, std::move(FalseStates));
1345 void ConsumedAnalyzer::run(AnalysisDeclContext &AC) {
1346 const FunctionDecl *D = dyn_cast_or_null<FunctionDecl>(AC.getDecl());
1350 CFG *CFGraph = AC.getCFG();
1354 determineExpectedReturnState(AC, D);
1356 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
1357 // AC.getCFG()->viewCFG(LangOptions());
1359 BlockInfo = ConsumedBlockInfo(CFGraph->getNumBlockIDs(), SortedGraph);
1361 CurrStates = llvm::make_unique<ConsumedStateMap>();
1362 ConsumedStmtVisitor Visitor(AC, *this, CurrStates.get());
1364 // Add all trackable parameters to the state map.
1365 for (const auto *PI : D->parameters())
1366 Visitor.VisitParmVarDecl(PI);
1368 // Visit all of the function's basic blocks.
1369 for (const auto *CurrBlock : *SortedGraph) {
1371 CurrStates = BlockInfo.getInfo(CurrBlock);
1376 } else if (!CurrStates->isReachable()) {
1377 CurrStates = nullptr;
1381 Visitor.reset(CurrStates.get());
1383 // Visit all of the basic block's statements.
1384 for (const auto &B : *CurrBlock) {
1385 switch (B.getKind()) {
1386 case CFGElement::Statement:
1387 Visitor.Visit(B.castAs<CFGStmt>().getStmt());
1390 case CFGElement::TemporaryDtor: {
1391 const CFGTemporaryDtor &DTor = B.castAs<CFGTemporaryDtor>();
1392 const CXXBindTemporaryExpr *BTE = DTor.getBindTemporaryExpr();
1394 Visitor.checkCallability(PropagationInfo(BTE),
1395 DTor.getDestructorDecl(AC.getASTContext()),
1397 CurrStates->remove(BTE);
1401 case CFGElement::AutomaticObjectDtor: {
1402 const CFGAutomaticObjDtor &DTor = B.castAs<CFGAutomaticObjDtor>();
1403 SourceLocation Loc = DTor.getTriggerStmt()->getLocEnd();
1404 const VarDecl *Var = DTor.getVarDecl();
1406 Visitor.checkCallability(PropagationInfo(Var),
1407 DTor.getDestructorDecl(AC.getASTContext()),
1417 // TODO: Handle other forms of branching with precision, including while-
1418 // and for-loops. (Deferred)
1419 if (!splitState(CurrBlock, Visitor)) {
1420 CurrStates->setSource(nullptr);
1422 if (CurrBlock->succ_size() > 1 ||
1423 (CurrBlock->succ_size() == 1 &&
1424 (*CurrBlock->succ_begin())->pred_size() > 1)) {
1426 auto *RawState = CurrStates.get();
1428 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1429 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1431 if (*SI == nullptr) continue;
1433 if (BlockInfo.isBackEdge(CurrBlock, *SI)) {
1434 BlockInfo.borrowInfo(*SI)->intersectAtLoopHead(
1435 *SI, CurrBlock, RawState, WarningsHandler);
1437 if (BlockInfo.allBackEdgesVisited(CurrBlock, *SI))
1438 BlockInfo.discardInfo(*SI);
1440 BlockInfo.addInfo(*SI, RawState, CurrStates);
1444 CurrStates = nullptr;
1448 if (CurrBlock == &AC.getCFG()->getExit() &&
1449 D->getCallResultType()->isVoidType())
1450 CurrStates->checkParamsForReturnTypestate(D->getLocation(),
1452 } // End of block iterator.
1454 // Delete the last existing state map.
1455 CurrStates = nullptr;
1457 WarningsHandler.emitDiagnostics();
1459 }} // end namespace clang::consumed