1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
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/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/EvaluatedExprVisitor.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/AST/RecursiveASTVisitor.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/AST/StmtObjC.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
27 #include "clang/Analysis/Analyses/Consumed.h"
28 #include "clang/Analysis/Analyses/ReachableCode.h"
29 #include "clang/Analysis/Analyses/ThreadSafety.h"
30 #include "clang/Analysis/Analyses/UninitializedValues.h"
31 #include "clang/Analysis/AnalysisDeclContext.h"
32 #include "clang/Analysis/CFG.h"
33 #include "clang/Analysis/CFGStmtMap.h"
34 #include "clang/Basic/SourceLocation.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "llvm/ADT/BitVector.h"
40 #include "llvm/ADT/MapVector.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringRef.h"
44 #include "llvm/Support/Casting.h"
45 #include <algorithm>
46 #include <deque>
47 #include <iterator>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // Unreachable code analysis.
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56   class UnreachableCodeHandler : public reachable_code::Callback {
57     Sema &S;
58     SourceRange PreviousSilenceableCondVal;
59 
60   public:
61     UnreachableCodeHandler(Sema &s) : S(s) {}
62 
63     void HandleUnreachable(reachable_code::UnreachableKind UK,
64                            SourceLocation L,
65                            SourceRange SilenceableCondVal,
66                            SourceRange R1,
67                            SourceRange R2) override {
68       // Avoid reporting multiple unreachable code diagnostics that are
69       // triggered by the same conditional value.
70       if (PreviousSilenceableCondVal.isValid() &&
71           SilenceableCondVal.isValid() &&
72           PreviousSilenceableCondVal == SilenceableCondVal)
73         return;
74       PreviousSilenceableCondVal = SilenceableCondVal;
75 
76       unsigned diag = diag::warn_unreachable;
77       switch (UK) {
78         case reachable_code::UK_Break:
79           diag = diag::warn_unreachable_break;
80           break;
81         case reachable_code::UK_Return:
82           diag = diag::warn_unreachable_return;
83           break;
84         case reachable_code::UK_Loop_Increment:
85           diag = diag::warn_unreachable_loop_increment;
86           break;
87         case reachable_code::UK_Other:
88           break;
89       }
90 
91       S.Diag(L, diag) << R1 << R2;
92 
93       SourceLocation Open = SilenceableCondVal.getBegin();
94       if (Open.isValid()) {
95         SourceLocation Close = SilenceableCondVal.getEnd();
96         Close = S.getLocForEndOfToken(Close);
97         if (Close.isValid()) {
98           S.Diag(Open, diag::note_unreachable_silence)
99             << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
100             << FixItHint::CreateInsertion(Close, ")");
101         }
102       }
103     }
104   };
105 } // anonymous namespace
106 
107 /// CheckUnreachable - Check for unreachable code.
108 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
109   // As a heuristic prune all diagnostics not in the main file.  Currently
110   // the majority of warnings in headers are false positives.  These
111   // are largely caused by configuration state, e.g. preprocessor
112   // defined code, etc.
113   //
114   // Note that this is also a performance optimization.  Analyzing
115   // headers many times can be expensive.
116   if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
117     return;
118 
119   UnreachableCodeHandler UC(S);
120   reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
121 }
122 
123 namespace {
124 /// Warn on logical operator errors in CFGBuilder
125 class LogicalErrorHandler : public CFGCallback {
126   Sema &S;
127 
128 public:
129   LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
130 
131   static bool HasMacroID(const Expr *E) {
132     if (E->getExprLoc().isMacroID())
133       return true;
134 
135     // Recurse to children.
136     for (const Stmt *SubStmt : E->children())
137       if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
138         if (HasMacroID(SubExpr))
139           return true;
140 
141     return false;
142   }
143 
144   void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
145     if (HasMacroID(B))
146       return;
147 
148     SourceRange DiagRange = B->getSourceRange();
149     S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
150         << DiagRange << isAlwaysTrue;
151   }
152 
153   void compareBitwiseEquality(const BinaryOperator *B,
154                               bool isAlwaysTrue) override {
155     if (HasMacroID(B))
156       return;
157 
158     SourceRange DiagRange = B->getSourceRange();
159     S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
160         << DiagRange << isAlwaysTrue;
161   }
162 };
163 } // anonymous namespace
164 
165 //===----------------------------------------------------------------------===//
166 // Check for infinite self-recursion in functions
167 //===----------------------------------------------------------------------===//
168 
169 // Returns true if the function is called anywhere within the CFGBlock.
170 // For member functions, the additional condition of being call from the
171 // this pointer is required.
172 static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
173   // Process all the Stmt's in this block to find any calls to FD.
174   for (const auto &B : Block) {
175     if (B.getKind() != CFGElement::Statement)
176       continue;
177 
178     const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
179     if (!CE || !CE->getCalleeDecl() ||
180         CE->getCalleeDecl()->getCanonicalDecl() != FD)
181       continue;
182 
183     // Skip function calls which are qualified with a templated class.
184     if (const DeclRefExpr *DRE =
185             dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
186       if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
187         if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
188             isa<TemplateSpecializationType>(NNS->getAsType())) {
189           continue;
190         }
191       }
192     }
193 
194     const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
195     if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
196         !MCE->getMethodDecl()->isVirtual())
197       return true;
198   }
199   return false;
200 }
201 
202 // Returns true if every path from the entry block passes through a call to FD.
203 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
204   llvm::SmallPtrSet<CFGBlock *, 16> Visited;
205   llvm::SmallVector<CFGBlock *, 16> WorkList;
206   // Keep track of whether we found at least one recursive path.
207   bool foundRecursion = false;
208 
209   const unsigned ExitID = cfg->getExit().getBlockID();
210 
211   // Seed the work list with the entry block.
212   WorkList.push_back(&cfg->getEntry());
213 
214   while (!WorkList.empty()) {
215     CFGBlock *Block = WorkList.pop_back_val();
216 
217     for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
218       if (CFGBlock *SuccBlock = *I) {
219         if (!Visited.insert(SuccBlock).second)
220           continue;
221 
222         // Found a path to the exit node without a recursive call.
223         if (ExitID == SuccBlock->getBlockID())
224           return false;
225 
226         // If the successor block contains a recursive call, end analysis there.
227         if (hasRecursiveCallInPath(FD, *SuccBlock)) {
228           foundRecursion = true;
229           continue;
230         }
231 
232         WorkList.push_back(SuccBlock);
233       }
234     }
235   }
236   return foundRecursion;
237 }
238 
239 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
240                                    const Stmt *Body, AnalysisDeclContext &AC) {
241   FD = FD->getCanonicalDecl();
242 
243   // Only run on non-templated functions and non-templated members of
244   // templated classes.
245   if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
246       FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
247     return;
248 
249   CFG *cfg = AC.getCFG();
250   if (!cfg) return;
251 
252   // If the exit block is unreachable, skip processing the function.
253   if (cfg->getExit().pred_empty())
254     return;
255 
256   // Emit diagnostic if a recursive function call is detected for all paths.
257   if (checkForRecursiveFunctionCall(FD, cfg))
258     S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
259 }
260 
261 //===----------------------------------------------------------------------===//
262 // Check for throw in a non-throwing function.
263 //===----------------------------------------------------------------------===//
264 
265 /// Determine whether an exception thrown by E, unwinding from ThrowBlock,
266 /// can reach ExitBlock.
267 static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
268                          CFG *Body) {
269   SmallVector<CFGBlock *, 16> Stack;
270   llvm::BitVector Queued(Body->getNumBlockIDs());
271 
272   Stack.push_back(&ThrowBlock);
273   Queued[ThrowBlock.getBlockID()] = true;
274 
275   while (!Stack.empty()) {
276     CFGBlock &UnwindBlock = *Stack.back();
277     Stack.pop_back();
278 
279     for (auto &Succ : UnwindBlock.succs()) {
280       if (!Succ.isReachable() || Queued[Succ->getBlockID()])
281         continue;
282 
283       if (Succ->getBlockID() == Body->getExit().getBlockID())
284         return true;
285 
286       if (auto *Catch =
287               dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
288         QualType Caught = Catch->getCaughtType();
289         if (Caught.isNull() || // catch (...) catches everything
290             !E->getSubExpr() || // throw; is considered cuaght by any handler
291             S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
292           // Exception doesn't escape via this path.
293           break;
294       } else {
295         Stack.push_back(Succ);
296         Queued[Succ->getBlockID()] = true;
297       }
298     }
299   }
300 
301   return false;
302 }
303 
304 static void visitReachableThrows(
305     CFG *BodyCFG,
306     llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
307   llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
308   clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
309   for (CFGBlock *B : *BodyCFG) {
310     if (!Reachable[B->getBlockID()])
311       continue;
312     for (CFGElement &E : *B) {
313       Optional<CFGStmt> S = E.getAs<CFGStmt>();
314       if (!S)
315         continue;
316       if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
317         Visit(Throw, *B);
318     }
319   }
320 }
321 
322 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
323                                                  const FunctionDecl *FD) {
324   if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
325       FD->getTypeSourceInfo()) {
326     S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
327     if (S.getLangOpts().CPlusPlus11 &&
328         (isa<CXXDestructorDecl>(FD) ||
329          FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
330          FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
331       if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
332                                          getAs<FunctionProtoType>())
333         S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
334             << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
335             << FD->getExceptionSpecSourceRange();
336     } else
337       S.Diag(FD->getLocation(), diag::note_throw_in_function)
338           << FD->getExceptionSpecSourceRange();
339   }
340 }
341 
342 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
343                                         AnalysisDeclContext &AC) {
344   CFG *BodyCFG = AC.getCFG();
345   if (!BodyCFG)
346     return;
347   if (BodyCFG->getExit().pred_empty())
348     return;
349   visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
350     if (throwEscapes(S, Throw, Block, BodyCFG))
351       EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
352   });
353 }
354 
355 static bool isNoexcept(const FunctionDecl *FD) {
356   const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
357   if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
358     return true;
359   return false;
360 }
361 
362 //===----------------------------------------------------------------------===//
363 // Check for missing return value.
364 //===----------------------------------------------------------------------===//
365 
366 enum ControlFlowKind {
367   UnknownFallThrough,
368   NeverFallThrough,
369   MaybeFallThrough,
370   AlwaysFallThrough,
371   NeverFallThroughOrReturn
372 };
373 
374 /// CheckFallThrough - Check that we don't fall off the end of a
375 /// Statement that should return a value.
376 ///
377 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
378 /// MaybeFallThrough iff we might or might not fall off the end,
379 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
380 /// return.  We assume NeverFallThrough iff we never fall off the end of the
381 /// statement but we may return.  We assume that functions not marked noreturn
382 /// will return.
383 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
384   CFG *cfg = AC.getCFG();
385   if (!cfg) return UnknownFallThrough;
386 
387   // The CFG leaves in dead things, and we don't want the dead code paths to
388   // confuse us, so we mark all live things first.
389   llvm::BitVector live(cfg->getNumBlockIDs());
390   unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
391                                                           live);
392 
393   bool AddEHEdges = AC.getAddEHEdges();
394   if (!AddEHEdges && count != cfg->getNumBlockIDs())
395     // When there are things remaining dead, and we didn't add EH edges
396     // from CallExprs to the catch clauses, we have to go back and
397     // mark them as live.
398     for (const auto *B : *cfg) {
399       if (!live[B->getBlockID()]) {
400         if (B->pred_begin() == B->pred_end()) {
401           if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
402             // When not adding EH edges from calls, catch clauses
403             // can otherwise seem dead.  Avoid noting them as dead.
404             count += reachable_code::ScanReachableFromBlock(B, live);
405           continue;
406         }
407       }
408     }
409 
410   // Now we know what is live, we check the live precessors of the exit block
411   // and look for fall through paths, being careful to ignore normal returns,
412   // and exceptional paths.
413   bool HasLiveReturn = false;
414   bool HasFakeEdge = false;
415   bool HasPlainEdge = false;
416   bool HasAbnormalEdge = false;
417 
418   // Ignore default cases that aren't likely to be reachable because all
419   // enums in a switch(X) have explicit case statements.
420   CFGBlock::FilterOptions FO;
421   FO.IgnoreDefaultsWithCoveredEnums = 1;
422 
423   for (CFGBlock::filtered_pred_iterator I =
424            cfg->getExit().filtered_pred_start_end(FO);
425        I.hasMore(); ++I) {
426     const CFGBlock &B = **I;
427     if (!live[B.getBlockID()])
428       continue;
429 
430     // Skip blocks which contain an element marked as no-return. They don't
431     // represent actually viable edges into the exit block, so mark them as
432     // abnormal.
433     if (B.hasNoReturnElement()) {
434       HasAbnormalEdge = true;
435       continue;
436     }
437 
438     // Destructors can appear after the 'return' in the CFG.  This is
439     // normal.  We need to look pass the destructors for the return
440     // statement (if it exists).
441     CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
442 
443     for ( ; ri != re ; ++ri)
444       if (ri->getAs<CFGStmt>())
445         break;
446 
447     // No more CFGElements in the block?
448     if (ri == re) {
449       if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
450         HasAbnormalEdge = true;
451         continue;
452       }
453       // A labeled empty statement, or the entry block...
454       HasPlainEdge = true;
455       continue;
456     }
457 
458     CFGStmt CS = ri->castAs<CFGStmt>();
459     const Stmt *S = CS.getStmt();
460     if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
461       HasLiveReturn = true;
462       continue;
463     }
464     if (isa<ObjCAtThrowStmt>(S)) {
465       HasFakeEdge = true;
466       continue;
467     }
468     if (isa<CXXThrowExpr>(S)) {
469       HasFakeEdge = true;
470       continue;
471     }
472     if (isa<MSAsmStmt>(S)) {
473       // TODO: Verify this is correct.
474       HasFakeEdge = true;
475       HasLiveReturn = true;
476       continue;
477     }
478     if (isa<CXXTryStmt>(S)) {
479       HasAbnormalEdge = true;
480       continue;
481     }
482     if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
483         == B.succ_end()) {
484       HasAbnormalEdge = true;
485       continue;
486     }
487 
488     HasPlainEdge = true;
489   }
490   if (!HasPlainEdge) {
491     if (HasLiveReturn)
492       return NeverFallThrough;
493     return NeverFallThroughOrReturn;
494   }
495   if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
496     return MaybeFallThrough;
497   // This says AlwaysFallThrough for calls to functions that are not marked
498   // noreturn, that don't return.  If people would like this warning to be more
499   // accurate, such functions should be marked as noreturn.
500   return AlwaysFallThrough;
501 }
502 
503 namespace {
504 
505 struct CheckFallThroughDiagnostics {
506   unsigned diag_MaybeFallThrough_HasNoReturn;
507   unsigned diag_MaybeFallThrough_ReturnsNonVoid;
508   unsigned diag_AlwaysFallThrough_HasNoReturn;
509   unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
510   unsigned diag_NeverFallThroughOrReturn;
511   enum { Function, Block, Lambda, Coroutine } funMode;
512   SourceLocation FuncLoc;
513 
514   static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
515     CheckFallThroughDiagnostics D;
516     D.FuncLoc = Func->getLocation();
517     D.diag_MaybeFallThrough_HasNoReturn =
518       diag::warn_falloff_noreturn_function;
519     D.diag_MaybeFallThrough_ReturnsNonVoid =
520       diag::warn_maybe_falloff_nonvoid_function;
521     D.diag_AlwaysFallThrough_HasNoReturn =
522       diag::warn_falloff_noreturn_function;
523     D.diag_AlwaysFallThrough_ReturnsNonVoid =
524       diag::warn_falloff_nonvoid_function;
525 
526     // Don't suggest that virtual functions be marked "noreturn", since they
527     // might be overridden by non-noreturn functions.
528     bool isVirtualMethod = false;
529     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
530       isVirtualMethod = Method->isVirtual();
531 
532     // Don't suggest that template instantiations be marked "noreturn"
533     bool isTemplateInstantiation = false;
534     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
535       isTemplateInstantiation = Function->isTemplateInstantiation();
536 
537     if (!isVirtualMethod && !isTemplateInstantiation)
538       D.diag_NeverFallThroughOrReturn =
539         diag::warn_suggest_noreturn_function;
540     else
541       D.diag_NeverFallThroughOrReturn = 0;
542 
543     D.funMode = Function;
544     return D;
545   }
546 
547   static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
548     CheckFallThroughDiagnostics D;
549     D.FuncLoc = Func->getLocation();
550     D.diag_MaybeFallThrough_HasNoReturn = 0;
551     D.diag_MaybeFallThrough_ReturnsNonVoid =
552         diag::warn_maybe_falloff_nonvoid_coroutine;
553     D.diag_AlwaysFallThrough_HasNoReturn = 0;
554     D.diag_AlwaysFallThrough_ReturnsNonVoid =
555         diag::warn_falloff_nonvoid_coroutine;
556     D.funMode = Coroutine;
557     return D;
558   }
559 
560   static CheckFallThroughDiagnostics MakeForBlock() {
561     CheckFallThroughDiagnostics D;
562     D.diag_MaybeFallThrough_HasNoReturn =
563       diag::err_noreturn_block_has_return_expr;
564     D.diag_MaybeFallThrough_ReturnsNonVoid =
565       diag::err_maybe_falloff_nonvoid_block;
566     D.diag_AlwaysFallThrough_HasNoReturn =
567       diag::err_noreturn_block_has_return_expr;
568     D.diag_AlwaysFallThrough_ReturnsNonVoid =
569       diag::err_falloff_nonvoid_block;
570     D.diag_NeverFallThroughOrReturn = 0;
571     D.funMode = Block;
572     return D;
573   }
574 
575   static CheckFallThroughDiagnostics MakeForLambda() {
576     CheckFallThroughDiagnostics D;
577     D.diag_MaybeFallThrough_HasNoReturn =
578       diag::err_noreturn_lambda_has_return_expr;
579     D.diag_MaybeFallThrough_ReturnsNonVoid =
580       diag::warn_maybe_falloff_nonvoid_lambda;
581     D.diag_AlwaysFallThrough_HasNoReturn =
582       diag::err_noreturn_lambda_has_return_expr;
583     D.diag_AlwaysFallThrough_ReturnsNonVoid =
584       diag::warn_falloff_nonvoid_lambda;
585     D.diag_NeverFallThroughOrReturn = 0;
586     D.funMode = Lambda;
587     return D;
588   }
589 
590   bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
591                         bool HasNoReturn) const {
592     if (funMode == Function) {
593       return (ReturnsVoid ||
594               D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
595                           FuncLoc)) &&
596              (!HasNoReturn ||
597               D.isIgnored(diag::warn_noreturn_function_has_return_expr,
598                           FuncLoc)) &&
599              (!ReturnsVoid ||
600               D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
601     }
602     if (funMode == Coroutine) {
603       return (ReturnsVoid ||
604               D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
605               D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
606                           FuncLoc)) &&
607              (!HasNoReturn);
608     }
609     // For blocks / lambdas.
610     return ReturnsVoid && !HasNoReturn;
611   }
612 };
613 
614 } // anonymous namespace
615 
616 /// CheckFallThroughForBody - Check that we don't fall off the end of a
617 /// function that should return a value.  Check that we don't fall off the end
618 /// of a noreturn function.  We assume that functions and blocks not marked
619 /// noreturn will return.
620 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
621                                     const BlockExpr *blkExpr,
622                                     const CheckFallThroughDiagnostics &CD,
623                                     AnalysisDeclContext &AC,
624                                     sema::FunctionScopeInfo *FSI) {
625 
626   bool ReturnsVoid = false;
627   bool HasNoReturn = false;
628   bool IsCoroutine = FSI->isCoroutine();
629 
630   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
631     if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
632       ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
633     else
634       ReturnsVoid = FD->getReturnType()->isVoidType();
635     HasNoReturn = FD->isNoReturn();
636   }
637   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
638     ReturnsVoid = MD->getReturnType()->isVoidType();
639     HasNoReturn = MD->hasAttr<NoReturnAttr>();
640   }
641   else if (isa<BlockDecl>(D)) {
642     QualType BlockTy = blkExpr->getType();
643     if (const FunctionType *FT =
644           BlockTy->getPointeeType()->getAs<FunctionType>()) {
645       if (FT->getReturnType()->isVoidType())
646         ReturnsVoid = true;
647       if (FT->getNoReturnAttr())
648         HasNoReturn = true;
649     }
650   }
651 
652   DiagnosticsEngine &Diags = S.getDiagnostics();
653 
654   // Short circuit for compilation speed.
655   if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
656       return;
657   SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
658   auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
659     if (IsCoroutine)
660       S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
661     else
662       S.Diag(Loc, DiagID);
663   };
664 
665   // cpu_dispatch functions permit empty function bodies for ICC compatibility.
666   if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
667     return;
668 
669   // Either in a function body compound statement, or a function-try-block.
670   switch (CheckFallThrough(AC)) {
671     case UnknownFallThrough:
672       break;
673 
674     case MaybeFallThrough:
675       if (HasNoReturn)
676         EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
677       else if (!ReturnsVoid)
678         EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
679       break;
680     case AlwaysFallThrough:
681       if (HasNoReturn)
682         EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
683       else if (!ReturnsVoid)
684         EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
685       break;
686     case NeverFallThroughOrReturn:
687       if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
688         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
689           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
690         } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
691           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
692         } else {
693           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
694         }
695       }
696       break;
697     case NeverFallThrough:
698       break;
699   }
700 }
701 
702 //===----------------------------------------------------------------------===//
703 // -Wuninitialized
704 //===----------------------------------------------------------------------===//
705 
706 namespace {
707 /// ContainsReference - A visitor class to search for references to
708 /// a particular declaration (the needle) within any evaluated component of an
709 /// expression (recursively).
710 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
711   bool FoundReference;
712   const DeclRefExpr *Needle;
713 
714 public:
715   typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
716 
717   ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
718     : Inherited(Context), FoundReference(false), Needle(Needle) {}
719 
720   void VisitExpr(const Expr *E) {
721     // Stop evaluating if we already have a reference.
722     if (FoundReference)
723       return;
724 
725     Inherited::VisitExpr(E);
726   }
727 
728   void VisitDeclRefExpr(const DeclRefExpr *E) {
729     if (E == Needle)
730       FoundReference = true;
731     else
732       Inherited::VisitDeclRefExpr(E);
733   }
734 
735   bool doesContainReference() const { return FoundReference; }
736 };
737 } // anonymous namespace
738 
739 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
740   QualType VariableTy = VD->getType().getCanonicalType();
741   if (VariableTy->isBlockPointerType() &&
742       !VD->hasAttr<BlocksAttr>()) {
743     S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
744         << VD->getDeclName()
745         << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
746     return true;
747   }
748 
749   // Don't issue a fixit if there is already an initializer.
750   if (VD->getInit())
751     return false;
752 
753   // Don't suggest a fixit inside macros.
754   if (VD->getEndLoc().isMacroID())
755     return false;
756 
757   SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
758 
759   // Suggest possible initialization (if any).
760   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
761   if (Init.empty())
762     return false;
763 
764   S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
765     << FixItHint::CreateInsertion(Loc, Init);
766   return true;
767 }
768 
769 /// Create a fixit to remove an if-like statement, on the assumption that its
770 /// condition is CondVal.
771 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
772                           const Stmt *Else, bool CondVal,
773                           FixItHint &Fixit1, FixItHint &Fixit2) {
774   if (CondVal) {
775     // If condition is always true, remove all but the 'then'.
776     Fixit1 = FixItHint::CreateRemoval(
777         CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
778     if (Else) {
779       SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
780       Fixit2 =
781           FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
782     }
783   } else {
784     // If condition is always false, remove all but the 'else'.
785     if (Else)
786       Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
787           If->getBeginLoc(), Else->getBeginLoc()));
788     else
789       Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
790   }
791 }
792 
793 /// DiagUninitUse -- Helper function to produce a diagnostic for an
794 /// uninitialized use of a variable.
795 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
796                           bool IsCapturedByBlock) {
797   bool Diagnosed = false;
798 
799   switch (Use.getKind()) {
800   case UninitUse::Always:
801     S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
802         << VD->getDeclName() << IsCapturedByBlock
803         << Use.getUser()->getSourceRange();
804     return;
805 
806   case UninitUse::AfterDecl:
807   case UninitUse::AfterCall:
808     S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
809       << VD->getDeclName() << IsCapturedByBlock
810       << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
811       << const_cast<DeclContext*>(VD->getLexicalDeclContext())
812       << VD->getSourceRange();
813     S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
814         << IsCapturedByBlock << Use.getUser()->getSourceRange();
815     return;
816 
817   case UninitUse::Maybe:
818   case UninitUse::Sometimes:
819     // Carry on to report sometimes-uninitialized branches, if possible,
820     // or a 'may be used uninitialized' diagnostic otherwise.
821     break;
822   }
823 
824   // Diagnose each branch which leads to a sometimes-uninitialized use.
825   for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
826        I != E; ++I) {
827     assert(Use.getKind() == UninitUse::Sometimes);
828 
829     const Expr *User = Use.getUser();
830     const Stmt *Term = I->Terminator;
831 
832     // Information used when building the diagnostic.
833     unsigned DiagKind;
834     StringRef Str;
835     SourceRange Range;
836 
837     // FixIts to suppress the diagnostic by removing the dead condition.
838     // For all binary terminators, branch 0 is taken if the condition is true,
839     // and branch 1 is taken if the condition is false.
840     int RemoveDiagKind = -1;
841     const char *FixitStr =
842         S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
843                                   : (I->Output ? "1" : "0");
844     FixItHint Fixit1, Fixit2;
845 
846     switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
847     default:
848       // Don't know how to report this. Just fall back to 'may be used
849       // uninitialized'. FIXME: Can this happen?
850       continue;
851 
852     // "condition is true / condition is false".
853     case Stmt::IfStmtClass: {
854       const IfStmt *IS = cast<IfStmt>(Term);
855       DiagKind = 0;
856       Str = "if";
857       Range = IS->getCond()->getSourceRange();
858       RemoveDiagKind = 0;
859       CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
860                     I->Output, Fixit1, Fixit2);
861       break;
862     }
863     case Stmt::ConditionalOperatorClass: {
864       const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
865       DiagKind = 0;
866       Str = "?:";
867       Range = CO->getCond()->getSourceRange();
868       RemoveDiagKind = 0;
869       CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
870                     I->Output, Fixit1, Fixit2);
871       break;
872     }
873     case Stmt::BinaryOperatorClass: {
874       const BinaryOperator *BO = cast<BinaryOperator>(Term);
875       if (!BO->isLogicalOp())
876         continue;
877       DiagKind = 0;
878       Str = BO->getOpcodeStr();
879       Range = BO->getLHS()->getSourceRange();
880       RemoveDiagKind = 0;
881       if ((BO->getOpcode() == BO_LAnd && I->Output) ||
882           (BO->getOpcode() == BO_LOr && !I->Output))
883         // true && y -> y, false || y -> y.
884         Fixit1 = FixItHint::CreateRemoval(
885             SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
886       else
887         // false && y -> false, true || y -> true.
888         Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
889       break;
890     }
891 
892     // "loop is entered / loop is exited".
893     case Stmt::WhileStmtClass:
894       DiagKind = 1;
895       Str = "while";
896       Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
897       RemoveDiagKind = 1;
898       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
899       break;
900     case Stmt::ForStmtClass:
901       DiagKind = 1;
902       Str = "for";
903       Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
904       RemoveDiagKind = 1;
905       if (I->Output)
906         Fixit1 = FixItHint::CreateRemoval(Range);
907       else
908         Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
909       break;
910     case Stmt::CXXForRangeStmtClass:
911       if (I->Output == 1) {
912         // The use occurs if a range-based for loop's body never executes.
913         // That may be impossible, and there's no syntactic fix for this,
914         // so treat it as a 'may be uninitialized' case.
915         continue;
916       }
917       DiagKind = 1;
918       Str = "for";
919       Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
920       break;
921 
922     // "condition is true / loop is exited".
923     case Stmt::DoStmtClass:
924       DiagKind = 2;
925       Str = "do";
926       Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
927       RemoveDiagKind = 1;
928       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
929       break;
930 
931     // "switch case is taken".
932     case Stmt::CaseStmtClass:
933       DiagKind = 3;
934       Str = "case";
935       Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
936       break;
937     case Stmt::DefaultStmtClass:
938       DiagKind = 3;
939       Str = "default";
940       Range = cast<DefaultStmt>(Term)->getDefaultLoc();
941       break;
942     }
943 
944     S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
945       << VD->getDeclName() << IsCapturedByBlock << DiagKind
946       << Str << I->Output << Range;
947     S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
948         << IsCapturedByBlock << User->getSourceRange();
949     if (RemoveDiagKind != -1)
950       S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
951         << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
952 
953     Diagnosed = true;
954   }
955 
956   if (!Diagnosed)
957     S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
958         << VD->getDeclName() << IsCapturedByBlock
959         << Use.getUser()->getSourceRange();
960 }
961 
962 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
963 /// uninitialized variable. This manages the different forms of diagnostic
964 /// emitted for particular types of uses. Returns true if the use was diagnosed
965 /// as a warning. If a particular use is one we omit warnings for, returns
966 /// false.
967 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
968                                      const UninitUse &Use,
969                                      bool alwaysReportSelfInit = false) {
970   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
971     // Inspect the initializer of the variable declaration which is
972     // being referenced prior to its initialization. We emit
973     // specialized diagnostics for self-initialization, and we
974     // specifically avoid warning about self references which take the
975     // form of:
976     //
977     //   int x = x;
978     //
979     // This is used to indicate to GCC that 'x' is intentionally left
980     // uninitialized. Proven code paths which access 'x' in
981     // an uninitialized state after this will still warn.
982     if (const Expr *Initializer = VD->getInit()) {
983       if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
984         return false;
985 
986       ContainsReference CR(S.Context, DRE);
987       CR.Visit(Initializer);
988       if (CR.doesContainReference()) {
989         S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
990             << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
991         return true;
992       }
993     }
994 
995     DiagUninitUse(S, VD, Use, false);
996   } else {
997     const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
998     if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
999       S.Diag(BE->getBeginLoc(),
1000              diag::warn_uninit_byref_blockvar_captured_by_block)
1001           << VD->getDeclName()
1002           << VD->getType().getQualifiers().hasObjCLifetime();
1003     else
1004       DiagUninitUse(S, VD, Use, true);
1005   }
1006 
1007   // Report where the variable was declared when the use wasn't within
1008   // the initializer of that declaration & we didn't already suggest
1009   // an initialization fixit.
1010   if (!SuggestInitializationFixit(S, VD))
1011     S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
1012         << VD->getDeclName();
1013 
1014   return true;
1015 }
1016 
1017 namespace {
1018   class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1019   public:
1020     FallthroughMapper(Sema &S)
1021       : FoundSwitchStatements(false),
1022         S(S) {
1023     }
1024 
1025     bool foundSwitchStatements() const { return FoundSwitchStatements; }
1026 
1027     void markFallthroughVisited(const AttributedStmt *Stmt) {
1028       bool Found = FallthroughStmts.erase(Stmt);
1029       assert(Found);
1030       (void)Found;
1031     }
1032 
1033     typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1034 
1035     const AttrStmts &getFallthroughStmts() const {
1036       return FallthroughStmts;
1037     }
1038 
1039     void fillReachableBlocks(CFG *Cfg) {
1040       assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1041       std::deque<const CFGBlock *> BlockQueue;
1042 
1043       ReachableBlocks.insert(&Cfg->getEntry());
1044       BlockQueue.push_back(&Cfg->getEntry());
1045       // Mark all case blocks reachable to avoid problems with switching on
1046       // constants, covered enums, etc.
1047       // These blocks can contain fall-through annotations, and we don't want to
1048       // issue a warn_fallthrough_attr_unreachable for them.
1049       for (const auto *B : *Cfg) {
1050         const Stmt *L = B->getLabel();
1051         if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1052           BlockQueue.push_back(B);
1053       }
1054 
1055       while (!BlockQueue.empty()) {
1056         const CFGBlock *P = BlockQueue.front();
1057         BlockQueue.pop_front();
1058         for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1059                                            E = P->succ_end();
1060              I != E; ++I) {
1061           if (*I && ReachableBlocks.insert(*I).second)
1062             BlockQueue.push_back(*I);
1063         }
1064       }
1065     }
1066 
1067     bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1068                                    bool IsTemplateInstantiation) {
1069       assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1070 
1071       int UnannotatedCnt = 0;
1072       AnnotatedCnt = 0;
1073 
1074       std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
1075       while (!BlockQueue.empty()) {
1076         const CFGBlock *P = BlockQueue.front();
1077         BlockQueue.pop_front();
1078         if (!P) continue;
1079 
1080         const Stmt *Term = P->getTerminator();
1081         if (Term && isa<SwitchStmt>(Term))
1082           continue; // Switch statement, good.
1083 
1084         const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1085         if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1086           continue; // Previous case label has no statements, good.
1087 
1088         const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1089         if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1090           continue; // Case label is preceded with a normal label, good.
1091 
1092         if (!ReachableBlocks.count(P)) {
1093           for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1094                                                 ElemEnd = P->rend();
1095                ElemIt != ElemEnd; ++ElemIt) {
1096             if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1097               if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1098                 // Don't issue a warning for an unreachable fallthrough
1099                 // attribute in template instantiations as it may not be
1100                 // unreachable in all instantiations of the template.
1101                 if (!IsTemplateInstantiation)
1102                   S.Diag(AS->getBeginLoc(),
1103                          diag::warn_fallthrough_attr_unreachable);
1104                 markFallthroughVisited(AS);
1105                 ++AnnotatedCnt;
1106                 break;
1107               }
1108               // Don't care about other unreachable statements.
1109             }
1110           }
1111           // If there are no unreachable statements, this may be a special
1112           // case in CFG:
1113           // case X: {
1114           //    A a;  // A has a destructor.
1115           //    break;
1116           // }
1117           // // <<<< This place is represented by a 'hanging' CFG block.
1118           // case Y:
1119           continue;
1120         }
1121 
1122         const Stmt *LastStmt = getLastStmt(*P);
1123         if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1124           markFallthroughVisited(AS);
1125           ++AnnotatedCnt;
1126           continue; // Fallthrough annotation, good.
1127         }
1128 
1129         if (!LastStmt) { // This block contains no executable statements.
1130           // Traverse its predecessors.
1131           std::copy(P->pred_begin(), P->pred_end(),
1132                     std::back_inserter(BlockQueue));
1133           continue;
1134         }
1135 
1136         ++UnannotatedCnt;
1137       }
1138       return !!UnannotatedCnt;
1139     }
1140 
1141     // RecursiveASTVisitor setup.
1142     bool shouldWalkTypesOfTypeLocs() const { return false; }
1143 
1144     bool VisitAttributedStmt(AttributedStmt *S) {
1145       if (asFallThroughAttr(S))
1146         FallthroughStmts.insert(S);
1147       return true;
1148     }
1149 
1150     bool VisitSwitchStmt(SwitchStmt *S) {
1151       FoundSwitchStatements = true;
1152       return true;
1153     }
1154 
1155     // We don't want to traverse local type declarations. We analyze their
1156     // methods separately.
1157     bool TraverseDecl(Decl *D) { return true; }
1158 
1159     // We analyze lambda bodies separately. Skip them here.
1160     bool TraverseLambdaExpr(LambdaExpr *LE) {
1161       // Traverse the captures, but not the body.
1162       for (const auto &C : zip(LE->captures(), LE->capture_inits()))
1163         TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
1164       return true;
1165     }
1166 
1167   private:
1168 
1169     static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1170       if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1171         if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1172           return AS;
1173       }
1174       return nullptr;
1175     }
1176 
1177     static const Stmt *getLastStmt(const CFGBlock &B) {
1178       if (const Stmt *Term = B.getTerminator())
1179         return Term;
1180       for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1181                                             ElemEnd = B.rend();
1182                                             ElemIt != ElemEnd; ++ElemIt) {
1183         if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1184           return CS->getStmt();
1185       }
1186       // Workaround to detect a statement thrown out by CFGBuilder:
1187       //   case X: {} case Y:
1188       //   case X: ; case Y:
1189       if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1190         if (!isa<SwitchCase>(SW->getSubStmt()))
1191           return SW->getSubStmt();
1192 
1193       return nullptr;
1194     }
1195 
1196     bool FoundSwitchStatements;
1197     AttrStmts FallthroughStmts;
1198     Sema &S;
1199     llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1200   };
1201 } // anonymous namespace
1202 
1203 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1204                                             SourceLocation Loc) {
1205   TokenValue FallthroughTokens[] = {
1206     tok::l_square, tok::l_square,
1207     PP.getIdentifierInfo("fallthrough"),
1208     tok::r_square, tok::r_square
1209   };
1210 
1211   TokenValue ClangFallthroughTokens[] = {
1212     tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1213     tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1214     tok::r_square, tok::r_square
1215   };
1216 
1217   bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
1218 
1219   StringRef MacroName;
1220   if (PreferClangAttr)
1221     MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1222   if (MacroName.empty())
1223     MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1224   if (MacroName.empty() && !PreferClangAttr)
1225     MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1226   if (MacroName.empty())
1227     MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1228   return MacroName;
1229 }
1230 
1231 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1232                                             bool PerFunction) {
1233   // Only perform this analysis when using [[]] attributes. There is no good
1234   // workflow for this warning when not using C++11. There is no good way to
1235   // silence the warning (no attribute is available) unless we are using
1236   // [[]] attributes. One could use pragmas to silence the warning, but as a
1237   // general solution that is gross and not in the spirit of this warning.
1238   //
1239   // NOTE: This an intermediate solution. There are on-going discussions on
1240   // how to properly support this warning outside of C++11 with an annotation.
1241   if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
1242     return;
1243 
1244   FallthroughMapper FM(S);
1245   FM.TraverseStmt(AC.getBody());
1246 
1247   if (!FM.foundSwitchStatements())
1248     return;
1249 
1250   if (PerFunction && FM.getFallthroughStmts().empty())
1251     return;
1252 
1253   CFG *Cfg = AC.getCFG();
1254 
1255   if (!Cfg)
1256     return;
1257 
1258   FM.fillReachableBlocks(Cfg);
1259 
1260   for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1261     const Stmt *Label = B->getLabel();
1262 
1263     if (!Label || !isa<SwitchCase>(Label))
1264       continue;
1265 
1266     int AnnotatedCnt;
1267 
1268     bool IsTemplateInstantiation = false;
1269     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1270       IsTemplateInstantiation = Function->isTemplateInstantiation();
1271     if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1272                                       IsTemplateInstantiation))
1273       continue;
1274 
1275     S.Diag(Label->getBeginLoc(),
1276            PerFunction ? diag::warn_unannotated_fallthrough_per_function
1277                        : diag::warn_unannotated_fallthrough);
1278 
1279     if (!AnnotatedCnt) {
1280       SourceLocation L = Label->getBeginLoc();
1281       if (L.isMacroID())
1282         continue;
1283       if (S.getLangOpts().CPlusPlus11) {
1284         const Stmt *Term = B->getTerminator();
1285         // Skip empty cases.
1286         while (B->empty() && !Term && B->succ_size() == 1) {
1287           B = *B->succ_begin();
1288           Term = B->getTerminator();
1289         }
1290         if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1291           Preprocessor &PP = S.getPreprocessor();
1292           StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1293           SmallString<64> TextToInsert(AnnotationSpelling);
1294           TextToInsert += "; ";
1295           S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1296               AnnotationSpelling <<
1297               FixItHint::CreateInsertion(L, TextToInsert);
1298         }
1299       }
1300       S.Diag(L, diag::note_insert_break_fixit) <<
1301         FixItHint::CreateInsertion(L, "break; ");
1302     }
1303   }
1304 
1305   for (const auto *F : FM.getFallthroughStmts())
1306     S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
1307 }
1308 
1309 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1310                      const Stmt *S) {
1311   assert(S);
1312 
1313   do {
1314     switch (S->getStmtClass()) {
1315     case Stmt::ForStmtClass:
1316     case Stmt::WhileStmtClass:
1317     case Stmt::CXXForRangeStmtClass:
1318     case Stmt::ObjCForCollectionStmtClass:
1319       return true;
1320     case Stmt::DoStmtClass: {
1321       Expr::EvalResult Result;
1322       if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
1323         return true;
1324       return Result.Val.getInt().getBoolValue();
1325     }
1326     default:
1327       break;
1328     }
1329   } while ((S = PM.getParent(S)));
1330 
1331   return false;
1332 }
1333 
1334 static void diagnoseRepeatedUseOfWeak(Sema &S,
1335                                       const sema::FunctionScopeInfo *CurFn,
1336                                       const Decl *D,
1337                                       const ParentMap &PM) {
1338   typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1339   typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1340   typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1341   typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1342   StmtUsesPair;
1343 
1344   ASTContext &Ctx = S.getASTContext();
1345 
1346   const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1347 
1348   // Extract all weak objects that are referenced more than once.
1349   SmallVector<StmtUsesPair, 8> UsesByStmt;
1350   for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1351        I != E; ++I) {
1352     const WeakUseVector &Uses = I->second;
1353 
1354     // Find the first read of the weak object.
1355     WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1356     for ( ; UI != UE; ++UI) {
1357       if (UI->isUnsafe())
1358         break;
1359     }
1360 
1361     // If there were only writes to this object, don't warn.
1362     if (UI == UE)
1363       continue;
1364 
1365     // If there was only one read, followed by any number of writes, and the
1366     // read is not within a loop, don't warn. Additionally, don't warn in a
1367     // loop if the base object is a local variable -- local variables are often
1368     // changed in loops.
1369     if (UI == Uses.begin()) {
1370       WeakUseVector::const_iterator UI2 = UI;
1371       for (++UI2; UI2 != UE; ++UI2)
1372         if (UI2->isUnsafe())
1373           break;
1374 
1375       if (UI2 == UE) {
1376         if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1377           continue;
1378 
1379         const WeakObjectProfileTy &Profile = I->first;
1380         if (!Profile.isExactProfile())
1381           continue;
1382 
1383         const NamedDecl *Base = Profile.getBase();
1384         if (!Base)
1385           Base = Profile.getProperty();
1386         assert(Base && "A profile always has a base or property.");
1387 
1388         if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1389           if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1390             continue;
1391       }
1392     }
1393 
1394     UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1395   }
1396 
1397   if (UsesByStmt.empty())
1398     return;
1399 
1400   // Sort by first use so that we emit the warnings in a deterministic order.
1401   SourceManager &SM = S.getSourceManager();
1402   llvm::sort(UsesByStmt,
1403              [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1404                return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
1405                                                    RHS.first->getBeginLoc());
1406              });
1407 
1408   // Classify the current code body for better warning text.
1409   // This enum should stay in sync with the cases in
1410   // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1411   // FIXME: Should we use a common classification enum and the same set of
1412   // possibilities all throughout Sema?
1413   enum {
1414     Function,
1415     Method,
1416     Block,
1417     Lambda
1418   } FunctionKind;
1419 
1420   if (isa<sema::BlockScopeInfo>(CurFn))
1421     FunctionKind = Block;
1422   else if (isa<sema::LambdaScopeInfo>(CurFn))
1423     FunctionKind = Lambda;
1424   else if (isa<ObjCMethodDecl>(D))
1425     FunctionKind = Method;
1426   else
1427     FunctionKind = Function;
1428 
1429   // Iterate through the sorted problems and emit warnings for each.
1430   for (const auto &P : UsesByStmt) {
1431     const Stmt *FirstRead = P.first;
1432     const WeakObjectProfileTy &Key = P.second->first;
1433     const WeakUseVector &Uses = P.second->second;
1434 
1435     // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1436     // may not contain enough information to determine that these are different
1437     // properties. We can only be 100% sure of a repeated use in certain cases,
1438     // and we adjust the diagnostic kind accordingly so that the less certain
1439     // case can be turned off if it is too noisy.
1440     unsigned DiagKind;
1441     if (Key.isExactProfile())
1442       DiagKind = diag::warn_arc_repeated_use_of_weak;
1443     else
1444       DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1445 
1446     // Classify the weak object being accessed for better warning text.
1447     // This enum should stay in sync with the cases in
1448     // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1449     enum {
1450       Variable,
1451       Property,
1452       ImplicitProperty,
1453       Ivar
1454     } ObjectKind;
1455 
1456     const NamedDecl *KeyProp = Key.getProperty();
1457     if (isa<VarDecl>(KeyProp))
1458       ObjectKind = Variable;
1459     else if (isa<ObjCPropertyDecl>(KeyProp))
1460       ObjectKind = Property;
1461     else if (isa<ObjCMethodDecl>(KeyProp))
1462       ObjectKind = ImplicitProperty;
1463     else if (isa<ObjCIvarDecl>(KeyProp))
1464       ObjectKind = Ivar;
1465     else
1466       llvm_unreachable("Unexpected weak object kind!");
1467 
1468     // Do not warn about IBOutlet weak property receivers being set to null
1469     // since they are typically only used from the main thread.
1470     if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1471       if (Prop->hasAttr<IBOutletAttr>())
1472         continue;
1473 
1474     // Show the first time the object was read.
1475     S.Diag(FirstRead->getBeginLoc(), DiagKind)
1476         << int(ObjectKind) << KeyProp << int(FunctionKind)
1477         << FirstRead->getSourceRange();
1478 
1479     // Print all the other accesses as notes.
1480     for (const auto &Use : Uses) {
1481       if (Use.getUseExpr() == FirstRead)
1482         continue;
1483       S.Diag(Use.getUseExpr()->getBeginLoc(),
1484              diag::note_arc_weak_also_accessed_here)
1485           << Use.getUseExpr()->getSourceRange();
1486     }
1487   }
1488 }
1489 
1490 namespace {
1491 class UninitValsDiagReporter : public UninitVariablesHandler {
1492   Sema &S;
1493   typedef SmallVector<UninitUse, 2> UsesVec;
1494   typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1495   // Prefer using MapVector to DenseMap, so that iteration order will be
1496   // the same as insertion order. This is needed to obtain a deterministic
1497   // order of diagnostics when calling flushDiagnostics().
1498   typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1499   UsesMap uses;
1500 
1501 public:
1502   UninitValsDiagReporter(Sema &S) : S(S) {}
1503   ~UninitValsDiagReporter() override { flushDiagnostics(); }
1504 
1505   MappedType &getUses(const VarDecl *vd) {
1506     MappedType &V = uses[vd];
1507     if (!V.getPointer())
1508       V.setPointer(new UsesVec());
1509     return V;
1510   }
1511 
1512   void handleUseOfUninitVariable(const VarDecl *vd,
1513                                  const UninitUse &use) override {
1514     getUses(vd).getPointer()->push_back(use);
1515   }
1516 
1517   void handleSelfInit(const VarDecl *vd) override {
1518     getUses(vd).setInt(true);
1519   }
1520 
1521   void flushDiagnostics() {
1522     for (const auto &P : uses) {
1523       const VarDecl *vd = P.first;
1524       const MappedType &V = P.second;
1525 
1526       UsesVec *vec = V.getPointer();
1527       bool hasSelfInit = V.getInt();
1528 
1529       // Specially handle the case where we have uses of an uninitialized
1530       // variable, but the root cause is an idiomatic self-init.  We want
1531       // to report the diagnostic at the self-init since that is the root cause.
1532       if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1533         DiagnoseUninitializedUse(S, vd,
1534                                  UninitUse(vd->getInit()->IgnoreParenCasts(),
1535                                            /* isAlwaysUninit */ true),
1536                                  /* alwaysReportSelfInit */ true);
1537       else {
1538         // Sort the uses by their SourceLocations.  While not strictly
1539         // guaranteed to produce them in line/column order, this will provide
1540         // a stable ordering.
1541         llvm::sort(vec->begin(), vec->end(),
1542                    [](const UninitUse &a, const UninitUse &b) {
1543           // Prefer a more confident report over a less confident one.
1544           if (a.getKind() != b.getKind())
1545             return a.getKind() > b.getKind();
1546           return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
1547         });
1548 
1549         for (const auto &U : *vec) {
1550           // If we have self-init, downgrade all uses to 'may be uninitialized'.
1551           UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1552 
1553           if (DiagnoseUninitializedUse(S, vd, Use))
1554             // Skip further diagnostics for this variable. We try to warn only
1555             // on the first point at which a variable is used uninitialized.
1556             break;
1557         }
1558       }
1559 
1560       // Release the uses vector.
1561       delete vec;
1562     }
1563 
1564     uses.clear();
1565   }
1566 
1567 private:
1568   static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1569     return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1570       return U.getKind() == UninitUse::Always ||
1571              U.getKind() == UninitUse::AfterCall ||
1572              U.getKind() == UninitUse::AfterDecl;
1573     });
1574   }
1575 };
1576 } // anonymous namespace
1577 
1578 namespace clang {
1579 namespace {
1580 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1581 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1582 typedef std::list<DelayedDiag> DiagList;
1583 
1584 struct SortDiagBySourceLocation {
1585   SourceManager &SM;
1586   SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1587 
1588   bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1589     // Although this call will be slow, this is only called when outputting
1590     // multiple warnings.
1591     return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1592   }
1593 };
1594 } // anonymous namespace
1595 } // namespace clang
1596 
1597 //===----------------------------------------------------------------------===//
1598 // -Wthread-safety
1599 //===----------------------------------------------------------------------===//
1600 namespace clang {
1601 namespace threadSafety {
1602 namespace {
1603 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1604   Sema &S;
1605   DiagList Warnings;
1606   SourceLocation FunLocation, FunEndLocation;
1607 
1608   const FunctionDecl *CurrentFunction;
1609   bool Verbose;
1610 
1611   OptionalNotes getNotes() const {
1612     if (Verbose && CurrentFunction) {
1613       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1614                                 S.PDiag(diag::note_thread_warning_in_fun)
1615                                     << CurrentFunction);
1616       return OptionalNotes(1, FNote);
1617     }
1618     return OptionalNotes();
1619   }
1620 
1621   OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1622     OptionalNotes ONS(1, Note);
1623     if (Verbose && CurrentFunction) {
1624       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1625                                 S.PDiag(diag::note_thread_warning_in_fun)
1626                                     << CurrentFunction);
1627       ONS.push_back(std::move(FNote));
1628     }
1629     return ONS;
1630   }
1631 
1632   OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1633                          const PartialDiagnosticAt &Note2) const {
1634     OptionalNotes ONS;
1635     ONS.push_back(Note1);
1636     ONS.push_back(Note2);
1637     if (Verbose && CurrentFunction) {
1638       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1639                                 S.PDiag(diag::note_thread_warning_in_fun)
1640                                     << CurrentFunction);
1641       ONS.push_back(std::move(FNote));
1642     }
1643     return ONS;
1644   }
1645 
1646   OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) {
1647     return LocLocked.isValid()
1648                ? getNotes(PartialDiagnosticAt(
1649                      LocLocked, S.PDiag(diag::note_locked_here) << Kind))
1650                : getNotes();
1651   }
1652 
1653  public:
1654   ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1655     : S(S), FunLocation(FL), FunEndLocation(FEL),
1656       CurrentFunction(nullptr), Verbose(false) {}
1657 
1658   void setVerbose(bool b) { Verbose = b; }
1659 
1660   /// Emit all buffered diagnostics in order of sourcelocation.
1661   /// We need to output diagnostics produced while iterating through
1662   /// the lockset in deterministic order, so this function orders diagnostics
1663   /// and outputs them.
1664   void emitDiagnostics() {
1665     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1666     for (const auto &Diag : Warnings) {
1667       S.Diag(Diag.first.first, Diag.first.second);
1668       for (const auto &Note : Diag.second)
1669         S.Diag(Note.first, Note.second);
1670     }
1671   }
1672 
1673   void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1674     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1675                                          << Loc);
1676     Warnings.emplace_back(std::move(Warning), getNotes());
1677   }
1678 
1679   void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1680                              SourceLocation Loc) override {
1681     if (Loc.isInvalid())
1682       Loc = FunLocation;
1683     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock)
1684                                          << Kind << LockName);
1685     Warnings.emplace_back(std::move(Warning), getNotes());
1686   }
1687 
1688   void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1689                                  LockKind Expected, LockKind Received,
1690                                  SourceLocation LocLocked,
1691                                  SourceLocation LocUnlock) override {
1692     if (LocUnlock.isInvalid())
1693       LocUnlock = FunLocation;
1694     PartialDiagnosticAt Warning(
1695         LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch)
1696                        << Kind << LockName << Received << Expected);
1697     Warnings.emplace_back(std::move(Warning),
1698                           makeLockedHereNote(LocLocked, Kind));
1699   }
1700 
1701   void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked,
1702                         SourceLocation LocDoubleLock) override {
1703     if (LocDoubleLock.isInvalid())
1704       LocDoubleLock = FunLocation;
1705     PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock)
1706                                                    << Kind << LockName);
1707     Warnings.emplace_back(std::move(Warning),
1708                           makeLockedHereNote(LocLocked, Kind));
1709   }
1710 
1711   void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1712                                  SourceLocation LocLocked,
1713                                  SourceLocation LocEndOfScope,
1714                                  LockErrorKind LEK) override {
1715     unsigned DiagID = 0;
1716     switch (LEK) {
1717       case LEK_LockedSomePredecessors:
1718         DiagID = diag::warn_lock_some_predecessors;
1719         break;
1720       case LEK_LockedSomeLoopIterations:
1721         DiagID = diag::warn_expecting_lock_held_on_loop;
1722         break;
1723       case LEK_LockedAtEndOfFunction:
1724         DiagID = diag::warn_no_unlock;
1725         break;
1726       case LEK_NotLockedAtEndOfFunction:
1727         DiagID = diag::warn_expecting_locked;
1728         break;
1729     }
1730     if (LocEndOfScope.isInvalid())
1731       LocEndOfScope = FunEndLocation;
1732 
1733     PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1734                                                                << LockName);
1735     Warnings.emplace_back(std::move(Warning),
1736                           makeLockedHereNote(LocLocked, Kind));
1737   }
1738 
1739   void handleExclusiveAndShared(StringRef Kind, Name LockName,
1740                                 SourceLocation Loc1,
1741                                 SourceLocation Loc2) override {
1742     PartialDiagnosticAt Warning(Loc1,
1743                                 S.PDiag(diag::warn_lock_exclusive_and_shared)
1744                                     << Kind << LockName);
1745     PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1746                                        << Kind << LockName);
1747     Warnings.emplace_back(std::move(Warning), getNotes(Note));
1748   }
1749 
1750   void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1751                          ProtectedOperationKind POK, AccessKind AK,
1752                          SourceLocation Loc) override {
1753     assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1754            "Only works for variables");
1755     unsigned DiagID = POK == POK_VarAccess?
1756                         diag::warn_variable_requires_any_lock:
1757                         diag::warn_var_deref_requires_any_lock;
1758     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1759       << D << getLockKindFromAccessKind(AK));
1760     Warnings.emplace_back(std::move(Warning), getNotes());
1761   }
1762 
1763   void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1764                           ProtectedOperationKind POK, Name LockName,
1765                           LockKind LK, SourceLocation Loc,
1766                           Name *PossibleMatch) override {
1767     unsigned DiagID = 0;
1768     if (PossibleMatch) {
1769       switch (POK) {
1770         case POK_VarAccess:
1771           DiagID = diag::warn_variable_requires_lock_precise;
1772           break;
1773         case POK_VarDereference:
1774           DiagID = diag::warn_var_deref_requires_lock_precise;
1775           break;
1776         case POK_FunctionCall:
1777           DiagID = diag::warn_fun_requires_lock_precise;
1778           break;
1779         case POK_PassByRef:
1780           DiagID = diag::warn_guarded_pass_by_reference;
1781           break;
1782         case POK_PtPassByRef:
1783           DiagID = diag::warn_pt_guarded_pass_by_reference;
1784           break;
1785       }
1786       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1787                                                        << D
1788                                                        << LockName << LK);
1789       PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1790                                         << *PossibleMatch);
1791       if (Verbose && POK == POK_VarAccess) {
1792         PartialDiagnosticAt VNote(D->getLocation(),
1793                                  S.PDiag(diag::note_guarded_by_declared_here)
1794                                      << D->getNameAsString());
1795         Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1796       } else
1797         Warnings.emplace_back(std::move(Warning), getNotes(Note));
1798     } else {
1799       switch (POK) {
1800         case POK_VarAccess:
1801           DiagID = diag::warn_variable_requires_lock;
1802           break;
1803         case POK_VarDereference:
1804           DiagID = diag::warn_var_deref_requires_lock;
1805           break;
1806         case POK_FunctionCall:
1807           DiagID = diag::warn_fun_requires_lock;
1808           break;
1809         case POK_PassByRef:
1810           DiagID = diag::warn_guarded_pass_by_reference;
1811           break;
1812         case POK_PtPassByRef:
1813           DiagID = diag::warn_pt_guarded_pass_by_reference;
1814           break;
1815       }
1816       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1817                                                        << D
1818                                                        << LockName << LK);
1819       if (Verbose && POK == POK_VarAccess) {
1820         PartialDiagnosticAt Note(D->getLocation(),
1821                                  S.PDiag(diag::note_guarded_by_declared_here));
1822         Warnings.emplace_back(std::move(Warning), getNotes(Note));
1823       } else
1824         Warnings.emplace_back(std::move(Warning), getNotes());
1825     }
1826   }
1827 
1828   void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1829                              SourceLocation Loc) override {
1830     PartialDiagnosticAt Warning(Loc,
1831         S.PDiag(diag::warn_acquire_requires_negative_cap)
1832         << Kind << LockName << Neg);
1833     Warnings.emplace_back(std::move(Warning), getNotes());
1834   }
1835 
1836   void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1837                              SourceLocation Loc) override {
1838     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1839                                          << Kind << FunName << LockName);
1840     Warnings.emplace_back(std::move(Warning), getNotes());
1841   }
1842 
1843   void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1844                                 SourceLocation Loc) override {
1845     PartialDiagnosticAt Warning(Loc,
1846       S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1847     Warnings.emplace_back(std::move(Warning), getNotes());
1848   }
1849 
1850   void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1851     PartialDiagnosticAt Warning(Loc,
1852       S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1853     Warnings.emplace_back(std::move(Warning), getNotes());
1854   }
1855 
1856   void enterFunction(const FunctionDecl* FD) override {
1857     CurrentFunction = FD;
1858   }
1859 
1860   void leaveFunction(const FunctionDecl* FD) override {
1861     CurrentFunction = nullptr;
1862   }
1863 };
1864 } // anonymous namespace
1865 } // namespace threadSafety
1866 } // namespace clang
1867 
1868 //===----------------------------------------------------------------------===//
1869 // -Wconsumed
1870 //===----------------------------------------------------------------------===//
1871 
1872 namespace clang {
1873 namespace consumed {
1874 namespace {
1875 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1876 
1877   Sema &S;
1878   DiagList Warnings;
1879 
1880 public:
1881 
1882   ConsumedWarningsHandler(Sema &S) : S(S) {}
1883 
1884   void emitDiagnostics() override {
1885     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1886     for (const auto &Diag : Warnings) {
1887       S.Diag(Diag.first.first, Diag.first.second);
1888       for (const auto &Note : Diag.second)
1889         S.Diag(Note.first, Note.second);
1890     }
1891   }
1892 
1893   void warnLoopStateMismatch(SourceLocation Loc,
1894                              StringRef VariableName) override {
1895     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1896       VariableName);
1897 
1898     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1899   }
1900 
1901   void warnParamReturnTypestateMismatch(SourceLocation Loc,
1902                                         StringRef VariableName,
1903                                         StringRef ExpectedState,
1904                                         StringRef ObservedState) override {
1905 
1906     PartialDiagnosticAt Warning(Loc, S.PDiag(
1907       diag::warn_param_return_typestate_mismatch) << VariableName <<
1908         ExpectedState << ObservedState);
1909 
1910     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1911   }
1912 
1913   void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1914                                   StringRef ObservedState) override {
1915 
1916     PartialDiagnosticAt Warning(Loc, S.PDiag(
1917       diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1918 
1919     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1920   }
1921 
1922   void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1923                                               StringRef TypeName) override {
1924     PartialDiagnosticAt Warning(Loc, S.PDiag(
1925       diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1926 
1927     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1928   }
1929 
1930   void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1931                                    StringRef ObservedState) override {
1932 
1933     PartialDiagnosticAt Warning(Loc, S.PDiag(
1934       diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1935 
1936     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1937   }
1938 
1939   void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1940                                    SourceLocation Loc) override {
1941 
1942     PartialDiagnosticAt Warning(Loc, S.PDiag(
1943       diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1944 
1945     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1946   }
1947 
1948   void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1949                              StringRef State, SourceLocation Loc) override {
1950 
1951     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1952                                 MethodName << VariableName << State);
1953 
1954     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1955   }
1956 };
1957 } // anonymous namespace
1958 } // namespace consumed
1959 } // namespace clang
1960 
1961 //===----------------------------------------------------------------------===//
1962 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1963 //  warnings on a function, method, or block.
1964 //===----------------------------------------------------------------------===//
1965 
1966 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1967   enableCheckFallThrough = 1;
1968   enableCheckUnreachable = 0;
1969   enableThreadSafetyAnalysis = 0;
1970   enableConsumedAnalysis = 0;
1971 }
1972 
1973 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1974   return (unsigned)!D.isIgnored(diag, SourceLocation());
1975 }
1976 
1977 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1978   : S(s),
1979     NumFunctionsAnalyzed(0),
1980     NumFunctionsWithBadCFGs(0),
1981     NumCFGBlocks(0),
1982     MaxCFGBlocksPerFunction(0),
1983     NumUninitAnalysisFunctions(0),
1984     NumUninitAnalysisVariables(0),
1985     MaxUninitAnalysisVariablesPerFunction(0),
1986     NumUninitAnalysisBlockVisits(0),
1987     MaxUninitAnalysisBlockVisitsPerFunction(0) {
1988 
1989   using namespace diag;
1990   DiagnosticsEngine &D = S.getDiagnostics();
1991 
1992   DefaultPolicy.enableCheckUnreachable =
1993     isEnabled(D, warn_unreachable) ||
1994     isEnabled(D, warn_unreachable_break) ||
1995     isEnabled(D, warn_unreachable_return) ||
1996     isEnabled(D, warn_unreachable_loop_increment);
1997 
1998   DefaultPolicy.enableThreadSafetyAnalysis =
1999     isEnabled(D, warn_double_lock);
2000 
2001   DefaultPolicy.enableConsumedAnalysis =
2002     isEnabled(D, warn_use_in_invalid_state);
2003 }
2004 
2005 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2006   for (const auto &D : fscope->PossiblyUnreachableDiags)
2007     S.Diag(D.Loc, D.PD);
2008 }
2009 
2010 void clang::sema::
2011 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
2012                                      sema::FunctionScopeInfo *fscope,
2013                                      const Decl *D, const BlockExpr *blkExpr) {
2014 
2015   // We avoid doing analysis-based warnings when there are errors for
2016   // two reasons:
2017   // (1) The CFGs often can't be constructed (if the body is invalid), so
2018   //     don't bother trying.
2019   // (2) The code already has problems; running the analysis just takes more
2020   //     time.
2021   DiagnosticsEngine &Diags = S.getDiagnostics();
2022 
2023   // Do not do any analysis if we are going to just ignore them.
2024   if (Diags.getIgnoreAllWarnings() ||
2025       (Diags.getSuppressSystemWarnings() &&
2026        S.SourceMgr.isInSystemHeader(D->getLocation())))
2027     return;
2028 
2029   // For code in dependent contexts, we'll do this at instantiation time.
2030   if (cast<DeclContext>(D)->isDependentContext())
2031     return;
2032 
2033   if (Diags.hasUncompilableErrorOccurred()) {
2034     // Flush out any possibly unreachable diagnostics.
2035     flushDiagnostics(S, fscope);
2036     return;
2037   }
2038 
2039   const Stmt *Body = D->getBody();
2040   assert(Body);
2041 
2042   // Construct the analysis context with the specified CFG build options.
2043   AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
2044 
2045   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
2046   // explosion for destructors that can result and the compile time hit.
2047   AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2048   AC.getCFGBuildOptions().AddEHEdges = false;
2049   AC.getCFGBuildOptions().AddInitializers = true;
2050   AC.getCFGBuildOptions().AddImplicitDtors = true;
2051   AC.getCFGBuildOptions().AddTemporaryDtors = true;
2052   AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2053   AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2054 
2055   // Force that certain expressions appear as CFGElements in the CFG.  This
2056   // is used to speed up various analyses.
2057   // FIXME: This isn't the right factoring.  This is here for initial
2058   // prototyping, but we need a way for analyses to say what expressions they
2059   // expect to always be CFGElements and then fill in the BuildOptions
2060   // appropriately.  This is essentially a layering violation.
2061   if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2062       P.enableConsumedAnalysis) {
2063     // Unreachable code analysis and thread safety require a linearized CFG.
2064     AC.getCFGBuildOptions().setAllAlwaysAdd();
2065   }
2066   else {
2067     AC.getCFGBuildOptions()
2068       .setAlwaysAdd(Stmt::BinaryOperatorClass)
2069       .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
2070       .setAlwaysAdd(Stmt::BlockExprClass)
2071       .setAlwaysAdd(Stmt::CStyleCastExprClass)
2072       .setAlwaysAdd(Stmt::DeclRefExprClass)
2073       .setAlwaysAdd(Stmt::ImplicitCastExprClass)
2074       .setAlwaysAdd(Stmt::UnaryOperatorClass)
2075       .setAlwaysAdd(Stmt::AttributedStmtClass);
2076   }
2077 
2078   // Install the logical handler for -Wtautological-overlap-compare
2079   llvm::Optional<LogicalErrorHandler> LEH;
2080   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2081                        D->getBeginLoc())) {
2082     LEH.emplace(S);
2083     AC.getCFGBuildOptions().Observer = &*LEH;
2084   }
2085 
2086   // Emit delayed diagnostics.
2087   if (!fscope->PossiblyUnreachableDiags.empty()) {
2088     bool analyzed = false;
2089 
2090     // Register the expressions with the CFGBuilder.
2091     for (const auto &D : fscope->PossiblyUnreachableDiags) {
2092       for (const Stmt *S : D.Stmts)
2093         AC.registerForcedBlockExpression(S);
2094     }
2095 
2096     if (AC.getCFG()) {
2097       analyzed = true;
2098       for (const auto &D : fscope->PossiblyUnreachableDiags) {
2099         bool AllReachable = true;
2100         for (const Stmt *S : D.Stmts) {
2101           const CFGBlock *block = AC.getBlockForRegisteredExpression(S);
2102           CFGReverseBlockReachabilityAnalysis *cra =
2103               AC.getCFGReachablityAnalysis();
2104           // FIXME: We should be able to assert that block is non-null, but
2105           // the CFG analysis can skip potentially-evaluated expressions in
2106           // edge cases; see test/Sema/vla-2.c.
2107           if (block && cra) {
2108             // Can this block be reached from the entrance?
2109             if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) {
2110               AllReachable = false;
2111               break;
2112             }
2113           }
2114           // If we cannot map to a basic block, assume the statement is
2115           // reachable.
2116         }
2117 
2118         if (AllReachable)
2119           S.Diag(D.Loc, D.PD);
2120       }
2121     }
2122 
2123     if (!analyzed)
2124       flushDiagnostics(S, fscope);
2125   }
2126 
2127   // Warning: check missing 'return'
2128   if (P.enableCheckFallThrough) {
2129     const CheckFallThroughDiagnostics &CD =
2130         (isa<BlockDecl>(D)
2131              ? CheckFallThroughDiagnostics::MakeForBlock()
2132              : (isa<CXXMethodDecl>(D) &&
2133                 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2134                 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2135                    ? CheckFallThroughDiagnostics::MakeForLambda()
2136                    : (fscope->isCoroutine()
2137                           ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2138                           : CheckFallThroughDiagnostics::MakeForFunction(D)));
2139     CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
2140   }
2141 
2142   // Warning: check for unreachable code
2143   if (P.enableCheckUnreachable) {
2144     // Only check for unreachable code on non-template instantiations.
2145     // Different template instantiations can effectively change the control-flow
2146     // and it is very difficult to prove that a snippet of code in a template
2147     // is unreachable for all instantiations.
2148     bool isTemplateInstantiation = false;
2149     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2150       isTemplateInstantiation = Function->isTemplateInstantiation();
2151     if (!isTemplateInstantiation)
2152       CheckUnreachable(S, AC);
2153   }
2154 
2155   // Check for thread safety violations
2156   if (P.enableThreadSafetyAnalysis) {
2157     SourceLocation FL = AC.getDecl()->getLocation();
2158     SourceLocation FEL = AC.getDecl()->getEndLoc();
2159     threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2160     if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
2161       Reporter.setIssueBetaWarnings(true);
2162     if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
2163       Reporter.setVerbose(true);
2164 
2165     threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2166                                           &S.ThreadSafetyDeclCache);
2167     Reporter.emitDiagnostics();
2168   }
2169 
2170   // Check for violations of consumed properties.
2171   if (P.enableConsumedAnalysis) {
2172     consumed::ConsumedWarningsHandler WarningHandler(S);
2173     consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2174     Analyzer.run(AC);
2175   }
2176 
2177   if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
2178       !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
2179       !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) {
2180     if (CFG *cfg = AC.getCFG()) {
2181       UninitValsDiagReporter reporter(S);
2182       UninitVariablesAnalysisStats stats;
2183       std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2184       runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2185                                         reporter, stats);
2186 
2187       if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2188         ++NumUninitAnalysisFunctions;
2189         NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2190         NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2191         MaxUninitAnalysisVariablesPerFunction =
2192             std::max(MaxUninitAnalysisVariablesPerFunction,
2193                      stats.NumVariablesAnalyzed);
2194         MaxUninitAnalysisBlockVisitsPerFunction =
2195             std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2196                      stats.NumBlockVisits);
2197       }
2198     }
2199   }
2200 
2201   bool FallThroughDiagFull =
2202       !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
2203   bool FallThroughDiagPerFunction = !Diags.isIgnored(
2204       diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
2205   if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2206       fscope->HasFallthroughStmt) {
2207     DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2208   }
2209 
2210   if (S.getLangOpts().ObjCWeak &&
2211       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
2212     diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2213 
2214 
2215   // Check for infinite self-recursion in functions
2216   if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2217                        D->getBeginLoc())) {
2218     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2219       checkRecursiveFunction(S, FD, Body, AC);
2220     }
2221   }
2222 
2223   // Check for throw out of non-throwing function.
2224   if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
2225     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2226       if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2227         checkThrowInNonThrowingFunc(S, FD, AC);
2228 
2229   // If none of the previous checks caused a CFG build, trigger one here
2230   // for -Wtautological-overlap-compare
2231   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2232                        D->getBeginLoc())) {
2233     AC.getCFG();
2234   }
2235 
2236   // Collect statistics about the CFG if it was built.
2237   if (S.CollectStats && AC.isCFGBuilt()) {
2238     ++NumFunctionsAnalyzed;
2239     if (CFG *cfg = AC.getCFG()) {
2240       // If we successfully built a CFG for this context, record some more
2241       // detail information about it.
2242       NumCFGBlocks += cfg->getNumBlockIDs();
2243       MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2244                                          cfg->getNumBlockIDs());
2245     } else {
2246       ++NumFunctionsWithBadCFGs;
2247     }
2248   }
2249 }
2250 
2251 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2252   llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2253 
2254   unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2255   unsigned AvgCFGBlocksPerFunction =
2256       !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2257   llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2258                << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2259                << "  " << NumCFGBlocks << " CFG blocks built.\n"
2260                << "  " << AvgCFGBlocksPerFunction
2261                << " average CFG blocks per function.\n"
2262                << "  " << MaxCFGBlocksPerFunction
2263                << " max CFG blocks per function.\n";
2264 
2265   unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2266       : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2267   unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2268       : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2269   llvm::errs() << NumUninitAnalysisFunctions
2270                << " functions analyzed for uninitialiazed variables\n"
2271                << "  " << NumUninitAnalysisVariables << " variables analyzed.\n"
2272                << "  " << AvgUninitVariablesPerFunction
2273                << " average variables per function.\n"
2274                << "  " << MaxUninitAnalysisVariablesPerFunction
2275                << " max variables per function.\n"
2276                << "  " << NumUninitAnalysisBlockVisits << " block visits.\n"
2277                << "  " << AvgUninitBlockVisitsPerFunction
2278                << " average block visits per function.\n"
2279                << "  " << MaxUninitAnalysisBlockVisitsPerFunction
2280                << " max block visits per function.\n";
2281 }
2282