1 //=== AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines analysis_warnings::[Policy,Executor]. 10 // Together they are used by Sema to issue warnings based on inexpensive 11 // static analysis algorithms in libAnalysis. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Sema/AnalysisBasedWarnings.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DynamicRecursiveASTVisitor.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/ExprObjC.h" 24 #include "clang/AST/OperationKinds.h" 25 #include "clang/AST/ParentMap.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/AST/StmtObjC.h" 28 #include "clang/AST/Type.h" 29 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h" 30 #include "clang/Analysis/Analyses/CalledOnceCheck.h" 31 #include "clang/Analysis/Analyses/Consumed.h" 32 #include "clang/Analysis/Analyses/LifetimeSafety.h" 33 #include "clang/Analysis/Analyses/ReachableCode.h" 34 #include "clang/Analysis/Analyses/ThreadSafety.h" 35 #include "clang/Analysis/Analyses/UninitializedValues.h" 36 #include "clang/Analysis/Analyses/UnsafeBufferUsage.h" 37 #include "clang/Analysis/AnalysisDeclContext.h" 38 #include "clang/Analysis/CFG.h" 39 #include "clang/Analysis/CFGStmtMap.h" 40 #include "clang/Analysis/FlowSensitive/DataflowWorklist.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/DiagnosticSema.h" 43 #include "clang/Basic/SourceLocation.h" 44 #include "clang/Basic/SourceManager.h" 45 #include "clang/Lex/Preprocessor.h" 46 #include "clang/Sema/ScopeInfo.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "llvm/ADT/ArrayRef.h" 49 #include "llvm/ADT/BitVector.h" 50 #include "llvm/ADT/DenseMap.h" 51 #include "llvm/ADT/MapVector.h" 52 #include "llvm/ADT/STLFunctionalExtras.h" 53 #include "llvm/ADT/SmallVector.h" 54 #include "llvm/ADT/StringRef.h" 55 #include "llvm/Support/Debug.h" 56 #include <algorithm> 57 #include <deque> 58 #include <iterator> 59 #include <optional> 60 61 using namespace clang; 62 63 //===----------------------------------------------------------------------===// 64 // Unreachable code analysis. 65 //===----------------------------------------------------------------------===// 66 67 namespace { 68 class UnreachableCodeHandler : public reachable_code::Callback { 69 Sema &S; 70 SourceRange PreviousSilenceableCondVal; 71 72 public: 73 UnreachableCodeHandler(Sema &s) : S(s) {} 74 75 void HandleUnreachable(reachable_code::UnreachableKind UK, SourceLocation L, 76 SourceRange SilenceableCondVal, SourceRange R1, 77 SourceRange R2, bool HasFallThroughAttr) override { 78 // If the diagnosed code is `[[fallthrough]];` and 79 // `-Wunreachable-code-fallthrough` is enabled, suppress `code will never 80 // be executed` warning to avoid generating diagnostic twice 81 if (HasFallThroughAttr && 82 !S.getDiagnostics().isIgnored(diag::warn_unreachable_fallthrough_attr, 83 SourceLocation())) 84 return; 85 86 // Avoid reporting multiple unreachable code diagnostics that are 87 // triggered by the same conditional value. 88 if (PreviousSilenceableCondVal.isValid() && 89 SilenceableCondVal.isValid() && 90 PreviousSilenceableCondVal == SilenceableCondVal) 91 return; 92 PreviousSilenceableCondVal = SilenceableCondVal; 93 94 unsigned diag = diag::warn_unreachable; 95 switch (UK) { 96 case reachable_code::UK_Break: 97 diag = diag::warn_unreachable_break; 98 break; 99 case reachable_code::UK_Return: 100 diag = diag::warn_unreachable_return; 101 break; 102 case reachable_code::UK_Loop_Increment: 103 diag = diag::warn_unreachable_loop_increment; 104 break; 105 case reachable_code::UK_Other: 106 break; 107 } 108 109 S.Diag(L, diag) << R1 << R2; 110 111 SourceLocation Open = SilenceableCondVal.getBegin(); 112 if (Open.isValid()) { 113 SourceLocation Close = SilenceableCondVal.getEnd(); 114 Close = S.getLocForEndOfToken(Close); 115 if (Close.isValid()) { 116 S.Diag(Open, diag::note_unreachable_silence) 117 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (") 118 << FixItHint::CreateInsertion(Close, ")"); 119 } 120 } 121 } 122 }; 123 } // anonymous namespace 124 125 /// CheckUnreachable - Check for unreachable code. 126 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) { 127 // As a heuristic prune all diagnostics not in the main file. Currently 128 // the majority of warnings in headers are false positives. These 129 // are largely caused by configuration state, e.g. preprocessor 130 // defined code, etc. 131 // 132 // Note that this is also a performance optimization. Analyzing 133 // headers many times can be expensive. 134 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc())) 135 return; 136 137 UnreachableCodeHandler UC(S); 138 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC); 139 } 140 141 namespace { 142 /// Warn on logical operator errors in CFGBuilder 143 class LogicalErrorHandler : public CFGCallback { 144 Sema &S; 145 146 public: 147 LogicalErrorHandler(Sema &S) : S(S) {} 148 149 static bool HasMacroID(const Expr *E) { 150 if (E->getExprLoc().isMacroID()) 151 return true; 152 153 // Recurse to children. 154 for (const Stmt *SubStmt : E->children()) 155 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt)) 156 if (HasMacroID(SubExpr)) 157 return true; 158 159 return false; 160 } 161 162 void logicAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override { 163 if (HasMacroID(B)) 164 return; 165 166 unsigned DiagID = isAlwaysTrue 167 ? diag::warn_tautological_negation_or_compare 168 : diag::warn_tautological_negation_and_compare; 169 SourceRange DiagRange = B->getSourceRange(); 170 S.Diag(B->getExprLoc(), DiagID) << DiagRange; 171 } 172 173 void compareAlwaysTrue(const BinaryOperator *B, 174 bool isAlwaysTrueOrFalse) override { 175 if (HasMacroID(B)) 176 return; 177 178 SourceRange DiagRange = B->getSourceRange(); 179 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison) 180 << DiagRange << isAlwaysTrueOrFalse; 181 } 182 183 void compareBitwiseEquality(const BinaryOperator *B, 184 bool isAlwaysTrue) override { 185 if (HasMacroID(B)) 186 return; 187 188 SourceRange DiagRange = B->getSourceRange(); 189 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always) 190 << DiagRange << isAlwaysTrue; 191 } 192 193 void compareBitwiseOr(const BinaryOperator *B) override { 194 if (HasMacroID(B)) 195 return; 196 197 SourceRange DiagRange = B->getSourceRange(); 198 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_or) << DiagRange; 199 } 200 201 static bool hasActiveDiagnostics(DiagnosticsEngine &Diags, 202 SourceLocation Loc) { 203 return !Diags.isIgnored(diag::warn_tautological_overlap_comparison, Loc) || 204 !Diags.isIgnored(diag::warn_comparison_bitwise_or, Loc) || 205 !Diags.isIgnored(diag::warn_tautological_negation_and_compare, Loc); 206 } 207 }; 208 } // anonymous namespace 209 210 //===----------------------------------------------------------------------===// 211 // Check for infinite self-recursion in functions 212 //===----------------------------------------------------------------------===// 213 214 // Returns true if the function is called anywhere within the CFGBlock. 215 // For member functions, the additional condition of being call from the 216 // this pointer is required. 217 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) { 218 // Process all the Stmt's in this block to find any calls to FD. 219 for (const auto &B : Block) { 220 if (B.getKind() != CFGElement::Statement) 221 continue; 222 223 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt()); 224 if (!CE || !CE->getCalleeDecl() || 225 CE->getCalleeDecl()->getCanonicalDecl() != FD) 226 continue; 227 228 // Skip function calls which are qualified with a templated class. 229 if (const DeclRefExpr *DRE = 230 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) { 231 if (NestedNameSpecifier *NNS = DRE->getQualifier()) { 232 if (NNS->getKind() == NestedNameSpecifier::TypeSpec && 233 isa<TemplateSpecializationType>(NNS->getAsType())) { 234 continue; 235 } 236 } 237 } 238 239 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE); 240 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) || 241 !MCE->getMethodDecl()->isVirtual()) 242 return true; 243 } 244 return false; 245 } 246 247 // Returns true if every path from the entry block passes through a call to FD. 248 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) { 249 llvm::SmallPtrSet<CFGBlock *, 16> Visited; 250 llvm::SmallVector<CFGBlock *, 16> WorkList; 251 // Keep track of whether we found at least one recursive path. 252 bool foundRecursion = false; 253 254 const unsigned ExitID = cfg->getExit().getBlockID(); 255 256 // Seed the work list with the entry block. 257 WorkList.push_back(&cfg->getEntry()); 258 259 while (!WorkList.empty()) { 260 CFGBlock *Block = WorkList.pop_back_val(); 261 262 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) { 263 if (CFGBlock *SuccBlock = *I) { 264 if (!Visited.insert(SuccBlock).second) 265 continue; 266 267 // Found a path to the exit node without a recursive call. 268 if (ExitID == SuccBlock->getBlockID()) 269 return false; 270 271 // If the successor block contains a recursive call, end analysis there. 272 if (hasRecursiveCallInPath(FD, *SuccBlock)) { 273 foundRecursion = true; 274 continue; 275 } 276 277 WorkList.push_back(SuccBlock); 278 } 279 } 280 } 281 return foundRecursion; 282 } 283 284 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD, 285 const Stmt *Body, AnalysisDeclContext &AC) { 286 FD = FD->getCanonicalDecl(); 287 288 // Only run on non-templated functions and non-templated members of 289 // templated classes. 290 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate && 291 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization) 292 return; 293 294 CFG *cfg = AC.getCFG(); 295 if (!cfg) return; 296 297 // If the exit block is unreachable, skip processing the function. 298 if (cfg->getExit().pred_empty()) 299 return; 300 301 // Emit diagnostic if a recursive function call is detected for all paths. 302 if (checkForRecursiveFunctionCall(FD, cfg)) 303 S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function); 304 } 305 306 //===----------------------------------------------------------------------===// 307 // Check for throw in a non-throwing function. 308 //===----------------------------------------------------------------------===// 309 310 /// Determine whether an exception thrown by E, unwinding from ThrowBlock, 311 /// can reach ExitBlock. 312 static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock, 313 CFG *Body) { 314 SmallVector<CFGBlock *, 16> Stack; 315 llvm::BitVector Queued(Body->getNumBlockIDs()); 316 317 Stack.push_back(&ThrowBlock); 318 Queued[ThrowBlock.getBlockID()] = true; 319 320 while (!Stack.empty()) { 321 CFGBlock &UnwindBlock = *Stack.pop_back_val(); 322 323 for (auto &Succ : UnwindBlock.succs()) { 324 if (!Succ.isReachable() || Queued[Succ->getBlockID()]) 325 continue; 326 327 if (Succ->getBlockID() == Body->getExit().getBlockID()) 328 return true; 329 330 if (auto *Catch = 331 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) { 332 QualType Caught = Catch->getCaughtType(); 333 if (Caught.isNull() || // catch (...) catches everything 334 !E->getSubExpr() || // throw; is considered cuaght by any handler 335 S.handlerCanCatch(Caught, E->getSubExpr()->getType())) 336 // Exception doesn't escape via this path. 337 break; 338 } else { 339 Stack.push_back(Succ); 340 Queued[Succ->getBlockID()] = true; 341 } 342 } 343 } 344 345 return false; 346 } 347 348 static void visitReachableThrows( 349 CFG *BodyCFG, 350 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) { 351 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs()); 352 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable); 353 for (CFGBlock *B : *BodyCFG) { 354 if (!Reachable[B->getBlockID()]) 355 continue; 356 for (CFGElement &E : *B) { 357 std::optional<CFGStmt> S = E.getAs<CFGStmt>(); 358 if (!S) 359 continue; 360 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt())) 361 Visit(Throw, *B); 362 } 363 } 364 } 365 366 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc, 367 const FunctionDecl *FD) { 368 if (!S.getSourceManager().isInSystemHeader(OpLoc) && 369 FD->getTypeSourceInfo()) { 370 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD; 371 if (S.getLangOpts().CPlusPlus11 && 372 (isa<CXXDestructorDecl>(FD) || 373 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete || 374 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) { 375 if (const auto *Ty = FD->getTypeSourceInfo()->getType()-> 376 getAs<FunctionProtoType>()) 377 S.Diag(FD->getLocation(), diag::note_throw_in_dtor) 378 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec() 379 << FD->getExceptionSpecSourceRange(); 380 } else 381 S.Diag(FD->getLocation(), diag::note_throw_in_function) 382 << FD->getExceptionSpecSourceRange(); 383 } 384 } 385 386 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD, 387 AnalysisDeclContext &AC) { 388 CFG *BodyCFG = AC.getCFG(); 389 if (!BodyCFG) 390 return; 391 if (BodyCFG->getExit().pred_empty()) 392 return; 393 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) { 394 if (throwEscapes(S, Throw, Block, BodyCFG)) 395 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD); 396 }); 397 } 398 399 static bool isNoexcept(const FunctionDecl *FD) { 400 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 401 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>()) 402 return true; 403 return false; 404 } 405 406 /// Checks if the given expression is a reference to a function with 407 /// 'noreturn' attribute. 408 static bool isReferenceToNoReturn(const Expr *E) { 409 if (auto *DRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 410 if (auto *FD = dyn_cast<FunctionDecl>(DRef->getDecl())) 411 return FD->isNoReturn(); 412 return false; 413 } 414 415 /// Checks if the given variable, which is assumed to be a function pointer, is 416 /// initialized with a function having 'noreturn' attribute. 417 static bool isInitializedWithNoReturn(const VarDecl *VD) { 418 if (const Expr *Init = VD->getInit()) { 419 if (auto *ListInit = dyn_cast<InitListExpr>(Init); 420 ListInit && ListInit->getNumInits() > 0) 421 Init = ListInit->getInit(0); 422 return isReferenceToNoReturn(Init); 423 } 424 return false; 425 } 426 427 namespace { 428 429 /// Looks for statements, that can define value of the given variable. 430 struct TransferFunctions : public StmtVisitor<TransferFunctions> { 431 const VarDecl *Var; 432 std::optional<bool> AllValuesAreNoReturn; 433 434 TransferFunctions(const VarDecl *VD) : Var(VD) {} 435 436 void reset() { AllValuesAreNoReturn = std::nullopt; } 437 438 void VisitDeclStmt(DeclStmt *DS) { 439 for (auto *DI : DS->decls()) 440 if (auto *VD = dyn_cast<VarDecl>(DI)) 441 if (VarDecl *Def = VD->getDefinition()) 442 if (Def == Var) 443 AllValuesAreNoReturn = isInitializedWithNoReturn(Def); 444 } 445 446 void VisitUnaryOperator(UnaryOperator *UO) { 447 if (UO->getOpcode() == UO_AddrOf) { 448 if (auto *DRef = 449 dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParenCasts())) 450 if (DRef->getDecl() == Var) 451 AllValuesAreNoReturn = false; 452 } 453 } 454 455 void VisitBinaryOperator(BinaryOperator *BO) { 456 if (BO->getOpcode() == BO_Assign) 457 if (auto *DRef = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParenCasts())) 458 if (DRef->getDecl() == Var) 459 AllValuesAreNoReturn = isReferenceToNoReturn(BO->getRHS()); 460 } 461 462 void VisitCallExpr(CallExpr *CE) { 463 for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; 464 ++I) { 465 const Expr *Arg = *I; 466 if (Arg->isGLValue() && !Arg->getType().isConstQualified()) 467 if (auto *DRef = dyn_cast<DeclRefExpr>(Arg->IgnoreParenCasts())) 468 if (auto VD = dyn_cast<VarDecl>(DRef->getDecl())) 469 if (VD->getDefinition() == Var) 470 AllValuesAreNoReturn = false; 471 } 472 } 473 }; 474 } // namespace 475 476 // Checks if all possible values of the given variable are functions with 477 // 'noreturn' attribute. 478 static bool areAllValuesNoReturn(const VarDecl *VD, const CFGBlock &VarBlk, 479 AnalysisDeclContext &AC) { 480 // The set of possible values of a constant variable is determined by 481 // its initializer, unless it is a function parameter. 482 if (!isa<ParmVarDecl>(VD) && VD->getType().isConstant(AC.getASTContext())) { 483 if (const VarDecl *Def = VD->getDefinition()) 484 return isInitializedWithNoReturn(Def); 485 return false; 486 } 487 488 // In multithreaded environment the value of a global variable may be changed 489 // asynchronously. 490 if (!VD->getDeclContext()->isFunctionOrMethod()) 491 return false; 492 493 // Check the condition "all values are noreturn". It is satisfied if the 494 // variable is set to "noreturn" value in the current block or all its 495 // predecessors satisfies the condition. 496 using MapTy = llvm::DenseMap<const CFGBlock *, std::optional<bool>>; 497 using ValueTy = MapTy::value_type; 498 MapTy BlocksToCheck; 499 BlocksToCheck[&VarBlk] = std::nullopt; 500 const auto BlockSatisfiesCondition = [](ValueTy Item) { 501 return Item.getSecond().value_or(false); 502 }; 503 504 TransferFunctions TF(VD); 505 BackwardDataflowWorklist Worklist(*AC.getCFG(), AC); 506 llvm::DenseSet<const CFGBlock *> Visited; 507 Worklist.enqueueBlock(&VarBlk); 508 while (const CFGBlock *B = Worklist.dequeue()) { 509 if (Visited.contains(B)) 510 continue; 511 Visited.insert(B); 512 // First check the current block. 513 for (CFGBlock::const_reverse_iterator ri = B->rbegin(), re = B->rend(); 514 ri != re; ++ri) { 515 if (std::optional<CFGStmt> cs = ri->getAs<CFGStmt>()) { 516 const Stmt *S = cs->getStmt(); 517 TF.reset(); 518 TF.Visit(const_cast<Stmt *>(S)); 519 if (TF.AllValuesAreNoReturn) { 520 if (!TF.AllValuesAreNoReturn.value()) 521 return false; 522 BlocksToCheck[B] = true; 523 break; 524 } 525 } 526 } 527 528 // If all checked blocks satisfy the condition, the check is finished. 529 if (std::all_of(BlocksToCheck.begin(), BlocksToCheck.end(), 530 BlockSatisfiesCondition)) 531 return true; 532 533 // If this block does not contain the variable definition, check 534 // its predecessors. 535 if (!BlocksToCheck[B]) { 536 Worklist.enqueuePredecessors(B); 537 BlocksToCheck.erase(B); 538 for (const auto &PredBlk : B->preds()) 539 if (!BlocksToCheck.contains(PredBlk)) 540 BlocksToCheck[PredBlk] = std::nullopt; 541 } 542 } 543 544 return false; 545 } 546 547 //===----------------------------------------------------------------------===// 548 // Check for missing return value. 549 //===----------------------------------------------------------------------===// 550 551 enum ControlFlowKind { 552 UnknownFallThrough, 553 NeverFallThrough, 554 MaybeFallThrough, 555 AlwaysFallThrough, 556 NeverFallThroughOrReturn 557 }; 558 559 /// CheckFallThrough - Check that we don't fall off the end of a 560 /// Statement that should return a value. 561 /// 562 /// \returns AlwaysFallThrough iff we always fall off the end of the statement, 563 /// MaybeFallThrough iff we might or might not fall off the end, 564 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or 565 /// return. We assume NeverFallThrough iff we never fall off the end of the 566 /// statement but we may return. We assume that functions not marked noreturn 567 /// will return. 568 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) { 569 CFG *cfg = AC.getCFG(); 570 if (!cfg) return UnknownFallThrough; 571 572 // The CFG leaves in dead things, and we don't want the dead code paths to 573 // confuse us, so we mark all live things first. 574 llvm::BitVector live(cfg->getNumBlockIDs()); 575 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(), 576 live); 577 578 bool AddEHEdges = AC.getAddEHEdges(); 579 if (!AddEHEdges && count != cfg->getNumBlockIDs()) 580 // When there are things remaining dead, and we didn't add EH edges 581 // from CallExprs to the catch clauses, we have to go back and 582 // mark them as live. 583 for (const auto *B : *cfg) { 584 if (!live[B->getBlockID()]) { 585 if (B->pred_begin() == B->pred_end()) { 586 const Stmt *Term = B->getTerminatorStmt(); 587 if (isa_and_nonnull<CXXTryStmt>(Term)) 588 // When not adding EH edges from calls, catch clauses 589 // can otherwise seem dead. Avoid noting them as dead. 590 count += reachable_code::ScanReachableFromBlock(B, live); 591 continue; 592 } 593 } 594 } 595 596 // Now we know what is live, we check the live precessors of the exit block 597 // and look for fall through paths, being careful to ignore normal returns, 598 // and exceptional paths. 599 bool HasLiveReturn = false; 600 bool HasFakeEdge = false; 601 bool HasPlainEdge = false; 602 bool HasAbnormalEdge = false; 603 604 // Ignore default cases that aren't likely to be reachable because all 605 // enums in a switch(X) have explicit case statements. 606 CFGBlock::FilterOptions FO; 607 FO.IgnoreDefaultsWithCoveredEnums = 1; 608 609 for (CFGBlock::filtered_pred_iterator I = 610 cfg->getExit().filtered_pred_start_end(FO); 611 I.hasMore(); ++I) { 612 const CFGBlock &B = **I; 613 if (!live[B.getBlockID()]) 614 continue; 615 616 // Skip blocks which contain an element marked as no-return. They don't 617 // represent actually viable edges into the exit block, so mark them as 618 // abnormal. 619 if (B.hasNoReturnElement()) { 620 HasAbnormalEdge = true; 621 continue; 622 } 623 624 // Destructors can appear after the 'return' in the CFG. This is 625 // normal. We need to look pass the destructors for the return 626 // statement (if it exists). 627 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend(); 628 629 for ( ; ri != re ; ++ri) 630 if (ri->getAs<CFGStmt>()) 631 break; 632 633 // No more CFGElements in the block? 634 if (ri == re) { 635 const Stmt *Term = B.getTerminatorStmt(); 636 if (Term && (isa<CXXTryStmt>(Term) || isa<ObjCAtTryStmt>(Term))) { 637 HasAbnormalEdge = true; 638 continue; 639 } 640 // A labeled empty statement, or the entry block... 641 HasPlainEdge = true; 642 continue; 643 } 644 645 CFGStmt CS = ri->castAs<CFGStmt>(); 646 const Stmt *S = CS.getStmt(); 647 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) { 648 HasLiveReturn = true; 649 continue; 650 } 651 if (isa<ObjCAtThrowStmt>(S)) { 652 HasFakeEdge = true; 653 continue; 654 } 655 if (isa<CXXThrowExpr>(S)) { 656 HasFakeEdge = true; 657 continue; 658 } 659 if (isa<MSAsmStmt>(S)) { 660 // TODO: Verify this is correct. 661 HasFakeEdge = true; 662 HasLiveReturn = true; 663 continue; 664 } 665 if (isa<CXXTryStmt>(S)) { 666 HasAbnormalEdge = true; 667 continue; 668 } 669 if (!llvm::is_contained(B.succs(), &cfg->getExit())) { 670 HasAbnormalEdge = true; 671 continue; 672 } 673 if (auto *Call = dyn_cast<CallExpr>(S)) { 674 const Expr *Callee = Call->getCallee(); 675 if (Callee->getType()->isPointerType()) 676 if (auto *DeclRef = 677 dyn_cast<DeclRefExpr>(Callee->IgnoreParenImpCasts())) 678 if (auto *VD = dyn_cast<VarDecl>(DeclRef->getDecl())) 679 if (areAllValuesNoReturn(VD, B, AC)) { 680 HasAbnormalEdge = true; 681 continue; 682 } 683 } 684 685 HasPlainEdge = true; 686 } 687 if (!HasPlainEdge) { 688 if (HasLiveReturn) 689 return NeverFallThrough; 690 return NeverFallThroughOrReturn; 691 } 692 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn) 693 return MaybeFallThrough; 694 // This says AlwaysFallThrough for calls to functions that are not marked 695 // noreturn, that don't return. If people would like this warning to be more 696 // accurate, such functions should be marked as noreturn. 697 return AlwaysFallThrough; 698 } 699 700 namespace { 701 702 struct CheckFallThroughDiagnostics { 703 unsigned diag_FallThrough_HasNoReturn = 0; 704 unsigned diag_FallThrough_ReturnsNonVoid = 0; 705 unsigned diag_NeverFallThroughOrReturn = 0; 706 unsigned FunKind; // TODO: use diag::FalloffFunctionKind 707 SourceLocation FuncLoc; 708 709 static CheckFallThroughDiagnostics MakeForFunction(Sema &S, 710 const Decl *Func) { 711 CheckFallThroughDiagnostics D; 712 D.FuncLoc = Func->getLocation(); 713 D.diag_FallThrough_HasNoReturn = diag::warn_noreturn_has_return_expr; 714 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid; 715 716 // Don't suggest that virtual functions be marked "noreturn", since they 717 // might be overridden by non-noreturn functions. 718 bool isVirtualMethod = false; 719 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) 720 isVirtualMethod = Method->isVirtual(); 721 722 // Don't suggest that template instantiations be marked "noreturn" 723 bool isTemplateInstantiation = false; 724 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) { 725 isTemplateInstantiation = Function->isTemplateInstantiation(); 726 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C99 && 727 Function->isMain()) { 728 D.diag_FallThrough_ReturnsNonVoid = diag::ext_main_no_return; 729 } 730 } 731 732 if (!isVirtualMethod && !isTemplateInstantiation) 733 D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function; 734 735 D.FunKind = diag::FalloffFunctionKind::Function; 736 return D; 737 } 738 739 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) { 740 CheckFallThroughDiagnostics D; 741 D.FuncLoc = Func->getLocation(); 742 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid; 743 D.FunKind = diag::FalloffFunctionKind::Coroutine; 744 return D; 745 } 746 747 static CheckFallThroughDiagnostics MakeForBlock() { 748 CheckFallThroughDiagnostics D; 749 D.diag_FallThrough_HasNoReturn = diag::err_noreturn_has_return_expr; 750 D.diag_FallThrough_ReturnsNonVoid = diag::err_falloff_nonvoid; 751 D.FunKind = diag::FalloffFunctionKind::Block; 752 return D; 753 } 754 755 static CheckFallThroughDiagnostics MakeForLambda() { 756 CheckFallThroughDiagnostics D; 757 D.diag_FallThrough_HasNoReturn = diag::err_noreturn_has_return_expr; 758 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid; 759 D.FunKind = diag::FalloffFunctionKind::Lambda; 760 return D; 761 } 762 763 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid, 764 bool HasNoReturn) const { 765 if (FunKind == diag::FalloffFunctionKind::Function) { 766 return (ReturnsVoid || 767 D.isIgnored(diag::warn_falloff_nonvoid, FuncLoc)) && 768 (!HasNoReturn || 769 D.isIgnored(diag::warn_noreturn_has_return_expr, FuncLoc)) && 770 (!ReturnsVoid || 771 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc)); 772 } 773 if (FunKind == diag::FalloffFunctionKind::Coroutine) { 774 return (ReturnsVoid || 775 D.isIgnored(diag::warn_falloff_nonvoid, FuncLoc)) && 776 (!HasNoReturn); 777 } 778 // For blocks / lambdas. 779 return ReturnsVoid && !HasNoReturn; 780 } 781 }; 782 783 } // anonymous namespace 784 785 /// CheckFallThroughForBody - Check that we don't fall off the end of a 786 /// function that should return a value. Check that we don't fall off the end 787 /// of a noreturn function. We assume that functions and blocks not marked 788 /// noreturn will return. 789 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, 790 QualType BlockType, 791 const CheckFallThroughDiagnostics &CD, 792 AnalysisDeclContext &AC) { 793 794 bool ReturnsVoid = false; 795 bool HasNoReturn = false; 796 797 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 798 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body)) 799 ReturnsVoid = CBody->getFallthroughHandler() != nullptr; 800 else 801 ReturnsVoid = FD->getReturnType()->isVoidType(); 802 HasNoReturn = FD->isNoReturn() || FD->hasAttr<InferredNoReturnAttr>(); 803 } 804 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 805 ReturnsVoid = MD->getReturnType()->isVoidType(); 806 HasNoReturn = MD->hasAttr<NoReturnAttr>(); 807 } 808 else if (isa<BlockDecl>(D)) { 809 if (const FunctionType *FT = 810 BlockType->getPointeeType()->getAs<FunctionType>()) { 811 if (FT->getReturnType()->isVoidType()) 812 ReturnsVoid = true; 813 if (FT->getNoReturnAttr()) 814 HasNoReturn = true; 815 } 816 } 817 818 DiagnosticsEngine &Diags = S.getDiagnostics(); 819 820 // Short circuit for compilation speed. 821 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn)) 822 return; 823 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc(); 824 825 // cpu_dispatch functions permit empty function bodies for ICC compatibility. 826 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion()) 827 return; 828 829 // Either in a function body compound statement, or a function-try-block. 830 switch (int FallThroughType = CheckFallThrough(AC)) { 831 case UnknownFallThrough: 832 break; 833 834 case MaybeFallThrough: 835 case AlwaysFallThrough: 836 if (HasNoReturn) { 837 if (CD.diag_FallThrough_HasNoReturn) 838 S.Diag(RBrace, CD.diag_FallThrough_HasNoReturn) << CD.FunKind; 839 } else if (!ReturnsVoid && CD.diag_FallThrough_ReturnsNonVoid) { 840 // If the final statement is a call to an always-throwing function, 841 // don't warn about the fall-through. 842 if (D->getAsFunction()) { 843 if (const auto *CS = dyn_cast<CompoundStmt>(Body); 844 CS && !CS->body_empty()) { 845 const Stmt *LastStmt = CS->body_back(); 846 // Unwrap ExprWithCleanups if necessary. 847 if (const auto *EWC = dyn_cast<ExprWithCleanups>(LastStmt)) { 848 LastStmt = EWC->getSubExpr(); 849 } 850 if (const auto *CE = dyn_cast<CallExpr>(LastStmt)) { 851 if (const FunctionDecl *Callee = CE->getDirectCallee(); 852 Callee && Callee->hasAttr<InferredNoReturnAttr>()) { 853 return; // Don't warn about fall-through. 854 } 855 } 856 // Direct throw. 857 if (isa<CXXThrowExpr>(LastStmt)) { 858 return; // Don't warn about fall-through. 859 } 860 } 861 } 862 bool NotInAllControlPaths = FallThroughType == MaybeFallThrough; 863 S.Diag(RBrace, CD.diag_FallThrough_ReturnsNonVoid) 864 << CD.FunKind << NotInAllControlPaths; 865 } 866 break; 867 case NeverFallThroughOrReturn: 868 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) { 869 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 870 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD; 871 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 872 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD; 873 } else { 874 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn); 875 } 876 } 877 break; 878 case NeverFallThrough: 879 break; 880 } 881 } 882 883 //===----------------------------------------------------------------------===// 884 // -Wuninitialized 885 //===----------------------------------------------------------------------===// 886 887 namespace { 888 /// ContainsReference - A visitor class to search for references to 889 /// a particular declaration (the needle) within any evaluated component of an 890 /// expression (recursively). 891 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> { 892 bool FoundReference; 893 const DeclRefExpr *Needle; 894 895 public: 896 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited; 897 898 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle) 899 : Inherited(Context), FoundReference(false), Needle(Needle) {} 900 901 void VisitExpr(const Expr *E) { 902 // Stop evaluating if we already have a reference. 903 if (FoundReference) 904 return; 905 906 Inherited::VisitExpr(E); 907 } 908 909 void VisitDeclRefExpr(const DeclRefExpr *E) { 910 if (E == Needle) 911 FoundReference = true; 912 else 913 Inherited::VisitDeclRefExpr(E); 914 } 915 916 bool doesContainReference() const { return FoundReference; } 917 }; 918 } // anonymous namespace 919 920 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) { 921 QualType VariableTy = VD->getType().getCanonicalType(); 922 if (VariableTy->isBlockPointerType() && 923 !VD->hasAttr<BlocksAttr>()) { 924 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) 925 << VD->getDeclName() 926 << FixItHint::CreateInsertion(VD->getLocation(), "__block "); 927 return true; 928 } 929 930 // Don't issue a fixit if there is already an initializer. 931 if (VD->getInit()) 932 return false; 933 934 // Don't suggest a fixit inside macros. 935 if (VD->getEndLoc().isMacroID()) 936 return false; 937 938 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); 939 940 // Suggest possible initialization (if any). 941 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 942 if (Init.empty()) 943 return false; 944 945 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName() 946 << FixItHint::CreateInsertion(Loc, Init); 947 return true; 948 } 949 950 /// Create a fixit to remove an if-like statement, on the assumption that its 951 /// condition is CondVal. 952 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then, 953 const Stmt *Else, bool CondVal, 954 FixItHint &Fixit1, FixItHint &Fixit2) { 955 if (CondVal) { 956 // If condition is always true, remove all but the 'then'. 957 Fixit1 = FixItHint::CreateRemoval( 958 CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc())); 959 if (Else) { 960 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc()); 961 Fixit2 = 962 FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc())); 963 } 964 } else { 965 // If condition is always false, remove all but the 'else'. 966 if (Else) 967 Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange( 968 If->getBeginLoc(), Else->getBeginLoc())); 969 else 970 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange()); 971 } 972 } 973 974 /// DiagUninitUse -- Helper function to produce a diagnostic for an 975 /// uninitialized use of a variable. 976 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use, 977 bool IsCapturedByBlock) { 978 bool Diagnosed = false; 979 980 switch (Use.getKind()) { 981 case UninitUse::Always: 982 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var) 983 << VD->getDeclName() << IsCapturedByBlock 984 << Use.getUser()->getSourceRange(); 985 return; 986 987 case UninitUse::AfterDecl: 988 case UninitUse::AfterCall: 989 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var) 990 << VD->getDeclName() << IsCapturedByBlock 991 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5) 992 << const_cast<DeclContext*>(VD->getLexicalDeclContext()) 993 << VD->getSourceRange(); 994 S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use) 995 << IsCapturedByBlock << Use.getUser()->getSourceRange(); 996 return; 997 998 case UninitUse::Maybe: 999 case UninitUse::Sometimes: 1000 // Carry on to report sometimes-uninitialized branches, if possible, 1001 // or a 'may be used uninitialized' diagnostic otherwise. 1002 break; 1003 } 1004 1005 // Diagnose each branch which leads to a sometimes-uninitialized use. 1006 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end(); 1007 I != E; ++I) { 1008 assert(Use.getKind() == UninitUse::Sometimes); 1009 1010 const Expr *User = Use.getUser(); 1011 const Stmt *Term = I->Terminator; 1012 1013 // Information used when building the diagnostic. 1014 unsigned DiagKind; 1015 StringRef Str; 1016 SourceRange Range; 1017 1018 // FixIts to suppress the diagnostic by removing the dead condition. 1019 // For all binary terminators, branch 0 is taken if the condition is true, 1020 // and branch 1 is taken if the condition is false. 1021 int RemoveDiagKind = -1; 1022 const char *FixitStr = 1023 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false") 1024 : (I->Output ? "1" : "0"); 1025 FixItHint Fixit1, Fixit2; 1026 1027 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) { 1028 default: 1029 // Don't know how to report this. Just fall back to 'may be used 1030 // uninitialized'. FIXME: Can this happen? 1031 continue; 1032 1033 // "condition is true / condition is false". 1034 case Stmt::IfStmtClass: { 1035 const IfStmt *IS = cast<IfStmt>(Term); 1036 DiagKind = 0; 1037 Str = "if"; 1038 Range = IS->getCond()->getSourceRange(); 1039 RemoveDiagKind = 0; 1040 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(), 1041 I->Output, Fixit1, Fixit2); 1042 break; 1043 } 1044 case Stmt::ConditionalOperatorClass: { 1045 const ConditionalOperator *CO = cast<ConditionalOperator>(Term); 1046 DiagKind = 0; 1047 Str = "?:"; 1048 Range = CO->getCond()->getSourceRange(); 1049 RemoveDiagKind = 0; 1050 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(), 1051 I->Output, Fixit1, Fixit2); 1052 break; 1053 } 1054 case Stmt::BinaryOperatorClass: { 1055 const BinaryOperator *BO = cast<BinaryOperator>(Term); 1056 if (!BO->isLogicalOp()) 1057 continue; 1058 DiagKind = 0; 1059 Str = BO->getOpcodeStr(); 1060 Range = BO->getLHS()->getSourceRange(); 1061 RemoveDiagKind = 0; 1062 if ((BO->getOpcode() == BO_LAnd && I->Output) || 1063 (BO->getOpcode() == BO_LOr && !I->Output)) 1064 // true && y -> y, false || y -> y. 1065 Fixit1 = FixItHint::CreateRemoval( 1066 SourceRange(BO->getBeginLoc(), BO->getOperatorLoc())); 1067 else 1068 // false && y -> false, true || y -> true. 1069 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr); 1070 break; 1071 } 1072 1073 // "loop is entered / loop is exited". 1074 case Stmt::WhileStmtClass: 1075 DiagKind = 1; 1076 Str = "while"; 1077 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange(); 1078 RemoveDiagKind = 1; 1079 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); 1080 break; 1081 case Stmt::ForStmtClass: 1082 DiagKind = 1; 1083 Str = "for"; 1084 Range = cast<ForStmt>(Term)->getCond()->getSourceRange(); 1085 RemoveDiagKind = 1; 1086 if (I->Output) 1087 Fixit1 = FixItHint::CreateRemoval(Range); 1088 else 1089 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); 1090 break; 1091 case Stmt::CXXForRangeStmtClass: 1092 if (I->Output == 1) { 1093 // The use occurs if a range-based for loop's body never executes. 1094 // That may be impossible, and there's no syntactic fix for this, 1095 // so treat it as a 'may be uninitialized' case. 1096 continue; 1097 } 1098 DiagKind = 1; 1099 Str = "for"; 1100 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange(); 1101 break; 1102 1103 // "condition is true / loop is exited". 1104 case Stmt::DoStmtClass: 1105 DiagKind = 2; 1106 Str = "do"; 1107 Range = cast<DoStmt>(Term)->getCond()->getSourceRange(); 1108 RemoveDiagKind = 1; 1109 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); 1110 break; 1111 1112 // "switch case is taken". 1113 case Stmt::CaseStmtClass: 1114 DiagKind = 3; 1115 Str = "case"; 1116 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange(); 1117 break; 1118 case Stmt::DefaultStmtClass: 1119 DiagKind = 3; 1120 Str = "default"; 1121 Range = cast<DefaultStmt>(Term)->getDefaultLoc(); 1122 break; 1123 } 1124 1125 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var) 1126 << VD->getDeclName() << IsCapturedByBlock << DiagKind 1127 << Str << I->Output << Range; 1128 S.Diag(User->getBeginLoc(), diag::note_uninit_var_use) 1129 << IsCapturedByBlock << User->getSourceRange(); 1130 if (RemoveDiagKind != -1) 1131 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond) 1132 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2; 1133 1134 Diagnosed = true; 1135 } 1136 1137 if (!Diagnosed) 1138 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var) 1139 << VD->getDeclName() << IsCapturedByBlock 1140 << Use.getUser()->getSourceRange(); 1141 } 1142 1143 /// Diagnose uninitialized const reference usages. 1144 static bool DiagnoseUninitializedConstRefUse(Sema &S, const VarDecl *VD, 1145 const UninitUse &Use) { 1146 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_const_reference) 1147 << VD->getDeclName() << Use.getUser()->getSourceRange(); 1148 return !S.getDiagnostics().isLastDiagnosticIgnored(); 1149 } 1150 1151 /// Diagnose uninitialized const pointer usages. 1152 static bool DiagnoseUninitializedConstPtrUse(Sema &S, const VarDecl *VD, 1153 const UninitUse &Use) { 1154 S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_const_pointer) 1155 << VD->getDeclName() << Use.getUser()->getSourceRange(); 1156 return !S.getDiagnostics().isLastDiagnosticIgnored(); 1157 } 1158 1159 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an 1160 /// uninitialized variable. This manages the different forms of diagnostic 1161 /// emitted for particular types of uses. Returns true if the use was diagnosed 1162 /// as a warning. If a particular use is one we omit warnings for, returns 1163 /// false. 1164 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD, 1165 const UninitUse &Use, 1166 bool alwaysReportSelfInit = false) { 1167 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) { 1168 // Inspect the initializer of the variable declaration which is 1169 // being referenced prior to its initialization. We emit 1170 // specialized diagnostics for self-initialization, and we 1171 // specifically avoid warning about self references which take the 1172 // form of: 1173 // 1174 // int x = x; 1175 // 1176 // This is used to indicate to GCC that 'x' is intentionally left 1177 // uninitialized. Proven code paths which access 'x' in 1178 // an uninitialized state after this will still warn. 1179 if (const Expr *Initializer = VD->getInit()) { 1180 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts()) 1181 return false; 1182 1183 ContainsReference CR(S.Context, DRE); 1184 CR.Visit(Initializer); 1185 if (CR.doesContainReference()) { 1186 S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init) 1187 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange(); 1188 return !S.getDiagnostics().isLastDiagnosticIgnored(); 1189 } 1190 } 1191 1192 DiagUninitUse(S, VD, Use, false); 1193 } else { 1194 const BlockExpr *BE = cast<BlockExpr>(Use.getUser()); 1195 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>()) 1196 S.Diag(BE->getBeginLoc(), 1197 diag::warn_uninit_byref_blockvar_captured_by_block) 1198 << VD->getDeclName() 1199 << VD->getType().getQualifiers().hasObjCLifetime(); 1200 else 1201 DiagUninitUse(S, VD, Use, true); 1202 } 1203 1204 // Report where the variable was declared when the use wasn't within 1205 // the initializer of that declaration & we didn't already suggest 1206 // an initialization fixit. 1207 if (!SuggestInitializationFixit(S, VD)) 1208 S.Diag(VD->getBeginLoc(), diag::note_var_declared_here) 1209 << VD->getDeclName(); 1210 1211 return !S.getDiagnostics().isLastDiagnosticIgnored(); 1212 } 1213 1214 namespace { 1215 class FallthroughMapper : public DynamicRecursiveASTVisitor { 1216 public: 1217 FallthroughMapper(Sema &S) : FoundSwitchStatements(false), S(S) { 1218 ShouldWalkTypesOfTypeLocs = false; 1219 } 1220 1221 bool foundSwitchStatements() const { return FoundSwitchStatements; } 1222 1223 void markFallthroughVisited(const AttributedStmt *Stmt) { 1224 bool Found = FallthroughStmts.erase(Stmt); 1225 assert(Found); 1226 (void)Found; 1227 } 1228 1229 typedef llvm::SmallPtrSet<const AttributedStmt *, 8> AttrStmts; 1230 1231 const AttrStmts &getFallthroughStmts() const { return FallthroughStmts; } 1232 1233 void fillReachableBlocks(CFG *Cfg) { 1234 assert(ReachableBlocks.empty() && "ReachableBlocks already filled"); 1235 std::deque<const CFGBlock *> BlockQueue; 1236 1237 ReachableBlocks.insert(&Cfg->getEntry()); 1238 BlockQueue.push_back(&Cfg->getEntry()); 1239 // Mark all case blocks reachable to avoid problems with switching on 1240 // constants, covered enums, etc. 1241 // These blocks can contain fall-through annotations, and we don't want to 1242 // issue a warn_fallthrough_attr_unreachable for them. 1243 for (const auto *B : *Cfg) { 1244 const Stmt *L = B->getLabel(); 1245 if (isa_and_nonnull<SwitchCase>(L) && ReachableBlocks.insert(B).second) 1246 BlockQueue.push_back(B); 1247 } 1248 1249 while (!BlockQueue.empty()) { 1250 const CFGBlock *P = BlockQueue.front(); 1251 BlockQueue.pop_front(); 1252 for (const CFGBlock *B : P->succs()) { 1253 if (B && ReachableBlocks.insert(B).second) 1254 BlockQueue.push_back(B); 1255 } 1256 } 1257 } 1258 1259 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt, 1260 bool IsTemplateInstantiation) { 1261 assert(!ReachableBlocks.empty() && "ReachableBlocks empty"); 1262 1263 int UnannotatedCnt = 0; 1264 AnnotatedCnt = 0; 1265 1266 std::deque<const CFGBlock *> BlockQueue(B.pred_begin(), B.pred_end()); 1267 while (!BlockQueue.empty()) { 1268 const CFGBlock *P = BlockQueue.front(); 1269 BlockQueue.pop_front(); 1270 if (!P) 1271 continue; 1272 1273 const Stmt *Term = P->getTerminatorStmt(); 1274 if (isa_and_nonnull<SwitchStmt>(Term)) 1275 continue; // Switch statement, good. 1276 1277 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel()); 1278 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end()) 1279 continue; // Previous case label has no statements, good. 1280 1281 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel()); 1282 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end()) 1283 continue; // Case label is preceded with a normal label, good. 1284 1285 if (!ReachableBlocks.count(P)) { 1286 for (const CFGElement &Elem : llvm::reverse(*P)) { 1287 if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) { 1288 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) { 1289 // Don't issue a warning for an unreachable fallthrough 1290 // attribute in template instantiations as it may not be 1291 // unreachable in all instantiations of the template. 1292 if (!IsTemplateInstantiation) 1293 S.Diag(AS->getBeginLoc(), 1294 diag::warn_unreachable_fallthrough_attr); 1295 markFallthroughVisited(AS); 1296 ++AnnotatedCnt; 1297 break; 1298 } 1299 // Don't care about other unreachable statements. 1300 } 1301 } 1302 // If there are no unreachable statements, this may be a special 1303 // case in CFG: 1304 // case X: { 1305 // A a; // A has a destructor. 1306 // break; 1307 // } 1308 // // <<<< This place is represented by a 'hanging' CFG block. 1309 // case Y: 1310 continue; 1311 } 1312 1313 const Stmt *LastStmt = getLastStmt(*P); 1314 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) { 1315 markFallthroughVisited(AS); 1316 ++AnnotatedCnt; 1317 continue; // Fallthrough annotation, good. 1318 } 1319 1320 if (!LastStmt) { // This block contains no executable statements. 1321 // Traverse its predecessors. 1322 std::copy(P->pred_begin(), P->pred_end(), 1323 std::back_inserter(BlockQueue)); 1324 continue; 1325 } 1326 1327 ++UnannotatedCnt; 1328 } 1329 return !!UnannotatedCnt; 1330 } 1331 1332 bool VisitAttributedStmt(AttributedStmt *S) override { 1333 if (asFallThroughAttr(S)) 1334 FallthroughStmts.insert(S); 1335 return true; 1336 } 1337 1338 bool VisitSwitchStmt(SwitchStmt *S) override { 1339 FoundSwitchStatements = true; 1340 return true; 1341 } 1342 1343 // We don't want to traverse local type declarations. We analyze their 1344 // methods separately. 1345 bool TraverseDecl(Decl *D) override { return true; } 1346 1347 // We analyze lambda bodies separately. Skip them here. 1348 bool TraverseLambdaExpr(LambdaExpr *LE) override { 1349 // Traverse the captures, but not the body. 1350 for (const auto C : zip(LE->captures(), LE->capture_inits())) 1351 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C)); 1352 return true; 1353 } 1354 1355 private: 1356 1357 static const AttributedStmt *asFallThroughAttr(const Stmt *S) { 1358 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) { 1359 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs())) 1360 return AS; 1361 } 1362 return nullptr; 1363 } 1364 1365 static const Stmt *getLastStmt(const CFGBlock &B) { 1366 if (const Stmt *Term = B.getTerminatorStmt()) 1367 return Term; 1368 for (const CFGElement &Elem : llvm::reverse(B)) 1369 if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) 1370 return CS->getStmt(); 1371 // Workaround to detect a statement thrown out by CFGBuilder: 1372 // case X: {} case Y: 1373 // case X: ; case Y: 1374 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel())) 1375 if (!isa<SwitchCase>(SW->getSubStmt())) 1376 return SW->getSubStmt(); 1377 1378 return nullptr; 1379 } 1380 1381 bool FoundSwitchStatements; 1382 AttrStmts FallthroughStmts; 1383 Sema &S; 1384 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks; 1385 }; 1386 } // anonymous namespace 1387 1388 static StringRef getFallthroughAttrSpelling(Preprocessor &PP, 1389 SourceLocation Loc) { 1390 TokenValue FallthroughTokens[] = { 1391 tok::l_square, tok::l_square, 1392 PP.getIdentifierInfo("fallthrough"), 1393 tok::r_square, tok::r_square 1394 }; 1395 1396 TokenValue ClangFallthroughTokens[] = { 1397 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"), 1398 tok::coloncolon, PP.getIdentifierInfo("fallthrough"), 1399 tok::r_square, tok::r_square 1400 }; 1401 1402 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C23; 1403 1404 StringRef MacroName; 1405 if (PreferClangAttr) 1406 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); 1407 if (MacroName.empty()) 1408 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens); 1409 if (MacroName.empty() && !PreferClangAttr) 1410 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); 1411 if (MacroName.empty()) { 1412 if (!PreferClangAttr) 1413 MacroName = "[[fallthrough]]"; 1414 else if (PP.getLangOpts().CPlusPlus) 1415 MacroName = "[[clang::fallthrough]]"; 1416 else 1417 MacroName = "__attribute__((fallthrough))"; 1418 } 1419 return MacroName; 1420 } 1421 1422 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, 1423 bool PerFunction) { 1424 FallthroughMapper FM(S); 1425 FM.TraverseStmt(AC.getBody()); 1426 1427 if (!FM.foundSwitchStatements()) 1428 return; 1429 1430 if (PerFunction && FM.getFallthroughStmts().empty()) 1431 return; 1432 1433 CFG *Cfg = AC.getCFG(); 1434 1435 if (!Cfg) 1436 return; 1437 1438 FM.fillReachableBlocks(Cfg); 1439 1440 for (const CFGBlock *B : llvm::reverse(*Cfg)) { 1441 const Stmt *Label = B->getLabel(); 1442 1443 if (!isa_and_nonnull<SwitchCase>(Label)) 1444 continue; 1445 1446 int AnnotatedCnt; 1447 1448 bool IsTemplateInstantiation = false; 1449 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl())) 1450 IsTemplateInstantiation = Function->isTemplateInstantiation(); 1451 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt, 1452 IsTemplateInstantiation)) 1453 continue; 1454 1455 S.Diag(Label->getBeginLoc(), 1456 PerFunction ? diag::warn_unannotated_fallthrough_per_function 1457 : diag::warn_unannotated_fallthrough); 1458 1459 if (!AnnotatedCnt) { 1460 SourceLocation L = Label->getBeginLoc(); 1461 if (L.isMacroID()) 1462 continue; 1463 1464 const Stmt *Term = B->getTerminatorStmt(); 1465 // Skip empty cases. 1466 while (B->empty() && !Term && B->succ_size() == 1) { 1467 B = *B->succ_begin(); 1468 Term = B->getTerminatorStmt(); 1469 } 1470 if (!(B->empty() && isa_and_nonnull<BreakStmt>(Term))) { 1471 Preprocessor &PP = S.getPreprocessor(); 1472 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L); 1473 SmallString<64> TextToInsert(AnnotationSpelling); 1474 TextToInsert += "; "; 1475 S.Diag(L, diag::note_insert_fallthrough_fixit) 1476 << AnnotationSpelling 1477 << FixItHint::CreateInsertion(L, TextToInsert); 1478 } 1479 S.Diag(L, diag::note_insert_break_fixit) 1480 << FixItHint::CreateInsertion(L, "break; "); 1481 } 1482 } 1483 1484 for (const auto *F : FM.getFallthroughStmts()) 1485 S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement); 1486 } 1487 1488 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM, 1489 const Stmt *S) { 1490 assert(S); 1491 1492 do { 1493 switch (S->getStmtClass()) { 1494 case Stmt::ForStmtClass: 1495 case Stmt::WhileStmtClass: 1496 case Stmt::CXXForRangeStmtClass: 1497 case Stmt::ObjCForCollectionStmtClass: 1498 return true; 1499 case Stmt::DoStmtClass: { 1500 Expr::EvalResult Result; 1501 if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx)) 1502 return true; 1503 return Result.Val.getInt().getBoolValue(); 1504 } 1505 default: 1506 break; 1507 } 1508 } while ((S = PM.getParent(S))); 1509 1510 return false; 1511 } 1512 1513 static void diagnoseRepeatedUseOfWeak(Sema &S, 1514 const sema::FunctionScopeInfo *CurFn, 1515 const Decl *D, 1516 const ParentMap &PM) { 1517 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy; 1518 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap; 1519 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector; 1520 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator> 1521 StmtUsesPair; 1522 1523 ASTContext &Ctx = S.getASTContext(); 1524 1525 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses(); 1526 1527 // Extract all weak objects that are referenced more than once. 1528 SmallVector<StmtUsesPair, 8> UsesByStmt; 1529 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end(); 1530 I != E; ++I) { 1531 const WeakUseVector &Uses = I->second; 1532 1533 // Find the first read of the weak object. 1534 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end(); 1535 for ( ; UI != UE; ++UI) { 1536 if (UI->isUnsafe()) 1537 break; 1538 } 1539 1540 // If there were only writes to this object, don't warn. 1541 if (UI == UE) 1542 continue; 1543 1544 // If there was only one read, followed by any number of writes, and the 1545 // read is not within a loop, don't warn. Additionally, don't warn in a 1546 // loop if the base object is a local variable -- local variables are often 1547 // changed in loops. 1548 if (UI == Uses.begin()) { 1549 WeakUseVector::const_iterator UI2 = UI; 1550 for (++UI2; UI2 != UE; ++UI2) 1551 if (UI2->isUnsafe()) 1552 break; 1553 1554 if (UI2 == UE) { 1555 if (!isInLoop(Ctx, PM, UI->getUseExpr())) 1556 continue; 1557 1558 const WeakObjectProfileTy &Profile = I->first; 1559 if (!Profile.isExactProfile()) 1560 continue; 1561 1562 const NamedDecl *Base = Profile.getBase(); 1563 if (!Base) 1564 Base = Profile.getProperty(); 1565 assert(Base && "A profile always has a base or property."); 1566 1567 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base)) 1568 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base)) 1569 continue; 1570 } 1571 } 1572 1573 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I)); 1574 } 1575 1576 if (UsesByStmt.empty()) 1577 return; 1578 1579 // Sort by first use so that we emit the warnings in a deterministic order. 1580 SourceManager &SM = S.getSourceManager(); 1581 llvm::sort(UsesByStmt, 1582 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) { 1583 return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(), 1584 RHS.first->getBeginLoc()); 1585 }); 1586 1587 // Classify the current code body for better warning text. 1588 // This enum should stay in sync with the cases in 1589 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak. 1590 // FIXME: Should we use a common classification enum and the same set of 1591 // possibilities all throughout Sema? 1592 enum { 1593 Function, 1594 Method, 1595 Block, 1596 Lambda 1597 } FunctionKind; 1598 1599 if (isa<sema::BlockScopeInfo>(CurFn)) 1600 FunctionKind = Block; 1601 else if (isa<sema::LambdaScopeInfo>(CurFn)) 1602 FunctionKind = Lambda; 1603 else if (isa<ObjCMethodDecl>(D)) 1604 FunctionKind = Method; 1605 else 1606 FunctionKind = Function; 1607 1608 // Iterate through the sorted problems and emit warnings for each. 1609 for (const auto &P : UsesByStmt) { 1610 const Stmt *FirstRead = P.first; 1611 const WeakObjectProfileTy &Key = P.second->first; 1612 const WeakUseVector &Uses = P.second->second; 1613 1614 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy 1615 // may not contain enough information to determine that these are different 1616 // properties. We can only be 100% sure of a repeated use in certain cases, 1617 // and we adjust the diagnostic kind accordingly so that the less certain 1618 // case can be turned off if it is too noisy. 1619 unsigned DiagKind; 1620 if (Key.isExactProfile()) 1621 DiagKind = diag::warn_arc_repeated_use_of_weak; 1622 else 1623 DiagKind = diag::warn_arc_possible_repeated_use_of_weak; 1624 1625 // Classify the weak object being accessed for better warning text. 1626 // This enum should stay in sync with the cases in 1627 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak. 1628 enum { 1629 Variable, 1630 Property, 1631 ImplicitProperty, 1632 Ivar 1633 } ObjectKind; 1634 1635 const NamedDecl *KeyProp = Key.getProperty(); 1636 if (isa<VarDecl>(KeyProp)) 1637 ObjectKind = Variable; 1638 else if (isa<ObjCPropertyDecl>(KeyProp)) 1639 ObjectKind = Property; 1640 else if (isa<ObjCMethodDecl>(KeyProp)) 1641 ObjectKind = ImplicitProperty; 1642 else if (isa<ObjCIvarDecl>(KeyProp)) 1643 ObjectKind = Ivar; 1644 else 1645 llvm_unreachable("Unexpected weak object kind!"); 1646 1647 // Do not warn about IBOutlet weak property receivers being set to null 1648 // since they are typically only used from the main thread. 1649 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp)) 1650 if (Prop->hasAttr<IBOutletAttr>()) 1651 continue; 1652 1653 // Show the first time the object was read. 1654 S.Diag(FirstRead->getBeginLoc(), DiagKind) 1655 << int(ObjectKind) << KeyProp << int(FunctionKind) 1656 << FirstRead->getSourceRange(); 1657 1658 // Print all the other accesses as notes. 1659 for (const auto &Use : Uses) { 1660 if (Use.getUseExpr() == FirstRead) 1661 continue; 1662 S.Diag(Use.getUseExpr()->getBeginLoc(), 1663 diag::note_arc_weak_also_accessed_here) 1664 << Use.getUseExpr()->getSourceRange(); 1665 } 1666 } 1667 } 1668 1669 namespace clang { 1670 namespace { 1671 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes; 1672 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag; 1673 typedef std::list<DelayedDiag> DiagList; 1674 1675 struct SortDiagBySourceLocation { 1676 SourceManager &SM; 1677 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {} 1678 1679 bool operator()(const DelayedDiag &left, const DelayedDiag &right) { 1680 // Although this call will be slow, this is only called when outputting 1681 // multiple warnings. 1682 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first); 1683 } 1684 }; 1685 } // anonymous namespace 1686 } // namespace clang 1687 1688 namespace { 1689 class UninitValsDiagReporter : public UninitVariablesHandler { 1690 Sema &S; 1691 typedef SmallVector<UninitUse, 2> UsesVec; 1692 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType; 1693 // Prefer using MapVector to DenseMap, so that iteration order will be 1694 // the same as insertion order. This is needed to obtain a deterministic 1695 // order of diagnostics when calling flushDiagnostics(). 1696 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap; 1697 UsesMap uses; 1698 1699 public: 1700 UninitValsDiagReporter(Sema &S) : S(S) {} 1701 ~UninitValsDiagReporter() override { flushDiagnostics(); } 1702 1703 MappedType &getUses(const VarDecl *vd) { 1704 MappedType &V = uses[vd]; 1705 if (!V.getPointer()) 1706 V.setPointer(new UsesVec()); 1707 return V; 1708 } 1709 1710 void handleUseOfUninitVariable(const VarDecl *vd, 1711 const UninitUse &use) override { 1712 getUses(vd).getPointer()->push_back(use); 1713 } 1714 1715 void handleSelfInit(const VarDecl *vd) override { getUses(vd).setInt(true); } 1716 1717 void flushDiagnostics() { 1718 for (const auto &P : uses) { 1719 const VarDecl *vd = P.first; 1720 const MappedType &V = P.second; 1721 1722 UsesVec *vec = V.getPointer(); 1723 bool hasSelfInit = V.getInt(); 1724 1725 diagnoseUnitializedVar(vd, hasSelfInit, vec); 1726 1727 // Release the uses vector. 1728 delete vec; 1729 } 1730 1731 uses.clear(); 1732 } 1733 1734 private: 1735 static bool hasAlwaysUninitializedUse(const UsesVec* vec) { 1736 return llvm::any_of(*vec, [](const UninitUse &U) { 1737 return U.getKind() == UninitUse::Always || 1738 U.getKind() == UninitUse::AfterCall || 1739 U.getKind() == UninitUse::AfterDecl; 1740 }); 1741 } 1742 1743 // Print the diagnostic for the variable. We try to warn only on the first 1744 // point at which a variable is used uninitialized. After the first 1745 // diagnostic is printed, further diagnostics for this variable are skipped. 1746 void diagnoseUnitializedVar(const VarDecl *vd, bool hasSelfInit, 1747 UsesVec *vec) { 1748 // Specially handle the case where we have uses of an uninitialized 1749 // variable, but the root cause is an idiomatic self-init. We want 1750 // to report the diagnostic at the self-init since that is the root cause. 1751 if (hasSelfInit && hasAlwaysUninitializedUse(vec)) { 1752 if (DiagnoseUninitializedUse(S, vd, 1753 UninitUse(vd->getInit()->IgnoreParenCasts(), 1754 /*isAlwaysUninit=*/true), 1755 /*alwaysReportSelfInit=*/true)) 1756 return; 1757 } 1758 1759 // Sort the uses by their SourceLocations. While not strictly 1760 // guaranteed to produce them in line/column order, this will provide 1761 // a stable ordering. 1762 llvm::sort(*vec, [](const UninitUse &a, const UninitUse &b) { 1763 // Prefer the direct use of an uninitialized variable over its use via 1764 // constant reference or pointer. 1765 if (a.isConstRefOrPtrUse() != b.isConstRefOrPtrUse()) 1766 return b.isConstRefOrPtrUse(); 1767 // Prefer a more confident report over a less confident one. 1768 if (a.getKind() != b.getKind()) 1769 return a.getKind() > b.getKind(); 1770 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc(); 1771 }); 1772 1773 for (const auto &U : *vec) { 1774 if (U.isConstRefUse()) { 1775 if (DiagnoseUninitializedConstRefUse(S, vd, U)) 1776 return; 1777 } else if (U.isConstPtrUse()) { 1778 if (DiagnoseUninitializedConstPtrUse(S, vd, U)) 1779 return; 1780 } else { 1781 // If we have self-init, downgrade all uses to 'may be uninitialized'. 1782 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U; 1783 if (DiagnoseUninitializedUse(S, vd, Use)) 1784 return; 1785 } 1786 } 1787 } 1788 }; 1789 1790 /// Inter-procedural data for the called-once checker. 1791 class CalledOnceInterProceduralData { 1792 public: 1793 // Add the delayed warning for the given block. 1794 void addDelayedWarning(const BlockDecl *Block, 1795 PartialDiagnosticAt &&Warning) { 1796 DelayedBlockWarnings[Block].emplace_back(std::move(Warning)); 1797 } 1798 // Report all of the warnings we've gathered for the given block. 1799 void flushWarnings(const BlockDecl *Block, Sema &S) { 1800 for (const PartialDiagnosticAt &Delayed : DelayedBlockWarnings[Block]) 1801 S.Diag(Delayed.first, Delayed.second); 1802 1803 discardWarnings(Block); 1804 } 1805 // Discard all of the warnings we've gathered for the given block. 1806 void discardWarnings(const BlockDecl *Block) { 1807 DelayedBlockWarnings.erase(Block); 1808 } 1809 1810 private: 1811 using DelayedDiagnostics = SmallVector<PartialDiagnosticAt, 2>; 1812 llvm::DenseMap<const BlockDecl *, DelayedDiagnostics> DelayedBlockWarnings; 1813 }; 1814 1815 class CalledOnceCheckReporter : public CalledOnceCheckHandler { 1816 public: 1817 CalledOnceCheckReporter(Sema &S, CalledOnceInterProceduralData &Data) 1818 : S(S), Data(Data) {} 1819 void handleDoubleCall(const ParmVarDecl *Parameter, const Expr *Call, 1820 const Expr *PrevCall, bool IsCompletionHandler, 1821 bool Poised) override { 1822 auto DiagToReport = IsCompletionHandler 1823 ? diag::warn_completion_handler_called_twice 1824 : diag::warn_called_once_gets_called_twice; 1825 S.Diag(Call->getBeginLoc(), DiagToReport) << Parameter; 1826 S.Diag(PrevCall->getBeginLoc(), diag::note_called_once_gets_called_twice) 1827 << Poised; 1828 } 1829 1830 void handleNeverCalled(const ParmVarDecl *Parameter, 1831 bool IsCompletionHandler) override { 1832 auto DiagToReport = IsCompletionHandler 1833 ? diag::warn_completion_handler_never_called 1834 : diag::warn_called_once_never_called; 1835 S.Diag(Parameter->getBeginLoc(), DiagToReport) 1836 << Parameter << /* Captured */ false; 1837 } 1838 1839 void handleNeverCalled(const ParmVarDecl *Parameter, const Decl *Function, 1840 const Stmt *Where, NeverCalledReason Reason, 1841 bool IsCalledDirectly, 1842 bool IsCompletionHandler) override { 1843 auto DiagToReport = IsCompletionHandler 1844 ? diag::warn_completion_handler_never_called_when 1845 : diag::warn_called_once_never_called_when; 1846 PartialDiagnosticAt Warning(Where->getBeginLoc(), S.PDiag(DiagToReport) 1847 << Parameter 1848 << IsCalledDirectly 1849 << (unsigned)Reason); 1850 1851 if (const auto *Block = dyn_cast<BlockDecl>(Function)) { 1852 // We shouldn't report these warnings on blocks immediately 1853 Data.addDelayedWarning(Block, std::move(Warning)); 1854 } else { 1855 S.Diag(Warning.first, Warning.second); 1856 } 1857 } 1858 1859 void handleCapturedNeverCalled(const ParmVarDecl *Parameter, 1860 const Decl *Where, 1861 bool IsCompletionHandler) override { 1862 auto DiagToReport = IsCompletionHandler 1863 ? diag::warn_completion_handler_never_called 1864 : diag::warn_called_once_never_called; 1865 S.Diag(Where->getBeginLoc(), DiagToReport) 1866 << Parameter << /* Captured */ true; 1867 } 1868 1869 void 1870 handleBlockThatIsGuaranteedToBeCalledOnce(const BlockDecl *Block) override { 1871 Data.flushWarnings(Block, S); 1872 } 1873 1874 void handleBlockWithNoGuarantees(const BlockDecl *Block) override { 1875 Data.discardWarnings(Block); 1876 } 1877 1878 private: 1879 Sema &S; 1880 CalledOnceInterProceduralData &Data; 1881 }; 1882 1883 constexpr unsigned CalledOnceWarnings[] = { 1884 diag::warn_called_once_never_called, 1885 diag::warn_called_once_never_called_when, 1886 diag::warn_called_once_gets_called_twice}; 1887 1888 constexpr unsigned CompletionHandlerWarnings[]{ 1889 diag::warn_completion_handler_never_called, 1890 diag::warn_completion_handler_never_called_when, 1891 diag::warn_completion_handler_called_twice}; 1892 1893 bool shouldAnalyzeCalledOnceImpl(llvm::ArrayRef<unsigned> DiagIDs, 1894 const DiagnosticsEngine &Diags, 1895 SourceLocation At) { 1896 return llvm::any_of(DiagIDs, [&Diags, At](unsigned DiagID) { 1897 return !Diags.isIgnored(DiagID, At); 1898 }); 1899 } 1900 1901 bool shouldAnalyzeCalledOnceConventions(const DiagnosticsEngine &Diags, 1902 SourceLocation At) { 1903 return shouldAnalyzeCalledOnceImpl(CompletionHandlerWarnings, Diags, At); 1904 } 1905 1906 bool shouldAnalyzeCalledOnceParameters(const DiagnosticsEngine &Diags, 1907 SourceLocation At) { 1908 return shouldAnalyzeCalledOnceImpl(CalledOnceWarnings, Diags, At) || 1909 shouldAnalyzeCalledOnceConventions(Diags, At); 1910 } 1911 } // anonymous namespace 1912 1913 //===----------------------------------------------------------------------===// 1914 // -Wthread-safety 1915 //===----------------------------------------------------------------------===// 1916 namespace clang { 1917 namespace threadSafety { 1918 namespace { 1919 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler { 1920 Sema &S; 1921 DiagList Warnings; 1922 SourceLocation FunLocation, FunEndLocation; 1923 1924 const FunctionDecl *CurrentFunction; 1925 bool Verbose; 1926 1927 OptionalNotes getNotes() const { 1928 if (Verbose && CurrentFunction) { 1929 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), 1930 S.PDiag(diag::note_thread_warning_in_fun) 1931 << CurrentFunction); 1932 return OptionalNotes(1, FNote); 1933 } 1934 return OptionalNotes(); 1935 } 1936 1937 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const { 1938 OptionalNotes ONS(1, Note); 1939 if (Verbose && CurrentFunction) { 1940 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), 1941 S.PDiag(diag::note_thread_warning_in_fun) 1942 << CurrentFunction); 1943 ONS.push_back(std::move(FNote)); 1944 } 1945 return ONS; 1946 } 1947 1948 OptionalNotes getNotes(const PartialDiagnosticAt &Note1, 1949 const PartialDiagnosticAt &Note2) const { 1950 OptionalNotes ONS; 1951 ONS.push_back(Note1); 1952 ONS.push_back(Note2); 1953 if (Verbose && CurrentFunction) { 1954 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), 1955 S.PDiag(diag::note_thread_warning_in_fun) 1956 << CurrentFunction); 1957 ONS.push_back(std::move(FNote)); 1958 } 1959 return ONS; 1960 } 1961 1962 OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) { 1963 return LocLocked.isValid() 1964 ? getNotes(PartialDiagnosticAt( 1965 LocLocked, S.PDiag(diag::note_locked_here) << Kind)) 1966 : getNotes(); 1967 } 1968 1969 OptionalNotes makeUnlockedHereNote(SourceLocation LocUnlocked, 1970 StringRef Kind) { 1971 return LocUnlocked.isValid() 1972 ? getNotes(PartialDiagnosticAt( 1973 LocUnlocked, S.PDiag(diag::note_unlocked_here) << Kind)) 1974 : getNotes(); 1975 } 1976 1977 OptionalNotes makeManagedMismatchNoteForParam(SourceLocation DeclLoc) { 1978 return DeclLoc.isValid() 1979 ? getNotes(PartialDiagnosticAt( 1980 DeclLoc, 1981 S.PDiag(diag::note_managed_mismatch_here_for_param))) 1982 : getNotes(); 1983 } 1984 1985 public: 1986 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL) 1987 : S(S), FunLocation(FL), FunEndLocation(FEL), 1988 CurrentFunction(nullptr), Verbose(false) {} 1989 1990 void setVerbose(bool b) { Verbose = b; } 1991 1992 /// Emit all buffered diagnostics in order of sourcelocation. 1993 /// We need to output diagnostics produced while iterating through 1994 /// the lockset in deterministic order, so this function orders diagnostics 1995 /// and outputs them. 1996 void emitDiagnostics() { 1997 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager())); 1998 for (const auto &Diag : Warnings) { 1999 S.Diag(Diag.first.first, Diag.first.second); 2000 for (const auto &Note : Diag.second) 2001 S.Diag(Note.first, Note.second); 2002 } 2003 } 2004 2005 void handleUnmatchedUnderlyingMutexes(SourceLocation Loc, SourceLocation DLoc, 2006 Name scopeName, StringRef Kind, 2007 Name expected, Name actual) override { 2008 PartialDiagnosticAt Warning(Loc, 2009 S.PDiag(diag::warn_unmatched_underlying_mutexes) 2010 << Kind << scopeName << expected << actual); 2011 Warnings.emplace_back(std::move(Warning), 2012 makeManagedMismatchNoteForParam(DLoc)); 2013 } 2014 2015 void handleExpectMoreUnderlyingMutexes(SourceLocation Loc, 2016 SourceLocation DLoc, Name scopeName, 2017 StringRef Kind, 2018 Name expected) override { 2019 PartialDiagnosticAt Warning( 2020 Loc, S.PDiag(diag::warn_expect_more_underlying_mutexes) 2021 << Kind << scopeName << expected); 2022 Warnings.emplace_back(std::move(Warning), 2023 makeManagedMismatchNoteForParam(DLoc)); 2024 } 2025 2026 void handleExpectFewerUnderlyingMutexes(SourceLocation Loc, 2027 SourceLocation DLoc, Name scopeName, 2028 StringRef Kind, 2029 Name actual) override { 2030 PartialDiagnosticAt Warning( 2031 Loc, S.PDiag(diag::warn_expect_fewer_underlying_mutexes) 2032 << Kind << scopeName << actual); 2033 Warnings.emplace_back(std::move(Warning), 2034 makeManagedMismatchNoteForParam(DLoc)); 2035 } 2036 2037 void handleInvalidLockExp(SourceLocation Loc) override { 2038 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock) 2039 << Loc); 2040 Warnings.emplace_back(std::move(Warning), getNotes()); 2041 } 2042 2043 void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc, 2044 SourceLocation LocPreviousUnlock) override { 2045 if (Loc.isInvalid()) 2046 Loc = FunLocation; 2047 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock) 2048 << Kind << LockName); 2049 Warnings.emplace_back(std::move(Warning), 2050 makeUnlockedHereNote(LocPreviousUnlock, Kind)); 2051 } 2052 2053 void handleIncorrectUnlockKind(StringRef Kind, Name LockName, 2054 LockKind Expected, LockKind Received, 2055 SourceLocation LocLocked, 2056 SourceLocation LocUnlock) override { 2057 if (LocUnlock.isInvalid()) 2058 LocUnlock = FunLocation; 2059 PartialDiagnosticAt Warning( 2060 LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch) 2061 << Kind << LockName << Received << Expected); 2062 Warnings.emplace_back(std::move(Warning), 2063 makeLockedHereNote(LocLocked, Kind)); 2064 } 2065 2066 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked, 2067 SourceLocation LocDoubleLock) override { 2068 if (LocDoubleLock.isInvalid()) 2069 LocDoubleLock = FunLocation; 2070 PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock) 2071 << Kind << LockName); 2072 Warnings.emplace_back(std::move(Warning), 2073 makeLockedHereNote(LocLocked, Kind)); 2074 } 2075 2076 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName, 2077 SourceLocation LocLocked, 2078 SourceLocation LocEndOfScope, 2079 LockErrorKind LEK, 2080 bool ReentrancyMismatch) override { 2081 unsigned DiagID = 0; 2082 switch (LEK) { 2083 case LEK_LockedSomePredecessors: 2084 DiagID = diag::warn_lock_some_predecessors; 2085 break; 2086 case LEK_LockedSomeLoopIterations: 2087 DiagID = diag::warn_expecting_lock_held_on_loop; 2088 break; 2089 case LEK_LockedAtEndOfFunction: 2090 DiagID = diag::warn_no_unlock; 2091 break; 2092 case LEK_NotLockedAtEndOfFunction: 2093 DiagID = diag::warn_expecting_locked; 2094 break; 2095 } 2096 if (LocEndOfScope.isInvalid()) 2097 LocEndOfScope = FunEndLocation; 2098 2099 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) 2100 << Kind << LockName 2101 << ReentrancyMismatch); 2102 Warnings.emplace_back(std::move(Warning), 2103 makeLockedHereNote(LocLocked, Kind)); 2104 } 2105 2106 void handleExclusiveAndShared(StringRef Kind, Name LockName, 2107 SourceLocation Loc1, 2108 SourceLocation Loc2) override { 2109 PartialDiagnosticAt Warning(Loc1, 2110 S.PDiag(diag::warn_lock_exclusive_and_shared) 2111 << Kind << LockName); 2112 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) 2113 << Kind << LockName); 2114 Warnings.emplace_back(std::move(Warning), getNotes(Note)); 2115 } 2116 2117 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK, 2118 AccessKind AK, SourceLocation Loc) override { 2119 assert((POK == POK_VarAccess || POK == POK_VarDereference) && 2120 "Only works for variables"); 2121 unsigned DiagID = POK == POK_VarAccess? 2122 diag::warn_variable_requires_any_lock: 2123 diag::warn_var_deref_requires_any_lock; 2124 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) 2125 << D << getLockKindFromAccessKind(AK)); 2126 Warnings.emplace_back(std::move(Warning), getNotes()); 2127 } 2128 2129 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D, 2130 ProtectedOperationKind POK, Name LockName, 2131 LockKind LK, SourceLocation Loc, 2132 Name *PossibleMatch) override { 2133 unsigned DiagID = 0; 2134 if (PossibleMatch) { 2135 switch (POK) { 2136 case POK_VarAccess: 2137 DiagID = diag::warn_variable_requires_lock_precise; 2138 break; 2139 case POK_VarDereference: 2140 DiagID = diag::warn_var_deref_requires_lock_precise; 2141 break; 2142 case POK_FunctionCall: 2143 DiagID = diag::warn_fun_requires_lock_precise; 2144 break; 2145 case POK_PassByRef: 2146 DiagID = diag::warn_guarded_pass_by_reference; 2147 break; 2148 case POK_PtPassByRef: 2149 DiagID = diag::warn_pt_guarded_pass_by_reference; 2150 break; 2151 case POK_ReturnByRef: 2152 DiagID = diag::warn_guarded_return_by_reference; 2153 break; 2154 case POK_PtReturnByRef: 2155 DiagID = diag::warn_pt_guarded_return_by_reference; 2156 break; 2157 case POK_PassPointer: 2158 DiagID = diag::warn_guarded_pass_pointer; 2159 break; 2160 case POK_PtPassPointer: 2161 DiagID = diag::warn_pt_guarded_pass_pointer; 2162 break; 2163 case POK_ReturnPointer: 2164 DiagID = diag::warn_guarded_return_pointer; 2165 break; 2166 case POK_PtReturnPointer: 2167 DiagID = diag::warn_pt_guarded_return_pointer; 2168 break; 2169 } 2170 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind 2171 << D 2172 << LockName << LK); 2173 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match) 2174 << *PossibleMatch); 2175 if (Verbose && POK == POK_VarAccess) { 2176 PartialDiagnosticAt VNote(D->getLocation(), 2177 S.PDiag(diag::note_guarded_by_declared_here) 2178 << D->getDeclName()); 2179 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote)); 2180 } else 2181 Warnings.emplace_back(std::move(Warning), getNotes(Note)); 2182 } else { 2183 switch (POK) { 2184 case POK_VarAccess: 2185 DiagID = diag::warn_variable_requires_lock; 2186 break; 2187 case POK_VarDereference: 2188 DiagID = diag::warn_var_deref_requires_lock; 2189 break; 2190 case POK_FunctionCall: 2191 DiagID = diag::warn_fun_requires_lock; 2192 break; 2193 case POK_PassByRef: 2194 DiagID = diag::warn_guarded_pass_by_reference; 2195 break; 2196 case POK_PtPassByRef: 2197 DiagID = diag::warn_pt_guarded_pass_by_reference; 2198 break; 2199 case POK_ReturnByRef: 2200 DiagID = diag::warn_guarded_return_by_reference; 2201 break; 2202 case POK_PtReturnByRef: 2203 DiagID = diag::warn_pt_guarded_return_by_reference; 2204 break; 2205 case POK_PassPointer: 2206 DiagID = diag::warn_guarded_pass_pointer; 2207 break; 2208 case POK_PtPassPointer: 2209 DiagID = diag::warn_pt_guarded_pass_pointer; 2210 break; 2211 case POK_ReturnPointer: 2212 DiagID = diag::warn_guarded_return_pointer; 2213 break; 2214 case POK_PtReturnPointer: 2215 DiagID = diag::warn_pt_guarded_return_pointer; 2216 break; 2217 } 2218 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind 2219 << D 2220 << LockName << LK); 2221 if (Verbose && POK == POK_VarAccess) { 2222 PartialDiagnosticAt Note(D->getLocation(), 2223 S.PDiag(diag::note_guarded_by_declared_here)); 2224 Warnings.emplace_back(std::move(Warning), getNotes(Note)); 2225 } else 2226 Warnings.emplace_back(std::move(Warning), getNotes()); 2227 } 2228 } 2229 2230 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg, 2231 SourceLocation Loc) override { 2232 PartialDiagnosticAt Warning(Loc, 2233 S.PDiag(diag::warn_acquire_requires_negative_cap) 2234 << Kind << LockName << Neg); 2235 Warnings.emplace_back(std::move(Warning), getNotes()); 2236 } 2237 2238 void handleNegativeNotHeld(const NamedDecl *D, Name LockName, 2239 SourceLocation Loc) override { 2240 PartialDiagnosticAt Warning( 2241 Loc, S.PDiag(diag::warn_fun_requires_negative_cap) << D << LockName); 2242 Warnings.emplace_back(std::move(Warning), getNotes()); 2243 } 2244 2245 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName, 2246 SourceLocation Loc) override { 2247 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex) 2248 << Kind << FunName << LockName); 2249 Warnings.emplace_back(std::move(Warning), getNotes()); 2250 } 2251 2252 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name, 2253 SourceLocation Loc) override { 2254 PartialDiagnosticAt Warning(Loc, 2255 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name); 2256 Warnings.emplace_back(std::move(Warning), getNotes()); 2257 } 2258 2259 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override { 2260 PartialDiagnosticAt Warning(Loc, 2261 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name); 2262 Warnings.emplace_back(std::move(Warning), getNotes()); 2263 } 2264 2265 void enterFunction(const FunctionDecl* FD) override { 2266 CurrentFunction = FD; 2267 } 2268 2269 void leaveFunction(const FunctionDecl* FD) override { 2270 CurrentFunction = nullptr; 2271 } 2272 }; 2273 } // anonymous namespace 2274 } // namespace threadSafety 2275 } // namespace clang 2276 2277 //===----------------------------------------------------------------------===// 2278 // -Wconsumed 2279 //===----------------------------------------------------------------------===// 2280 2281 namespace clang { 2282 namespace consumed { 2283 namespace { 2284 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase { 2285 2286 Sema &S; 2287 DiagList Warnings; 2288 2289 public: 2290 2291 ConsumedWarningsHandler(Sema &S) : S(S) {} 2292 2293 void emitDiagnostics() override { 2294 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager())); 2295 for (const auto &Diag : Warnings) { 2296 S.Diag(Diag.first.first, Diag.first.second); 2297 for (const auto &Note : Diag.second) 2298 S.Diag(Note.first, Note.second); 2299 } 2300 } 2301 2302 void warnLoopStateMismatch(SourceLocation Loc, 2303 StringRef VariableName) override { 2304 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) << 2305 VariableName); 2306 2307 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2308 } 2309 2310 void warnParamReturnTypestateMismatch(SourceLocation Loc, 2311 StringRef VariableName, 2312 StringRef ExpectedState, 2313 StringRef ObservedState) override { 2314 2315 PartialDiagnosticAt Warning(Loc, S.PDiag( 2316 diag::warn_param_return_typestate_mismatch) << VariableName << 2317 ExpectedState << ObservedState); 2318 2319 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2320 } 2321 2322 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, 2323 StringRef ObservedState) override { 2324 2325 PartialDiagnosticAt Warning(Loc, S.PDiag( 2326 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState); 2327 2328 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2329 } 2330 2331 void warnReturnTypestateForUnconsumableType(SourceLocation Loc, 2332 StringRef TypeName) override { 2333 PartialDiagnosticAt Warning(Loc, S.PDiag( 2334 diag::warn_return_typestate_for_unconsumable_type) << TypeName); 2335 2336 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2337 } 2338 2339 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, 2340 StringRef ObservedState) override { 2341 2342 PartialDiagnosticAt Warning(Loc, S.PDiag( 2343 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState); 2344 2345 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2346 } 2347 2348 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State, 2349 SourceLocation Loc) override { 2350 2351 PartialDiagnosticAt Warning(Loc, S.PDiag( 2352 diag::warn_use_of_temp_in_invalid_state) << MethodName << State); 2353 2354 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2355 } 2356 2357 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName, 2358 StringRef State, SourceLocation Loc) override { 2359 2360 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) << 2361 MethodName << VariableName << State); 2362 2363 Warnings.emplace_back(std::move(Warning), OptionalNotes()); 2364 } 2365 }; 2366 } // anonymous namespace 2367 } // namespace consumed 2368 } // namespace clang 2369 2370 //===----------------------------------------------------------------------===// 2371 // Unsafe buffer usage analysis. 2372 //===----------------------------------------------------------------------===// 2373 2374 namespace { 2375 class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler { 2376 Sema &S; 2377 bool SuggestSuggestions; // Recommend -fsafe-buffer-usage-suggestions? 2378 2379 // Lists as a string the names of variables in `VarGroupForVD` except for `VD` 2380 // itself: 2381 std::string listVariableGroupAsString( 2382 const VarDecl *VD, const ArrayRef<const VarDecl *> &VarGroupForVD) const { 2383 if (VarGroupForVD.size() <= 1) 2384 return ""; 2385 2386 std::vector<StringRef> VarNames; 2387 auto PutInQuotes = [](StringRef S) -> std::string { 2388 return "'" + S.str() + "'"; 2389 }; 2390 2391 for (auto *V : VarGroupForVD) { 2392 if (V == VD) 2393 continue; 2394 VarNames.push_back(V->getName()); 2395 } 2396 if (VarNames.size() == 1) { 2397 return PutInQuotes(VarNames[0]); 2398 } 2399 if (VarNames.size() == 2) { 2400 return PutInQuotes(VarNames[0]) + " and " + PutInQuotes(VarNames[1]); 2401 } 2402 assert(VarGroupForVD.size() > 3); 2403 const unsigned N = VarNames.size() - 2404 2; // need to print the last two names as "..., X, and Y" 2405 std::string AllVars = ""; 2406 2407 for (unsigned I = 0; I < N; ++I) 2408 AllVars.append(PutInQuotes(VarNames[I]) + ", "); 2409 AllVars.append(PutInQuotes(VarNames[N]) + ", and " + 2410 PutInQuotes(VarNames[N + 1])); 2411 return AllVars; 2412 } 2413 2414 public: 2415 UnsafeBufferUsageReporter(Sema &S, bool SuggestSuggestions) 2416 : S(S), SuggestSuggestions(SuggestSuggestions) {} 2417 2418 void handleUnsafeOperation(const Stmt *Operation, bool IsRelatedToDecl, 2419 ASTContext &Ctx) override { 2420 SourceLocation Loc; 2421 SourceRange Range; 2422 unsigned MsgParam = 0; 2423 NamedDecl *D = nullptr; 2424 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Operation)) { 2425 Loc = ASE->getBase()->getExprLoc(); 2426 Range = ASE->getBase()->getSourceRange(); 2427 MsgParam = 2; 2428 } else if (const auto *BO = dyn_cast<BinaryOperator>(Operation)) { 2429 BinaryOperator::Opcode Op = BO->getOpcode(); 2430 if (Op == BO_Add || Op == BO_AddAssign || Op == BO_Sub || 2431 Op == BO_SubAssign) { 2432 if (BO->getRHS()->getType()->isIntegerType()) { 2433 Loc = BO->getLHS()->getExprLoc(); 2434 Range = BO->getLHS()->getSourceRange(); 2435 } else { 2436 Loc = BO->getRHS()->getExprLoc(); 2437 Range = BO->getRHS()->getSourceRange(); 2438 } 2439 MsgParam = 1; 2440 } 2441 } else if (const auto *UO = dyn_cast<UnaryOperator>(Operation)) { 2442 UnaryOperator::Opcode Op = UO->getOpcode(); 2443 if (Op == UO_PreInc || Op == UO_PreDec || Op == UO_PostInc || 2444 Op == UO_PostDec) { 2445 Loc = UO->getSubExpr()->getExprLoc(); 2446 Range = UO->getSubExpr()->getSourceRange(); 2447 MsgParam = 1; 2448 } 2449 } else { 2450 if (isa<CallExpr>(Operation) || isa<CXXConstructExpr>(Operation)) { 2451 // note_unsafe_buffer_operation doesn't have this mode yet. 2452 assert(!IsRelatedToDecl && "Not implemented yet!"); 2453 MsgParam = 3; 2454 } else if (isa<MemberExpr>(Operation)) { 2455 // note_unsafe_buffer_operation doesn't have this mode yet. 2456 assert(!IsRelatedToDecl && "Not implemented yet!"); 2457 auto *ME = cast<MemberExpr>(Operation); 2458 D = ME->getMemberDecl(); 2459 MsgParam = 5; 2460 } else if (const auto *ECE = dyn_cast<ExplicitCastExpr>(Operation)) { 2461 QualType destType = ECE->getType(); 2462 bool destTypeComplete = true; 2463 2464 if (!isa<PointerType>(destType)) 2465 return; 2466 destType = destType.getTypePtr()->getPointeeType(); 2467 if (const auto *D = destType->getAsTagDecl()) 2468 destTypeComplete = D->isCompleteDefinition(); 2469 2470 // If destination type is incomplete, it is unsafe to cast to anyway, no 2471 // need to check its type: 2472 if (destTypeComplete) { 2473 const uint64_t dSize = Ctx.getTypeSize(destType); 2474 QualType srcType = ECE->getSubExpr()->getType(); 2475 2476 assert(srcType->isPointerType()); 2477 2478 const uint64_t sSize = 2479 Ctx.getTypeSize(srcType.getTypePtr()->getPointeeType()); 2480 2481 if (sSize >= dSize) 2482 return; 2483 } 2484 if (const auto *CE = dyn_cast<CXXMemberCallExpr>( 2485 ECE->getSubExpr()->IgnoreParens())) { 2486 D = CE->getMethodDecl(); 2487 } 2488 2489 if (!D) 2490 return; 2491 2492 MsgParam = 4; 2493 } 2494 Loc = Operation->getBeginLoc(); 2495 Range = Operation->getSourceRange(); 2496 } 2497 if (IsRelatedToDecl) { 2498 assert(!SuggestSuggestions && 2499 "Variables blamed for unsafe buffer usage without suggestions!"); 2500 S.Diag(Loc, diag::note_unsafe_buffer_operation) << MsgParam << Range; 2501 } else { 2502 if (D) { 2503 S.Diag(Loc, diag::warn_unsafe_buffer_operation) 2504 << MsgParam << D << Range; 2505 } else { 2506 S.Diag(Loc, diag::warn_unsafe_buffer_operation) << MsgParam << Range; 2507 } 2508 if (SuggestSuggestions) { 2509 S.Diag(Loc, diag::note_safe_buffer_usage_suggestions_disabled); 2510 } 2511 } 2512 } 2513 2514 void handleUnsafeLibcCall(const CallExpr *Call, unsigned PrintfInfo, 2515 ASTContext &Ctx, 2516 const Expr *UnsafeArg = nullptr) override { 2517 S.Diag(Call->getBeginLoc(), diag::warn_unsafe_buffer_libc_call) 2518 << Call->getDirectCallee() // We've checked there is a direct callee 2519 << Call->getSourceRange(); 2520 if (PrintfInfo > 0) { 2521 SourceRange R = 2522 UnsafeArg ? UnsafeArg->getSourceRange() : Call->getSourceRange(); 2523 S.Diag(R.getBegin(), diag::note_unsafe_buffer_printf_call) 2524 << PrintfInfo << R; 2525 } 2526 } 2527 2528 void handleUnsafeOperationInContainer(const Stmt *Operation, 2529 bool IsRelatedToDecl, 2530 ASTContext &Ctx) override { 2531 SourceLocation Loc; 2532 SourceRange Range; 2533 unsigned MsgParam = 0; 2534 2535 // This function only handles SpanTwoParamConstructorGadget so far, which 2536 // always gives a CXXConstructExpr. 2537 const auto *CtorExpr = cast<CXXConstructExpr>(Operation); 2538 Loc = CtorExpr->getLocation(); 2539 2540 S.Diag(Loc, diag::warn_unsafe_buffer_usage_in_container); 2541 if (IsRelatedToDecl) { 2542 assert(!SuggestSuggestions && 2543 "Variables blamed for unsafe buffer usage without suggestions!"); 2544 S.Diag(Loc, diag::note_unsafe_buffer_operation) << MsgParam << Range; 2545 } 2546 } 2547 2548 void handleUnsafeVariableGroup(const VarDecl *Variable, 2549 const VariableGroupsManager &VarGrpMgr, 2550 FixItList &&Fixes, const Decl *D, 2551 const FixitStrategy &VarTargetTypes) override { 2552 assert(!SuggestSuggestions && 2553 "Unsafe buffer usage fixits displayed without suggestions!"); 2554 S.Diag(Variable->getLocation(), diag::warn_unsafe_buffer_variable) 2555 << Variable << (Variable->getType()->isPointerType() ? 0 : 1) 2556 << Variable->getSourceRange(); 2557 if (!Fixes.empty()) { 2558 assert(isa<NamedDecl>(D) && 2559 "Fix-its are generated only for `NamedDecl`s"); 2560 const NamedDecl *ND = cast<NamedDecl>(D); 2561 bool BriefMsg = false; 2562 // If the variable group involves parameters, the diagnostic message will 2563 // NOT explain how the variables are grouped as the reason is non-trivial 2564 // and irrelavant to users' experience: 2565 const auto VarGroupForVD = VarGrpMgr.getGroupOfVar(Variable, &BriefMsg); 2566 unsigned FixItStrategy = 0; 2567 switch (VarTargetTypes.lookup(Variable)) { 2568 case clang::FixitStrategy::Kind::Span: 2569 FixItStrategy = 0; 2570 break; 2571 case clang::FixitStrategy::Kind::Array: 2572 FixItStrategy = 1; 2573 break; 2574 default: 2575 assert(false && "We support only std::span and std::array"); 2576 }; 2577 2578 const auto &FD = 2579 S.Diag(Variable->getLocation(), 2580 BriefMsg ? diag::note_unsafe_buffer_variable_fixit_together 2581 : diag::note_unsafe_buffer_variable_fixit_group); 2582 2583 FD << Variable << FixItStrategy; 2584 FD << listVariableGroupAsString(Variable, VarGroupForVD) 2585 << (VarGroupForVD.size() > 1) << ND; 2586 for (const auto &F : Fixes) { 2587 FD << F; 2588 } 2589 } 2590 2591 #ifndef NDEBUG 2592 if (areDebugNotesRequested()) 2593 for (const DebugNote &Note: DebugNotesByVar[Variable]) 2594 S.Diag(Note.first, diag::note_safe_buffer_debug_mode) << Note.second; 2595 #endif 2596 } 2597 2598 bool isSafeBufferOptOut(const SourceLocation &Loc) const override { 2599 return S.PP.isSafeBufferOptOut(S.getSourceManager(), Loc); 2600 } 2601 2602 bool ignoreUnsafeBufferInContainer(const SourceLocation &Loc) const override { 2603 return S.Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_container, Loc); 2604 } 2605 2606 bool ignoreUnsafeBufferInLibcCall(const SourceLocation &Loc) const override { 2607 return S.Diags.isIgnored(diag::warn_unsafe_buffer_libc_call, Loc); 2608 } 2609 2610 // Returns the text representation of clang::unsafe_buffer_usage attribute. 2611 // `WSSuffix` holds customized "white-space"s, e.g., newline or whilespace 2612 // characters. 2613 std::string 2614 getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc, 2615 StringRef WSSuffix = "") const override { 2616 Preprocessor &PP = S.getPreprocessor(); 2617 TokenValue ClangUnsafeBufferUsageTokens[] = { 2618 tok::l_square, 2619 tok::l_square, 2620 PP.getIdentifierInfo("clang"), 2621 tok::coloncolon, 2622 PP.getIdentifierInfo("unsafe_buffer_usage"), 2623 tok::r_square, 2624 tok::r_square}; 2625 2626 StringRef MacroName; 2627 2628 // The returned macro (it returns) is guaranteed not to be function-like: 2629 MacroName = PP.getLastMacroWithSpelling(Loc, ClangUnsafeBufferUsageTokens); 2630 if (MacroName.empty()) 2631 MacroName = "[[clang::unsafe_buffer_usage]]"; 2632 return MacroName.str() + WSSuffix.str(); 2633 } 2634 }; 2635 } // namespace 2636 2637 //===----------------------------------------------------------------------===// 2638 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based 2639 // warnings on a function, method, or block. 2640 //===----------------------------------------------------------------------===// 2641 2642 sema::AnalysisBasedWarnings::Policy::Policy() { 2643 enableCheckFallThrough = 1; 2644 enableCheckUnreachable = 0; 2645 enableThreadSafetyAnalysis = 0; 2646 enableConsumedAnalysis = 0; 2647 } 2648 2649 /// InterProceduralData aims to be a storage of whatever data should be passed 2650 /// between analyses of different functions. 2651 /// 2652 /// At the moment, its primary goal is to make the information gathered during 2653 /// the analysis of the blocks available during the analysis of the enclosing 2654 /// function. This is important due to the fact that blocks are analyzed before 2655 /// the enclosed function is even parsed fully, so it is not viable to access 2656 /// anything in the outer scope while analyzing the block. On the other hand, 2657 /// re-building CFG for blocks and re-analyzing them when we do have all the 2658 /// information (i.e. during the analysis of the enclosing function) seems to be 2659 /// ill-designed. 2660 class sema::AnalysisBasedWarnings::InterProceduralData { 2661 public: 2662 // It is important to analyze blocks within functions because it's a very 2663 // common pattern to capture completion handler parameters by blocks. 2664 CalledOnceInterProceduralData CalledOnceData; 2665 }; 2666 2667 template <typename... Ts> 2668 static bool areAnyEnabled(DiagnosticsEngine &D, SourceLocation Loc, 2669 Ts... Diags) { 2670 return (!D.isIgnored(Diags, Loc) || ...); 2671 } 2672 2673 sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) 2674 : S(s), IPData(std::make_unique<InterProceduralData>()), 2675 NumFunctionsAnalyzed(0), NumFunctionsWithBadCFGs(0), NumCFGBlocks(0), 2676 MaxCFGBlocksPerFunction(0), NumUninitAnalysisFunctions(0), 2677 NumUninitAnalysisVariables(0), MaxUninitAnalysisVariablesPerFunction(0), 2678 NumUninitAnalysisBlockVisits(0), 2679 MaxUninitAnalysisBlockVisitsPerFunction(0) { 2680 } 2681 2682 // We need this here for unique_ptr with forward declared class. 2683 sema::AnalysisBasedWarnings::~AnalysisBasedWarnings() = default; 2684 2685 sema::AnalysisBasedWarnings::Policy 2686 sema::AnalysisBasedWarnings::getPolicyInEffectAt(SourceLocation Loc) { 2687 using namespace diag; 2688 DiagnosticsEngine &D = S.getDiagnostics(); 2689 Policy P; 2690 2691 // Note: The enabled checks should be kept in sync with the switch in 2692 // SemaPPCallbacks::PragmaDiagnostic(). 2693 P.enableCheckUnreachable = 2694 PolicyOverrides.enableCheckUnreachable || 2695 areAnyEnabled(D, Loc, warn_unreachable, warn_unreachable_break, 2696 warn_unreachable_return, warn_unreachable_loop_increment); 2697 2698 P.enableThreadSafetyAnalysis = PolicyOverrides.enableThreadSafetyAnalysis || 2699 areAnyEnabled(D, Loc, warn_double_lock); 2700 2701 P.enableConsumedAnalysis = PolicyOverrides.enableConsumedAnalysis || 2702 areAnyEnabled(D, Loc, warn_use_in_invalid_state); 2703 return P; 2704 } 2705 2706 void sema::AnalysisBasedWarnings::clearOverrides() { 2707 PolicyOverrides.enableCheckUnreachable = false; 2708 PolicyOverrides.enableConsumedAnalysis = false; 2709 PolicyOverrides.enableThreadSafetyAnalysis = false; 2710 } 2711 2712 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) { 2713 for (const auto &D : fscope->PossiblyUnreachableDiags) 2714 S.Diag(D.Loc, D.PD); 2715 } 2716 2717 // An AST Visitor that calls a callback function on each callable DEFINITION 2718 // that is NOT in a dependent context: 2719 class CallableVisitor : public DynamicRecursiveASTVisitor { 2720 private: 2721 llvm::function_ref<void(const Decl *)> Callback; 2722 const Module *const TUModule; 2723 2724 public: 2725 CallableVisitor(llvm::function_ref<void(const Decl *)> Callback, 2726 const Module *const TUModule) 2727 : Callback(Callback), TUModule(TUModule) { 2728 ShouldVisitTemplateInstantiations = true; 2729 ShouldVisitImplicitCode = false; 2730 } 2731 2732 bool TraverseDecl(Decl *Node) override { 2733 // For performance reasons, only validate the current translation unit's 2734 // module, and not modules it depends on. 2735 // See https://issues.chromium.org/issues/351909443 for details. 2736 if (Node && Node->getOwningModule() == TUModule) 2737 return DynamicRecursiveASTVisitor::TraverseDecl(Node); 2738 return true; 2739 } 2740 2741 bool VisitFunctionDecl(FunctionDecl *Node) override { 2742 if (cast<DeclContext>(Node)->isDependentContext()) 2743 return true; // Not to analyze dependent decl 2744 // `FunctionDecl->hasBody()` returns true if the function has a body 2745 // somewhere defined. But we want to know if this `Node` has a body 2746 // child. So we use `doesThisDeclarationHaveABody`: 2747 if (Node->doesThisDeclarationHaveABody()) 2748 Callback(Node); 2749 return true; 2750 } 2751 2752 bool VisitBlockDecl(BlockDecl *Node) override { 2753 if (cast<DeclContext>(Node)->isDependentContext()) 2754 return true; // Not to analyze dependent decl 2755 Callback(Node); 2756 return true; 2757 } 2758 2759 bool VisitObjCMethodDecl(ObjCMethodDecl *Node) override { 2760 if (cast<DeclContext>(Node)->isDependentContext()) 2761 return true; // Not to analyze dependent decl 2762 if (Node->hasBody()) 2763 Callback(Node); 2764 return true; 2765 } 2766 2767 bool VisitLambdaExpr(LambdaExpr *Node) override { 2768 return VisitFunctionDecl(Node->getCallOperator()); 2769 } 2770 }; 2771 2772 void clang::sema::AnalysisBasedWarnings::IssueWarnings( 2773 TranslationUnitDecl *TU) { 2774 if (!TU) 2775 return; // This is unexpected, give up quietly. 2776 2777 DiagnosticsEngine &Diags = S.getDiagnostics(); 2778 2779 if (S.hasUncompilableErrorOccurred() || Diags.getIgnoreAllWarnings()) 2780 // exit if having uncompilable errors or ignoring all warnings: 2781 return; 2782 2783 DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions(); 2784 2785 // UnsafeBufferUsage analysis settings. 2786 bool UnsafeBufferUsageCanEmitSuggestions = S.getLangOpts().CPlusPlus20; 2787 bool UnsafeBufferUsageShouldEmitSuggestions = // Should != Can. 2788 UnsafeBufferUsageCanEmitSuggestions && 2789 DiagOpts.ShowSafeBufferUsageSuggestions; 2790 bool UnsafeBufferUsageShouldSuggestSuggestions = 2791 UnsafeBufferUsageCanEmitSuggestions && 2792 !DiagOpts.ShowSafeBufferUsageSuggestions; 2793 UnsafeBufferUsageReporter R(S, UnsafeBufferUsageShouldSuggestSuggestions); 2794 2795 // The Callback function that performs analyses: 2796 auto CallAnalyzers = [&](const Decl *Node) -> void { 2797 if (Node->hasAttr<UnsafeBufferUsageAttr>()) 2798 return; 2799 2800 // Perform unsafe buffer usage analysis: 2801 if (!Diags.isIgnored(diag::warn_unsafe_buffer_operation, 2802 Node->getBeginLoc()) || 2803 !Diags.isIgnored(diag::warn_unsafe_buffer_variable, 2804 Node->getBeginLoc()) || 2805 !Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_container, 2806 Node->getBeginLoc()) || 2807 !Diags.isIgnored(diag::warn_unsafe_buffer_libc_call, 2808 Node->getBeginLoc())) { 2809 clang::checkUnsafeBufferUsage(Node, R, 2810 UnsafeBufferUsageShouldEmitSuggestions); 2811 } 2812 2813 // More analysis ... 2814 }; 2815 // Emit per-function analysis-based warnings that require the whole-TU 2816 // reasoning. Check if any of them is enabled at all before scanning the AST: 2817 if (!Diags.isIgnored(diag::warn_unsafe_buffer_operation, SourceLocation()) || 2818 !Diags.isIgnored(diag::warn_unsafe_buffer_variable, SourceLocation()) || 2819 !Diags.isIgnored(diag::warn_unsafe_buffer_usage_in_container, 2820 SourceLocation()) || 2821 (!Diags.isIgnored(diag::warn_unsafe_buffer_libc_call, SourceLocation()) && 2822 S.getLangOpts().CPlusPlus /* only warn about libc calls in C++ */)) { 2823 CallableVisitor(CallAnalyzers, TU->getOwningModule()) 2824 .TraverseTranslationUnitDecl(TU); 2825 } 2826 } 2827 2828 void clang::sema::AnalysisBasedWarnings::IssueWarnings( 2829 sema::AnalysisBasedWarnings::Policy P, sema::FunctionScopeInfo *fscope, 2830 const Decl *D, QualType BlockType) { 2831 2832 // We avoid doing analysis-based warnings when there are errors for 2833 // two reasons: 2834 // (1) The CFGs often can't be constructed (if the body is invalid), so 2835 // don't bother trying. 2836 // (2) The code already has problems; running the analysis just takes more 2837 // time. 2838 DiagnosticsEngine &Diags = S.getDiagnostics(); 2839 2840 // Do not do any analysis if we are going to just ignore them. 2841 if (Diags.getIgnoreAllWarnings() || 2842 (Diags.getSuppressSystemWarnings() && 2843 S.SourceMgr.isInSystemHeader(D->getLocation()))) 2844 return; 2845 2846 // For code in dependent contexts, we'll do this at instantiation time. 2847 if (cast<DeclContext>(D)->isDependentContext()) 2848 return; 2849 2850 if (S.hasUncompilableErrorOccurred()) { 2851 // Flush out any possibly unreachable diagnostics. 2852 flushDiagnostics(S, fscope); 2853 return; 2854 } 2855 2856 const Stmt *Body = D->getBody(); 2857 assert(Body); 2858 2859 // Construct the analysis context with the specified CFG build options. 2860 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D); 2861 2862 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2 2863 // explosion for destructors that can result and the compile time hit. 2864 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true; 2865 AC.getCFGBuildOptions().AddEHEdges = false; 2866 AC.getCFGBuildOptions().AddInitializers = true; 2867 AC.getCFGBuildOptions().AddImplicitDtors = true; 2868 AC.getCFGBuildOptions().AddTemporaryDtors = true; 2869 AC.getCFGBuildOptions().AddCXXNewAllocator = false; 2870 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true; 2871 2872 // Force that certain expressions appear as CFGElements in the CFG. This 2873 // is used to speed up various analyses. 2874 // FIXME: This isn't the right factoring. This is here for initial 2875 // prototyping, but we need a way for analyses to say what expressions they 2876 // expect to always be CFGElements and then fill in the BuildOptions 2877 // appropriately. This is essentially a layering violation. 2878 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis || 2879 P.enableConsumedAnalysis) { 2880 // Unreachable code analysis and thread safety require a linearized CFG. 2881 AC.getCFGBuildOptions().setAllAlwaysAdd(); 2882 } 2883 else { 2884 AC.getCFGBuildOptions() 2885 .setAlwaysAdd(Stmt::BinaryOperatorClass) 2886 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass) 2887 .setAlwaysAdd(Stmt::BlockExprClass) 2888 .setAlwaysAdd(Stmt::CStyleCastExprClass) 2889 .setAlwaysAdd(Stmt::DeclRefExprClass) 2890 .setAlwaysAdd(Stmt::ImplicitCastExprClass) 2891 .setAlwaysAdd(Stmt::UnaryOperatorClass); 2892 } 2893 2894 bool EnableLifetimeSafetyAnalysis = S.getLangOpts().EnableLifetimeSafety; 2895 // Install the logical handler. 2896 std::optional<LogicalErrorHandler> LEH; 2897 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) { 2898 LEH.emplace(S); 2899 AC.getCFGBuildOptions().Observer = &*LEH; 2900 } 2901 2902 // Emit delayed diagnostics. 2903 if (!fscope->PossiblyUnreachableDiags.empty()) { 2904 bool analyzed = false; 2905 2906 // Register the expressions with the CFGBuilder. 2907 for (const auto &D : fscope->PossiblyUnreachableDiags) { 2908 for (const Stmt *S : D.Stmts) 2909 AC.registerForcedBlockExpression(S); 2910 } 2911 2912 if (AC.getCFG()) { 2913 analyzed = true; 2914 for (const auto &D : fscope->PossiblyUnreachableDiags) { 2915 bool AllReachable = true; 2916 for (const Stmt *S : D.Stmts) { 2917 const CFGBlock *block = AC.getBlockForRegisteredExpression(S); 2918 CFGReverseBlockReachabilityAnalysis *cra = 2919 AC.getCFGReachablityAnalysis(); 2920 // FIXME: We should be able to assert that block is non-null, but 2921 // the CFG analysis can skip potentially-evaluated expressions in 2922 // edge cases; see test/Sema/vla-2.c. 2923 if (block && cra) { 2924 // Can this block be reached from the entrance? 2925 if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) { 2926 AllReachable = false; 2927 break; 2928 } 2929 } 2930 // If we cannot map to a basic block, assume the statement is 2931 // reachable. 2932 } 2933 2934 if (AllReachable) 2935 S.Diag(D.Loc, D.PD); 2936 } 2937 } 2938 2939 if (!analyzed) 2940 flushDiagnostics(S, fscope); 2941 } 2942 2943 // Warning: check missing 'return' 2944 if (P.enableCheckFallThrough) { 2945 const CheckFallThroughDiagnostics &CD = 2946 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock() 2947 : (isa<CXXMethodDecl>(D) && 2948 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call && 2949 cast<CXXMethodDecl>(D)->getParent()->isLambda()) 2950 ? CheckFallThroughDiagnostics::MakeForLambda() 2951 : (fscope->isCoroutine() 2952 ? CheckFallThroughDiagnostics::MakeForCoroutine(D) 2953 : CheckFallThroughDiagnostics::MakeForFunction(S, D))); 2954 CheckFallThroughForBody(S, D, Body, BlockType, CD, AC); 2955 } 2956 2957 // Warning: check for unreachable code 2958 if (P.enableCheckUnreachable) { 2959 // Only check for unreachable code on non-template instantiations. 2960 // Different template instantiations can effectively change the control-flow 2961 // and it is very difficult to prove that a snippet of code in a template 2962 // is unreachable for all instantiations. 2963 bool isTemplateInstantiation = false; 2964 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 2965 isTemplateInstantiation = Function->isTemplateInstantiation(); 2966 if (!isTemplateInstantiation) 2967 CheckUnreachable(S, AC); 2968 } 2969 2970 // Check for thread safety violations 2971 if (P.enableThreadSafetyAnalysis) { 2972 SourceLocation FL = AC.getDecl()->getLocation(); 2973 SourceLocation FEL = AC.getDecl()->getEndLoc(); 2974 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL); 2975 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc())) 2976 Reporter.setIssueBetaWarnings(true); 2977 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc())) 2978 Reporter.setVerbose(true); 2979 2980 threadSafety::runThreadSafetyAnalysis(AC, Reporter, 2981 &S.ThreadSafetyDeclCache); 2982 Reporter.emitDiagnostics(); 2983 } 2984 2985 // Check for violations of consumed properties. 2986 if (P.enableConsumedAnalysis) { 2987 consumed::ConsumedWarningsHandler WarningHandler(S); 2988 consumed::ConsumedAnalyzer Analyzer(WarningHandler); 2989 Analyzer.run(AC); 2990 } 2991 2992 if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) || 2993 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) || 2994 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc()) || 2995 !Diags.isIgnored(diag::warn_uninit_const_reference, D->getBeginLoc()) || 2996 !Diags.isIgnored(diag::warn_uninit_const_pointer, D->getBeginLoc())) { 2997 if (CFG *cfg = AC.getCFG()) { 2998 UninitValsDiagReporter reporter(S); 2999 UninitVariablesAnalysisStats stats; 3000 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats)); 3001 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC, 3002 reporter, stats); 3003 3004 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) { 3005 ++NumUninitAnalysisFunctions; 3006 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed; 3007 NumUninitAnalysisBlockVisits += stats.NumBlockVisits; 3008 MaxUninitAnalysisVariablesPerFunction = 3009 std::max(MaxUninitAnalysisVariablesPerFunction, 3010 stats.NumVariablesAnalyzed); 3011 MaxUninitAnalysisBlockVisitsPerFunction = 3012 std::max(MaxUninitAnalysisBlockVisitsPerFunction, 3013 stats.NumBlockVisits); 3014 } 3015 } 3016 } 3017 3018 // TODO: Enable lifetime safety analysis for other languages once it is 3019 // stable. 3020 if (EnableLifetimeSafetyAnalysis && S.getLangOpts().CPlusPlus) { 3021 if (CFG *cfg = AC.getCFG()) 3022 runLifetimeSafetyAnalysis(*cast<DeclContext>(D), *cfg, AC); 3023 } 3024 // Check for violations of "called once" parameter properties. 3025 if (S.getLangOpts().ObjC && !S.getLangOpts().CPlusPlus && 3026 shouldAnalyzeCalledOnceParameters(Diags, D->getBeginLoc())) { 3027 if (AC.getCFG()) { 3028 CalledOnceCheckReporter Reporter(S, IPData->CalledOnceData); 3029 checkCalledOnceParameters( 3030 AC, Reporter, 3031 shouldAnalyzeCalledOnceConventions(Diags, D->getBeginLoc())); 3032 } 3033 } 3034 3035 bool FallThroughDiagFull = 3036 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc()); 3037 bool FallThroughDiagPerFunction = !Diags.isIgnored( 3038 diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc()); 3039 if (FallThroughDiagFull || FallThroughDiagPerFunction || 3040 fscope->HasFallthroughStmt) { 3041 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull); 3042 } 3043 3044 if (S.getLangOpts().ObjCWeak && 3045 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc())) 3046 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap()); 3047 3048 3049 // Check for infinite self-recursion in functions 3050 if (!Diags.isIgnored(diag::warn_infinite_recursive_function, 3051 D->getBeginLoc())) { 3052 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3053 checkRecursiveFunction(S, FD, Body, AC); 3054 } 3055 } 3056 3057 // Check for throw out of non-throwing function. 3058 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc())) 3059 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 3060 if (S.getLangOpts().CPlusPlus && !fscope->isCoroutine() && isNoexcept(FD)) 3061 checkThrowInNonThrowingFunc(S, FD, AC); 3062 3063 // If none of the previous checks caused a CFG build, trigger one here 3064 // for the logical error handler. 3065 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) { 3066 AC.getCFG(); 3067 } 3068 3069 // Clear any of our policy overrides. 3070 clearOverrides(); 3071 3072 // Collect statistics about the CFG if it was built. 3073 if (S.CollectStats && AC.isCFGBuilt()) { 3074 ++NumFunctionsAnalyzed; 3075 if (CFG *cfg = AC.getCFG()) { 3076 // If we successfully built a CFG for this context, record some more 3077 // detail information about it. 3078 NumCFGBlocks += cfg->getNumBlockIDs(); 3079 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction, 3080 cfg->getNumBlockIDs()); 3081 } else { 3082 ++NumFunctionsWithBadCFGs; 3083 } 3084 } 3085 } 3086 3087 void clang::sema::AnalysisBasedWarnings::PrintStats() const { 3088 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n"; 3089 3090 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs; 3091 unsigned AvgCFGBlocksPerFunction = 3092 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt; 3093 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed (" 3094 << NumFunctionsWithBadCFGs << " w/o CFGs).\n" 3095 << " " << NumCFGBlocks << " CFG blocks built.\n" 3096 << " " << AvgCFGBlocksPerFunction 3097 << " average CFG blocks per function.\n" 3098 << " " << MaxCFGBlocksPerFunction 3099 << " max CFG blocks per function.\n"; 3100 3101 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0 3102 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions; 3103 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0 3104 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions; 3105 llvm::errs() << NumUninitAnalysisFunctions 3106 << " functions analyzed for uninitialiazed variables\n" 3107 << " " << NumUninitAnalysisVariables << " variables analyzed.\n" 3108 << " " << AvgUninitVariablesPerFunction 3109 << " average variables per function.\n" 3110 << " " << MaxUninitAnalysisVariablesPerFunction 3111 << " max variables per function.\n" 3112 << " " << NumUninitAnalysisBlockVisits << " block visits.\n" 3113 << " " << AvgUninitBlockVisitsPerFunction 3114 << " average block visits per function.\n" 3115 << " " << MaxUninitAnalysisBlockVisitsPerFunction 3116 << " max block visits per function.\n"; 3117 } 3118