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