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