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