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