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