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()->getBeginLoc(); 68 69 // Block is empty. 70 // If we have one successor, return the first statement in that block 71 if (Block->succ_size() == 1 && *Block->succ_begin()) 72 return getFirstStmtLoc(*Block->succ_begin()); 73 74 return {}; 75 } 76 77 static SourceLocation getLastStmtLoc(const CFGBlock *Block) { 78 // Find the source location of the last statement in the block, if the block 79 // is not empty. 80 if (const Stmt *StmtNode = Block->getTerminator()) { 81 return StmtNode->getBeginLoc(); 82 } else { 83 for (CFGBlock::const_reverse_iterator BI = Block->rbegin(), 84 BE = Block->rend(); BI != BE; ++BI) { 85 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) 86 return CS->getStmt()->getBeginLoc(); 87 } 88 } 89 90 // If we have one successor, return the first statement in that block 91 SourceLocation Loc; 92 if (Block->succ_size() == 1 && *Block->succ_begin()) 93 Loc = getFirstStmtLoc(*Block->succ_begin()); 94 if (Loc.isValid()) 95 return Loc; 96 97 // If we have one predecessor, return the last statement in that block 98 if (Block->pred_size() == 1 && *Block->pred_begin()) 99 return getLastStmtLoc(*Block->pred_begin()); 100 101 return Loc; 102 } 103 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 <est, 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 ConsumedAnalyzer &Analyzer; 467 ConsumedStateMap *StateMap; 468 MapType PropagationMap; 469 470 InfoEntry findInfo(const Expr *E) { 471 if (const auto Cleanups = dyn_cast<ExprWithCleanups>(E)) 472 if (!Cleanups->cleanupsHaveSideEffects()) 473 E = Cleanups->getSubExpr(); 474 return PropagationMap.find(E->IgnoreParens()); 475 } 476 477 ConstInfoEntry findInfo(const Expr *E) const { 478 if (const auto Cleanups = dyn_cast<ExprWithCleanups>(E)) 479 if (!Cleanups->cleanupsHaveSideEffects()) 480 E = Cleanups->getSubExpr(); 481 return PropagationMap.find(E->IgnoreParens()); 482 } 483 484 void insertInfo(const Expr *E, const PropagationInfo &PI) { 485 PropagationMap.insert(PairType(E->IgnoreParens(), PI)); 486 } 487 488 void forwardInfo(const Expr *From, const Expr *To); 489 void copyInfo(const Expr *From, const Expr *To, ConsumedState CS); 490 ConsumedState getInfo(const Expr *From); 491 void setInfo(const Expr *To, ConsumedState NS); 492 void propagateReturnType(const Expr *Call, const FunctionDecl *Fun); 493 494 public: 495 void checkCallability(const PropagationInfo &PInfo, 496 const FunctionDecl *FunDecl, 497 SourceLocation BlameLoc); 498 bool handleCall(const CallExpr *Call, const Expr *ObjArg, 499 const FunctionDecl *FunD); 500 501 void VisitBinaryOperator(const BinaryOperator *BinOp); 502 void VisitCallExpr(const CallExpr *Call); 503 void VisitCastExpr(const CastExpr *Cast); 504 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Temp); 505 void VisitCXXConstructExpr(const CXXConstructExpr *Call); 506 void VisitCXXMemberCallExpr(const CXXMemberCallExpr *Call); 507 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *Call); 508 void VisitDeclRefExpr(const DeclRefExpr *DeclRef); 509 void VisitDeclStmt(const DeclStmt *DelcS); 510 void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Temp); 511 void VisitMemberExpr(const MemberExpr *MExpr); 512 void VisitParmVarDecl(const ParmVarDecl *Param); 513 void VisitReturnStmt(const ReturnStmt *Ret); 514 void VisitUnaryOperator(const UnaryOperator *UOp); 515 void VisitVarDecl(const VarDecl *Var); 516 517 ConsumedStmtVisitor(ConsumedAnalyzer &Analyzer, ConsumedStateMap *StateMap) 518 : Analyzer(Analyzer), StateMap(StateMap) {} 519 520 PropagationInfo getInfo(const Expr *StmtNode) const { 521 ConstInfoEntry Entry = findInfo(StmtNode); 522 523 if (Entry != PropagationMap.end()) 524 return Entry->second; 525 else 526 return {}; 527 } 528 529 void reset(ConsumedStateMap *NewStateMap) { 530 StateMap = NewStateMap; 531 } 532 }; 533 534 } // namespace consumed 535 } // namespace clang 536 537 void ConsumedStmtVisitor::forwardInfo(const Expr *From, const Expr *To) { 538 InfoEntry Entry = findInfo(From); 539 if (Entry != PropagationMap.end()) 540 insertInfo(To, Entry->second); 541 } 542 543 // Create a new state for To, which is initialized to the state of From. 544 // If NS is not CS_None, sets the state of From to NS. 545 void ConsumedStmtVisitor::copyInfo(const Expr *From, const Expr *To, 546 ConsumedState NS) { 547 InfoEntry Entry = findInfo(From); 548 if (Entry != PropagationMap.end()) { 549 PropagationInfo& PInfo = Entry->second; 550 ConsumedState CS = PInfo.getAsState(StateMap); 551 if (CS != CS_None) 552 insertInfo(To, PropagationInfo(CS)); 553 if (NS != CS_None && PInfo.isPointerToValue()) 554 setStateForVarOrTmp(StateMap, PInfo, NS); 555 } 556 } 557 558 // Get the ConsumedState for From 559 ConsumedState ConsumedStmtVisitor::getInfo(const Expr *From) { 560 InfoEntry Entry = findInfo(From); 561 if (Entry != PropagationMap.end()) { 562 PropagationInfo& PInfo = Entry->second; 563 return PInfo.getAsState(StateMap); 564 } 565 return CS_None; 566 } 567 568 // If we already have info for To then update it, otherwise create a new entry. 569 void ConsumedStmtVisitor::setInfo(const Expr *To, ConsumedState NS) { 570 InfoEntry Entry = findInfo(To); 571 if (Entry != PropagationMap.end()) { 572 PropagationInfo& PInfo = Entry->second; 573 if (PInfo.isPointerToValue()) 574 setStateForVarOrTmp(StateMap, PInfo, NS); 575 } else if (NS != CS_None) { 576 insertInfo(To, PropagationInfo(NS)); 577 } 578 } 579 580 void ConsumedStmtVisitor::checkCallability(const PropagationInfo &PInfo, 581 const FunctionDecl *FunDecl, 582 SourceLocation BlameLoc) { 583 assert(!PInfo.isTest()); 584 585 const CallableWhenAttr *CWAttr = FunDecl->getAttr<CallableWhenAttr>(); 586 if (!CWAttr) 587 return; 588 589 if (PInfo.isVar()) { 590 ConsumedState VarState = StateMap->getState(PInfo.getVar()); 591 592 if (VarState == CS_None || isCallableInState(CWAttr, VarState)) 593 return; 594 595 Analyzer.WarningsHandler.warnUseInInvalidState( 596 FunDecl->getNameAsString(), PInfo.getVar()->getNameAsString(), 597 stateToString(VarState), BlameLoc); 598 } else { 599 ConsumedState TmpState = PInfo.getAsState(StateMap); 600 601 if (TmpState == CS_None || isCallableInState(CWAttr, TmpState)) 602 return; 603 604 Analyzer.WarningsHandler.warnUseOfTempInInvalidState( 605 FunDecl->getNameAsString(), stateToString(TmpState), BlameLoc); 606 } 607 } 608 609 // Factors out common behavior for function, method, and operator calls. 610 // Check parameters and set parameter state if necessary. 611 // Returns true if the state of ObjArg is set, or false otherwise. 612 bool ConsumedStmtVisitor::handleCall(const CallExpr *Call, const Expr *ObjArg, 613 const FunctionDecl *FunD) { 614 unsigned Offset = 0; 615 if (isa<CXXOperatorCallExpr>(Call) && isa<CXXMethodDecl>(FunD)) 616 Offset = 1; // first argument is 'this' 617 618 // check explicit parameters 619 for (unsigned Index = Offset; Index < Call->getNumArgs(); ++Index) { 620 // Skip variable argument lists. 621 if (Index - Offset >= FunD->getNumParams()) 622 break; 623 624 const ParmVarDecl *Param = FunD->getParamDecl(Index - Offset); 625 QualType ParamType = Param->getType(); 626 627 InfoEntry Entry = findInfo(Call->getArg(Index)); 628 629 if (Entry == PropagationMap.end() || Entry->second.isTest()) 630 continue; 631 PropagationInfo PInfo = Entry->second; 632 633 // Check that the parameter is in the correct state. 634 if (ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>()) { 635 ConsumedState ParamState = PInfo.getAsState(StateMap); 636 ConsumedState ExpectedState = mapParamTypestateAttrState(PTA); 637 638 if (ParamState != ExpectedState) 639 Analyzer.WarningsHandler.warnParamTypestateMismatch( 640 Call->getArg(Index)->getExprLoc(), 641 stateToString(ExpectedState), stateToString(ParamState)); 642 } 643 644 if (!(Entry->second.isVar() || Entry->second.isTmp())) 645 continue; 646 647 // Adjust state on the caller side. 648 if (isRValueRef(ParamType)) 649 setStateForVarOrTmp(StateMap, PInfo, consumed::CS_Consumed); 650 else if (ReturnTypestateAttr *RT = Param->getAttr<ReturnTypestateAttr>()) 651 setStateForVarOrTmp(StateMap, PInfo, mapReturnTypestateAttrState(RT)); 652 else if (isPointerOrRef(ParamType) && 653 (!ParamType->getPointeeType().isConstQualified() || 654 isSetOnReadPtrType(ParamType))) 655 setStateForVarOrTmp(StateMap, PInfo, consumed::CS_Unknown); 656 } 657 658 if (!ObjArg) 659 return false; 660 661 // check implicit 'self' parameter, if present 662 InfoEntry Entry = findInfo(ObjArg); 663 if (Entry != PropagationMap.end()) { 664 PropagationInfo PInfo = Entry->second; 665 checkCallability(PInfo, FunD, Call->getExprLoc()); 666 667 if (SetTypestateAttr *STA = FunD->getAttr<SetTypestateAttr>()) { 668 if (PInfo.isVar()) { 669 StateMap->setState(PInfo.getVar(), mapSetTypestateAttrState(STA)); 670 return true; 671 } 672 else if (PInfo.isTmp()) { 673 StateMap->setState(PInfo.getTmp(), mapSetTypestateAttrState(STA)); 674 return true; 675 } 676 } 677 else if (isTestingFunction(FunD) && PInfo.isVar()) { 678 PropagationMap.insert(PairType(Call, 679 PropagationInfo(PInfo.getVar(), testsFor(FunD)))); 680 } 681 } 682 return false; 683 } 684 685 void ConsumedStmtVisitor::propagateReturnType(const Expr *Call, 686 const FunctionDecl *Fun) { 687 QualType RetType = Fun->getCallResultType(); 688 if (RetType->isReferenceType()) 689 RetType = RetType->getPointeeType(); 690 691 if (isConsumableType(RetType)) { 692 ConsumedState ReturnState; 693 if (ReturnTypestateAttr *RTA = Fun->getAttr<ReturnTypestateAttr>()) 694 ReturnState = mapReturnTypestateAttrState(RTA); 695 else 696 ReturnState = mapConsumableAttrState(RetType); 697 698 PropagationMap.insert(PairType(Call, PropagationInfo(ReturnState))); 699 } 700 } 701 702 void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) { 703 switch (BinOp->getOpcode()) { 704 case BO_LAnd: 705 case BO_LOr : { 706 InfoEntry LEntry = findInfo(BinOp->getLHS()), 707 REntry = findInfo(BinOp->getRHS()); 708 709 VarTestResult LTest, RTest; 710 711 if (LEntry != PropagationMap.end() && LEntry->second.isVarTest()) { 712 LTest = LEntry->second.getVarTest(); 713 } else { 714 LTest.Var = nullptr; 715 LTest.TestsFor = CS_None; 716 } 717 718 if (REntry != PropagationMap.end() && REntry->second.isVarTest()) { 719 RTest = REntry->second.getVarTest(); 720 } else { 721 RTest.Var = nullptr; 722 RTest.TestsFor = CS_None; 723 } 724 725 if (!(LTest.Var == nullptr && RTest.Var == nullptr)) 726 PropagationMap.insert(PairType(BinOp, PropagationInfo(BinOp, 727 static_cast<EffectiveOp>(BinOp->getOpcode() == BO_LOr), LTest, RTest))); 728 break; 729 } 730 731 case BO_PtrMemD: 732 case BO_PtrMemI: 733 forwardInfo(BinOp->getLHS(), BinOp); 734 break; 735 736 default: 737 break; 738 } 739 } 740 741 void ConsumedStmtVisitor::VisitCallExpr(const CallExpr *Call) { 742 const FunctionDecl *FunDecl = Call->getDirectCallee(); 743 if (!FunDecl) 744 return; 745 746 // Special case for the std::move function. 747 // TODO: Make this more specific. (Deferred) 748 if (Call->isCallToStdMove()) { 749 copyInfo(Call->getArg(0), Call, CS_Consumed); 750 return; 751 } 752 753 handleCall(Call, nullptr, FunDecl); 754 propagateReturnType(Call, FunDecl); 755 } 756 757 void ConsumedStmtVisitor::VisitCastExpr(const CastExpr *Cast) { 758 forwardInfo(Cast->getSubExpr(), Cast); 759 } 760 761 void ConsumedStmtVisitor::VisitCXXBindTemporaryExpr( 762 const CXXBindTemporaryExpr *Temp) { 763 764 InfoEntry Entry = findInfo(Temp->getSubExpr()); 765 766 if (Entry != PropagationMap.end() && !Entry->second.isTest()) { 767 StateMap->setState(Temp, Entry->second.getAsState(StateMap)); 768 PropagationMap.insert(PairType(Temp, PropagationInfo(Temp))); 769 } 770 } 771 772 void ConsumedStmtVisitor::VisitCXXConstructExpr(const CXXConstructExpr *Call) { 773 CXXConstructorDecl *Constructor = Call->getConstructor(); 774 775 QualType ThisType = Constructor->getThisType()->getPointeeType(); 776 777 if (!isConsumableType(ThisType)) 778 return; 779 780 // FIXME: What should happen if someone annotates the move constructor? 781 if (ReturnTypestateAttr *RTA = Constructor->getAttr<ReturnTypestateAttr>()) { 782 // TODO: Adjust state of args appropriately. 783 ConsumedState RetState = mapReturnTypestateAttrState(RTA); 784 PropagationMap.insert(PairType(Call, PropagationInfo(RetState))); 785 } else if (Constructor->isDefaultConstructor()) { 786 PropagationMap.insert(PairType(Call, 787 PropagationInfo(consumed::CS_Consumed))); 788 } else if (Constructor->isMoveConstructor()) { 789 copyInfo(Call->getArg(0), Call, CS_Consumed); 790 } else if (Constructor->isCopyConstructor()) { 791 // Copy state from arg. If setStateOnRead then set arg to CS_Unknown. 792 ConsumedState NS = 793 isSetOnReadPtrType(Constructor->getThisType()) ? 794 CS_Unknown : CS_None; 795 copyInfo(Call->getArg(0), Call, NS); 796 } else { 797 // TODO: Adjust state of args appropriately. 798 ConsumedState RetState = mapConsumableAttrState(ThisType); 799 PropagationMap.insert(PairType(Call, PropagationInfo(RetState))); 800 } 801 } 802 803 void ConsumedStmtVisitor::VisitCXXMemberCallExpr( 804 const CXXMemberCallExpr *Call) { 805 CXXMethodDecl* MD = Call->getMethodDecl(); 806 if (!MD) 807 return; 808 809 handleCall(Call, Call->getImplicitObjectArgument(), MD); 810 propagateReturnType(Call, MD); 811 } 812 813 void ConsumedStmtVisitor::VisitCXXOperatorCallExpr( 814 const CXXOperatorCallExpr *Call) { 815 const auto *FunDecl = dyn_cast_or_null<FunctionDecl>(Call->getDirectCallee()); 816 if (!FunDecl) return; 817 818 if (Call->getOperator() == OO_Equal) { 819 ConsumedState CS = getInfo(Call->getArg(1)); 820 if (!handleCall(Call, Call->getArg(0), FunDecl)) 821 setInfo(Call->getArg(0), CS); 822 return; 823 } 824 825 if (const auto *MCall = dyn_cast<CXXMemberCallExpr>(Call)) 826 handleCall(MCall, MCall->getImplicitObjectArgument(), FunDecl); 827 else 828 handleCall(Call, Call->getArg(0), FunDecl); 829 830 propagateReturnType(Call, FunDecl); 831 } 832 833 void ConsumedStmtVisitor::VisitDeclRefExpr(const DeclRefExpr *DeclRef) { 834 if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclRef->getDecl())) 835 if (StateMap->getState(Var) != consumed::CS_None) 836 PropagationMap.insert(PairType(DeclRef, PropagationInfo(Var))); 837 } 838 839 void ConsumedStmtVisitor::VisitDeclStmt(const DeclStmt *DeclS) { 840 for (const auto *DI : DeclS->decls()) 841 if (isa<VarDecl>(DI)) 842 VisitVarDecl(cast<VarDecl>(DI)); 843 844 if (DeclS->isSingleDecl()) 845 if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl())) 846 PropagationMap.insert(PairType(DeclS, PropagationInfo(Var))); 847 } 848 849 void ConsumedStmtVisitor::VisitMaterializeTemporaryExpr( 850 const MaterializeTemporaryExpr *Temp) { 851 forwardInfo(Temp->GetTemporaryExpr(), Temp); 852 } 853 854 void ConsumedStmtVisitor::VisitMemberExpr(const MemberExpr *MExpr) { 855 forwardInfo(MExpr->getBase(), MExpr); 856 } 857 858 void ConsumedStmtVisitor::VisitParmVarDecl(const ParmVarDecl *Param) { 859 QualType ParamType = Param->getType(); 860 ConsumedState ParamState = consumed::CS_None; 861 862 if (const ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>()) 863 ParamState = mapParamTypestateAttrState(PTA); 864 else if (isConsumableType(ParamType)) 865 ParamState = mapConsumableAttrState(ParamType); 866 else if (isRValueRef(ParamType) && 867 isConsumableType(ParamType->getPointeeType())) 868 ParamState = mapConsumableAttrState(ParamType->getPointeeType()); 869 else if (ParamType->isReferenceType() && 870 isConsumableType(ParamType->getPointeeType())) 871 ParamState = consumed::CS_Unknown; 872 873 if (ParamState != CS_None) 874 StateMap->setState(Param, ParamState); 875 } 876 877 void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) { 878 ConsumedState ExpectedState = Analyzer.getExpectedReturnState(); 879 880 if (ExpectedState != CS_None) { 881 InfoEntry Entry = findInfo(Ret->getRetValue()); 882 883 if (Entry != PropagationMap.end()) { 884 ConsumedState RetState = Entry->second.getAsState(StateMap); 885 886 if (RetState != ExpectedState) 887 Analyzer.WarningsHandler.warnReturnTypestateMismatch( 888 Ret->getReturnLoc(), stateToString(ExpectedState), 889 stateToString(RetState)); 890 } 891 } 892 893 StateMap->checkParamsForReturnTypestate(Ret->getBeginLoc(), 894 Analyzer.WarningsHandler); 895 } 896 897 void ConsumedStmtVisitor::VisitUnaryOperator(const UnaryOperator *UOp) { 898 InfoEntry Entry = findInfo(UOp->getSubExpr()); 899 if (Entry == PropagationMap.end()) return; 900 901 switch (UOp->getOpcode()) { 902 case UO_AddrOf: 903 PropagationMap.insert(PairType(UOp, Entry->second)); 904 break; 905 906 case UO_LNot: 907 if (Entry->second.isTest()) 908 PropagationMap.insert(PairType(UOp, Entry->second.invertTest())); 909 break; 910 911 default: 912 break; 913 } 914 } 915 916 // TODO: See if I need to check for reference types here. 917 void ConsumedStmtVisitor::VisitVarDecl(const VarDecl *Var) { 918 if (isConsumableType(Var->getType())) { 919 if (Var->hasInit()) { 920 MapType::iterator VIT = findInfo(Var->getInit()->IgnoreImplicit()); 921 if (VIT != PropagationMap.end()) { 922 PropagationInfo PInfo = VIT->second; 923 ConsumedState St = PInfo.getAsState(StateMap); 924 925 if (St != consumed::CS_None) { 926 StateMap->setState(Var, St); 927 return; 928 } 929 } 930 } 931 // Otherwise 932 StateMap->setState(Var, consumed::CS_Unknown); 933 } 934 } 935 936 static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test, 937 ConsumedStateMap *ThenStates, 938 ConsumedStateMap *ElseStates) { 939 ConsumedState VarState = ThenStates->getState(Test.Var); 940 941 if (VarState == CS_Unknown) { 942 ThenStates->setState(Test.Var, Test.TestsFor); 943 ElseStates->setState(Test.Var, invertConsumedUnconsumed(Test.TestsFor)); 944 } else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) { 945 ThenStates->markUnreachable(); 946 } else if (VarState == Test.TestsFor) { 947 ElseStates->markUnreachable(); 948 } 949 } 950 951 static void splitVarStateForIfBinOp(const PropagationInfo &PInfo, 952 ConsumedStateMap *ThenStates, 953 ConsumedStateMap *ElseStates) { 954 const VarTestResult <est = PInfo.getLTest(), 955 &RTest = PInfo.getRTest(); 956 957 ConsumedState LState = LTest.Var ? ThenStates->getState(LTest.Var) : CS_None, 958 RState = RTest.Var ? ThenStates->getState(RTest.Var) : CS_None; 959 960 if (LTest.Var) { 961 if (PInfo.testEffectiveOp() == EO_And) { 962 if (LState == CS_Unknown) { 963 ThenStates->setState(LTest.Var, LTest.TestsFor); 964 } else if (LState == invertConsumedUnconsumed(LTest.TestsFor)) { 965 ThenStates->markUnreachable(); 966 } else if (LState == LTest.TestsFor && isKnownState(RState)) { 967 if (RState == RTest.TestsFor) 968 ElseStates->markUnreachable(); 969 else 970 ThenStates->markUnreachable(); 971 } 972 } else { 973 if (LState == CS_Unknown) { 974 ElseStates->setState(LTest.Var, 975 invertConsumedUnconsumed(LTest.TestsFor)); 976 } else if (LState == LTest.TestsFor) { 977 ElseStates->markUnreachable(); 978 } else if (LState == invertConsumedUnconsumed(LTest.TestsFor) && 979 isKnownState(RState)) { 980 if (RState == RTest.TestsFor) 981 ElseStates->markUnreachable(); 982 else 983 ThenStates->markUnreachable(); 984 } 985 } 986 } 987 988 if (RTest.Var) { 989 if (PInfo.testEffectiveOp() == EO_And) { 990 if (RState == CS_Unknown) 991 ThenStates->setState(RTest.Var, RTest.TestsFor); 992 else if (RState == invertConsumedUnconsumed(RTest.TestsFor)) 993 ThenStates->markUnreachable(); 994 } else { 995 if (RState == CS_Unknown) 996 ElseStates->setState(RTest.Var, 997 invertConsumedUnconsumed(RTest.TestsFor)); 998 else if (RState == RTest.TestsFor) 999 ElseStates->markUnreachable(); 1000 } 1001 } 1002 } 1003 1004 bool ConsumedBlockInfo::allBackEdgesVisited(const CFGBlock *CurrBlock, 1005 const CFGBlock *TargetBlock) { 1006 assert(CurrBlock && "Block pointer must not be NULL"); 1007 assert(TargetBlock && "TargetBlock pointer must not be NULL"); 1008 1009 unsigned int CurrBlockOrder = VisitOrder[CurrBlock->getBlockID()]; 1010 for (CFGBlock::const_pred_iterator PI = TargetBlock->pred_begin(), 1011 PE = TargetBlock->pred_end(); PI != PE; ++PI) { 1012 if (*PI && CurrBlockOrder < VisitOrder[(*PI)->getBlockID()] ) 1013 return false; 1014 } 1015 return true; 1016 } 1017 1018 void ConsumedBlockInfo::addInfo( 1019 const CFGBlock *Block, ConsumedStateMap *StateMap, 1020 std::unique_ptr<ConsumedStateMap> &OwnedStateMap) { 1021 assert(Block && "Block pointer must not be NULL"); 1022 1023 auto &Entry = StateMapsArray[Block->getBlockID()]; 1024 1025 if (Entry) { 1026 Entry->intersect(*StateMap); 1027 } else if (OwnedStateMap) 1028 Entry = std::move(OwnedStateMap); 1029 else 1030 Entry = llvm::make_unique<ConsumedStateMap>(*StateMap); 1031 } 1032 1033 void ConsumedBlockInfo::addInfo(const CFGBlock *Block, 1034 std::unique_ptr<ConsumedStateMap> StateMap) { 1035 assert(Block && "Block pointer must not be NULL"); 1036 1037 auto &Entry = StateMapsArray[Block->getBlockID()]; 1038 1039 if (Entry) { 1040 Entry->intersect(*StateMap); 1041 } else { 1042 Entry = std::move(StateMap); 1043 } 1044 } 1045 1046 ConsumedStateMap* ConsumedBlockInfo::borrowInfo(const CFGBlock *Block) { 1047 assert(Block && "Block pointer must not be NULL"); 1048 assert(StateMapsArray[Block->getBlockID()] && "Block has no block info"); 1049 1050 return StateMapsArray[Block->getBlockID()].get(); 1051 } 1052 1053 void ConsumedBlockInfo::discardInfo(const CFGBlock *Block) { 1054 StateMapsArray[Block->getBlockID()] = nullptr; 1055 } 1056 1057 std::unique_ptr<ConsumedStateMap> 1058 ConsumedBlockInfo::getInfo(const CFGBlock *Block) { 1059 assert(Block && "Block pointer must not be NULL"); 1060 1061 auto &Entry = StateMapsArray[Block->getBlockID()]; 1062 return isBackEdgeTarget(Block) ? llvm::make_unique<ConsumedStateMap>(*Entry) 1063 : std::move(Entry); 1064 } 1065 1066 bool ConsumedBlockInfo::isBackEdge(const CFGBlock *From, const CFGBlock *To) { 1067 assert(From && "From block must not be NULL"); 1068 assert(To && "From block must not be NULL"); 1069 1070 return VisitOrder[From->getBlockID()] > VisitOrder[To->getBlockID()]; 1071 } 1072 1073 bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) { 1074 assert(Block && "Block pointer must not be NULL"); 1075 1076 // Anything with less than two predecessors can't be the target of a back 1077 // edge. 1078 if (Block->pred_size() < 2) 1079 return false; 1080 1081 unsigned int BlockVisitOrder = VisitOrder[Block->getBlockID()]; 1082 for (CFGBlock::const_pred_iterator PI = Block->pred_begin(), 1083 PE = Block->pred_end(); PI != PE; ++PI) { 1084 if (*PI && BlockVisitOrder < VisitOrder[(*PI)->getBlockID()]) 1085 return true; 1086 } 1087 return false; 1088 } 1089 1090 void ConsumedStateMap::checkParamsForReturnTypestate(SourceLocation BlameLoc, 1091 ConsumedWarningsHandlerBase &WarningsHandler) const { 1092 1093 for (const auto &DM : VarMap) { 1094 if (isa<ParmVarDecl>(DM.first)) { 1095 const auto *Param = cast<ParmVarDecl>(DM.first); 1096 const ReturnTypestateAttr *RTA = Param->getAttr<ReturnTypestateAttr>(); 1097 1098 if (!RTA) 1099 continue; 1100 1101 ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA); 1102 if (DM.second != ExpectedState) 1103 WarningsHandler.warnParamReturnTypestateMismatch(BlameLoc, 1104 Param->getNameAsString(), stateToString(ExpectedState), 1105 stateToString(DM.second)); 1106 } 1107 } 1108 } 1109 1110 void ConsumedStateMap::clearTemporaries() { 1111 TmpMap.clear(); 1112 } 1113 1114 ConsumedState ConsumedStateMap::getState(const VarDecl *Var) const { 1115 VarMapType::const_iterator Entry = VarMap.find(Var); 1116 1117 if (Entry != VarMap.end()) 1118 return Entry->second; 1119 1120 return CS_None; 1121 } 1122 1123 ConsumedState 1124 ConsumedStateMap::getState(const CXXBindTemporaryExpr *Tmp) const { 1125 TmpMapType::const_iterator Entry = TmpMap.find(Tmp); 1126 1127 if (Entry != TmpMap.end()) 1128 return Entry->second; 1129 1130 return CS_None; 1131 } 1132 1133 void ConsumedStateMap::intersect(const ConsumedStateMap &Other) { 1134 ConsumedState LocalState; 1135 1136 if (this->From && this->From == Other.From && !Other.Reachable) { 1137 this->markUnreachable(); 1138 return; 1139 } 1140 1141 for (const auto &DM : Other.VarMap) { 1142 LocalState = this->getState(DM.first); 1143 1144 if (LocalState == CS_None) 1145 continue; 1146 1147 if (LocalState != DM.second) 1148 VarMap[DM.first] = CS_Unknown; 1149 } 1150 } 1151 1152 void ConsumedStateMap::intersectAtLoopHead(const CFGBlock *LoopHead, 1153 const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates, 1154 ConsumedWarningsHandlerBase &WarningsHandler) { 1155 1156 ConsumedState LocalState; 1157 SourceLocation BlameLoc = getLastStmtLoc(LoopBack); 1158 1159 for (const auto &DM : LoopBackStates->VarMap) { 1160 LocalState = this->getState(DM.first); 1161 1162 if (LocalState == CS_None) 1163 continue; 1164 1165 if (LocalState != DM.second) { 1166 VarMap[DM.first] = CS_Unknown; 1167 WarningsHandler.warnLoopStateMismatch(BlameLoc, 1168 DM.first->getNameAsString()); 1169 } 1170 } 1171 } 1172 1173 void ConsumedStateMap::markUnreachable() { 1174 this->Reachable = false; 1175 VarMap.clear(); 1176 TmpMap.clear(); 1177 } 1178 1179 void ConsumedStateMap::setState(const VarDecl *Var, ConsumedState State) { 1180 VarMap[Var] = State; 1181 } 1182 1183 void ConsumedStateMap::setState(const CXXBindTemporaryExpr *Tmp, 1184 ConsumedState State) { 1185 TmpMap[Tmp] = State; 1186 } 1187 1188 void ConsumedStateMap::remove(const CXXBindTemporaryExpr *Tmp) { 1189 TmpMap.erase(Tmp); 1190 } 1191 1192 bool ConsumedStateMap::operator!=(const ConsumedStateMap *Other) const { 1193 for (const auto &DM : Other->VarMap) 1194 if (this->getState(DM.first) != DM.second) 1195 return true; 1196 return false; 1197 } 1198 1199 void ConsumedAnalyzer::determineExpectedReturnState(AnalysisDeclContext &AC, 1200 const FunctionDecl *D) { 1201 QualType ReturnType; 1202 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1203 ReturnType = Constructor->getThisType()->getPointeeType(); 1204 } else 1205 ReturnType = D->getCallResultType(); 1206 1207 if (const ReturnTypestateAttr *RTSAttr = D->getAttr<ReturnTypestateAttr>()) { 1208 const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1209 if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1210 // FIXME: This should be removed when template instantiation propagates 1211 // attributes at template specialization definition, not 1212 // declaration. When it is removed the test needs to be enabled 1213 // in SemaDeclAttr.cpp. 1214 WarningsHandler.warnReturnTypestateForUnconsumableType( 1215 RTSAttr->getLocation(), ReturnType.getAsString()); 1216 ExpectedReturnState = CS_None; 1217 } else 1218 ExpectedReturnState = mapReturnTypestateAttrState(RTSAttr); 1219 } else if (isConsumableType(ReturnType)) { 1220 if (isAutoCastType(ReturnType)) // We can auto-cast the state to the 1221 ExpectedReturnState = CS_None; // expected state. 1222 else 1223 ExpectedReturnState = mapConsumableAttrState(ReturnType); 1224 } 1225 else 1226 ExpectedReturnState = CS_None; 1227 } 1228 1229 bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, 1230 const ConsumedStmtVisitor &Visitor) { 1231 std::unique_ptr<ConsumedStateMap> FalseStates( 1232 new ConsumedStateMap(*CurrStates)); 1233 PropagationInfo PInfo; 1234 1235 if (const auto *IfNode = 1236 dyn_cast_or_null<IfStmt>(CurrBlock->getTerminator().getStmt())) { 1237 const Expr *Cond = IfNode->getCond(); 1238 1239 PInfo = Visitor.getInfo(Cond); 1240 if (!PInfo.isValid() && isa<BinaryOperator>(Cond)) 1241 PInfo = Visitor.getInfo(cast<BinaryOperator>(Cond)->getRHS()); 1242 1243 if (PInfo.isVarTest()) { 1244 CurrStates->setSource(Cond); 1245 FalseStates->setSource(Cond); 1246 splitVarStateForIf(IfNode, PInfo.getVarTest(), CurrStates.get(), 1247 FalseStates.get()); 1248 } else if (PInfo.isBinTest()) { 1249 CurrStates->setSource(PInfo.testSourceNode()); 1250 FalseStates->setSource(PInfo.testSourceNode()); 1251 splitVarStateForIfBinOp(PInfo, CurrStates.get(), FalseStates.get()); 1252 } else { 1253 return false; 1254 } 1255 } else if (const auto *BinOp = 1256 dyn_cast_or_null<BinaryOperator>(CurrBlock->getTerminator().getStmt())) { 1257 PInfo = Visitor.getInfo(BinOp->getLHS()); 1258 if (!PInfo.isVarTest()) { 1259 if ((BinOp = dyn_cast_or_null<BinaryOperator>(BinOp->getLHS()))) { 1260 PInfo = Visitor.getInfo(BinOp->getRHS()); 1261 1262 if (!PInfo.isVarTest()) 1263 return false; 1264 } else { 1265 return false; 1266 } 1267 } 1268 1269 CurrStates->setSource(BinOp); 1270 FalseStates->setSource(BinOp); 1271 1272 const VarTestResult &Test = PInfo.getVarTest(); 1273 ConsumedState VarState = CurrStates->getState(Test.Var); 1274 1275 if (BinOp->getOpcode() == BO_LAnd) { 1276 if (VarState == CS_Unknown) 1277 CurrStates->setState(Test.Var, Test.TestsFor); 1278 else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) 1279 CurrStates->markUnreachable(); 1280 1281 } else if (BinOp->getOpcode() == BO_LOr) { 1282 if (VarState == CS_Unknown) 1283 FalseStates->setState(Test.Var, 1284 invertConsumedUnconsumed(Test.TestsFor)); 1285 else if (VarState == Test.TestsFor) 1286 FalseStates->markUnreachable(); 1287 } 1288 } else { 1289 return false; 1290 } 1291 1292 CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(); 1293 1294 if (*SI) 1295 BlockInfo.addInfo(*SI, std::move(CurrStates)); 1296 else 1297 CurrStates = nullptr; 1298 1299 if (*++SI) 1300 BlockInfo.addInfo(*SI, std::move(FalseStates)); 1301 1302 return true; 1303 } 1304 1305 void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { 1306 const auto *D = dyn_cast_or_null<FunctionDecl>(AC.getDecl()); 1307 if (!D) 1308 return; 1309 1310 CFG *CFGraph = AC.getCFG(); 1311 if (!CFGraph) 1312 return; 1313 1314 determineExpectedReturnState(AC, D); 1315 1316 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>(); 1317 // AC.getCFG()->viewCFG(LangOptions()); 1318 1319 BlockInfo = ConsumedBlockInfo(CFGraph->getNumBlockIDs(), SortedGraph); 1320 1321 CurrStates = llvm::make_unique<ConsumedStateMap>(); 1322 ConsumedStmtVisitor Visitor(*this, CurrStates.get()); 1323 1324 // Add all trackable parameters to the state map. 1325 for (const auto *PI : D->parameters()) 1326 Visitor.VisitParmVarDecl(PI); 1327 1328 // Visit all of the function's basic blocks. 1329 for (const auto *CurrBlock : *SortedGraph) { 1330 if (!CurrStates) 1331 CurrStates = BlockInfo.getInfo(CurrBlock); 1332 1333 if (!CurrStates) { 1334 continue; 1335 } else if (!CurrStates->isReachable()) { 1336 CurrStates = nullptr; 1337 continue; 1338 } 1339 1340 Visitor.reset(CurrStates.get()); 1341 1342 // Visit all of the basic block's statements. 1343 for (const auto &B : *CurrBlock) { 1344 switch (B.getKind()) { 1345 case CFGElement::Statement: 1346 Visitor.Visit(B.castAs<CFGStmt>().getStmt()); 1347 break; 1348 1349 case CFGElement::TemporaryDtor: { 1350 const CFGTemporaryDtor &DTor = B.castAs<CFGTemporaryDtor>(); 1351 const CXXBindTemporaryExpr *BTE = DTor.getBindTemporaryExpr(); 1352 1353 Visitor.checkCallability(PropagationInfo(BTE), 1354 DTor.getDestructorDecl(AC.getASTContext()), 1355 BTE->getExprLoc()); 1356 CurrStates->remove(BTE); 1357 break; 1358 } 1359 1360 case CFGElement::AutomaticObjectDtor: { 1361 const CFGAutomaticObjDtor &DTor = B.castAs<CFGAutomaticObjDtor>(); 1362 SourceLocation Loc = DTor.getTriggerStmt()->getEndLoc(); 1363 const VarDecl *Var = DTor.getVarDecl(); 1364 1365 Visitor.checkCallability(PropagationInfo(Var), 1366 DTor.getDestructorDecl(AC.getASTContext()), 1367 Loc); 1368 break; 1369 } 1370 1371 default: 1372 break; 1373 } 1374 } 1375 1376 // TODO: Handle other forms of branching with precision, including while- 1377 // and for-loops. (Deferred) 1378 if (!splitState(CurrBlock, Visitor)) { 1379 CurrStates->setSource(nullptr); 1380 1381 if (CurrBlock->succ_size() > 1 || 1382 (CurrBlock->succ_size() == 1 && 1383 (*CurrBlock->succ_begin())->pred_size() > 1)) { 1384 1385 auto *RawState = CurrStates.get(); 1386 1387 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 1388 SE = CurrBlock->succ_end(); SI != SE; ++SI) { 1389 if (*SI == nullptr) continue; 1390 1391 if (BlockInfo.isBackEdge(CurrBlock, *SI)) { 1392 BlockInfo.borrowInfo(*SI)->intersectAtLoopHead( 1393 *SI, CurrBlock, RawState, WarningsHandler); 1394 1395 if (BlockInfo.allBackEdgesVisited(CurrBlock, *SI)) 1396 BlockInfo.discardInfo(*SI); 1397 } else { 1398 BlockInfo.addInfo(*SI, RawState, CurrStates); 1399 } 1400 } 1401 1402 CurrStates = nullptr; 1403 } 1404 } 1405 1406 if (CurrBlock == &AC.getCFG()->getExit() && 1407 D->getCallResultType()->isVoidType()) 1408 CurrStates->checkParamsForReturnTypestate(D->getLocation(), 1409 WarningsHandler); 1410 } // End of block iterator. 1411 1412 // Delete the last existing state map. 1413 CurrStates = nullptr; 1414 1415 WarningsHandler.emitDiagnostics(); 1416 } 1417