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