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 /// CheckFallThroughForFunctionDef - 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 
644   bool ReturnsVoid = false;
645   bool HasNoReturn = false;
646   bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
647 
648   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
649     if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
650       ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
651     else
652       ReturnsVoid = FD->getReturnType()->isVoidType();
653     HasNoReturn = FD->isNoReturn();
654   }
655   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
656     ReturnsVoid = MD->getReturnType()->isVoidType();
657     HasNoReturn = MD->hasAttr<NoReturnAttr>();
658   }
659   else if (isa<BlockDecl>(D)) {
660     QualType BlockTy = blkExpr->getType();
661     if (const FunctionType *FT =
662           BlockTy->getPointeeType()->getAs<FunctionType>()) {
663       if (FT->getReturnType()->isVoidType())
664         ReturnsVoid = true;
665       if (FT->getNoReturnAttr())
666         HasNoReturn = true;
667     }
668   }
669 
670   DiagnosticsEngine &Diags = S.getDiagnostics();
671 
672   // Short circuit for compilation speed.
673   if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
674       return;
675   SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
676   auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
677     if (IsCoroutine)
678       S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
679     else
680       S.Diag(Loc, DiagID);
681   };
682   // Either in a function body compound statement, or a function-try-block.
683   switch (CheckFallThrough(AC)) {
684     case UnknownFallThrough:
685       break;
686 
687     case MaybeFallThrough:
688       if (HasNoReturn)
689         EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
690       else if (!ReturnsVoid)
691         EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
692       break;
693     case AlwaysFallThrough:
694       if (HasNoReturn)
695         EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
696       else if (!ReturnsVoid)
697         EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
698       break;
699     case NeverFallThroughOrReturn:
700       if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
701         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
702           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
703         } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
704           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
705         } else {
706           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
707         }
708       }
709       break;
710     case NeverFallThrough:
711       break;
712   }
713 }
714 
715 //===----------------------------------------------------------------------===//
716 // -Wuninitialized
717 //===----------------------------------------------------------------------===//
718 
719 namespace {
720 /// ContainsReference - A visitor class to search for references to
721 /// a particular declaration (the needle) within any evaluated component of an
722 /// expression (recursively).
723 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
724   bool FoundReference;
725   const DeclRefExpr *Needle;
726 
727 public:
728   typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
729 
730   ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
731     : Inherited(Context), FoundReference(false), Needle(Needle) {}
732 
733   void VisitExpr(const Expr *E) {
734     // Stop evaluating if we already have a reference.
735     if (FoundReference)
736       return;
737 
738     Inherited::VisitExpr(E);
739   }
740 
741   void VisitDeclRefExpr(const DeclRefExpr *E) {
742     if (E == Needle)
743       FoundReference = true;
744     else
745       Inherited::VisitDeclRefExpr(E);
746   }
747 
748   bool doesContainReference() const { return FoundReference; }
749 };
750 } // anonymous namespace
751 
752 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
753   QualType VariableTy = VD->getType().getCanonicalType();
754   if (VariableTy->isBlockPointerType() &&
755       !VD->hasAttr<BlocksAttr>()) {
756     S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
757         << VD->getDeclName()
758         << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
759     return true;
760   }
761 
762   // Don't issue a fixit if there is already an initializer.
763   if (VD->getInit())
764     return false;
765 
766   // Don't suggest a fixit inside macros.
767   if (VD->getLocEnd().isMacroID())
768     return false;
769 
770   SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
771 
772   // Suggest possible initialization (if any).
773   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
774   if (Init.empty())
775     return false;
776 
777   S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
778     << FixItHint::CreateInsertion(Loc, Init);
779   return true;
780 }
781 
782 /// Create a fixit to remove an if-like statement, on the assumption that its
783 /// condition is CondVal.
784 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
785                           const Stmt *Else, bool CondVal,
786                           FixItHint &Fixit1, FixItHint &Fixit2) {
787   if (CondVal) {
788     // If condition is always true, remove all but the 'then'.
789     Fixit1 = FixItHint::CreateRemoval(
790         CharSourceRange::getCharRange(If->getLocStart(),
791                                       Then->getLocStart()));
792     if (Else) {
793       SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
794       Fixit2 = FixItHint::CreateRemoval(
795           SourceRange(ElseKwLoc, Else->getLocEnd()));
796     }
797   } else {
798     // If condition is always false, remove all but the 'else'.
799     if (Else)
800       Fixit1 = FixItHint::CreateRemoval(
801           CharSourceRange::getCharRange(If->getLocStart(),
802                                         Else->getLocStart()));
803     else
804       Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
805   }
806 }
807 
808 /// DiagUninitUse -- Helper function to produce a diagnostic for an
809 /// uninitialized use of a variable.
810 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
811                           bool IsCapturedByBlock) {
812   bool Diagnosed = false;
813 
814   switch (Use.getKind()) {
815   case UninitUse::Always:
816     S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
817         << VD->getDeclName() << IsCapturedByBlock
818         << Use.getUser()->getSourceRange();
819     return;
820 
821   case UninitUse::AfterDecl:
822   case UninitUse::AfterCall:
823     S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
824       << VD->getDeclName() << IsCapturedByBlock
825       << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
826       << const_cast<DeclContext*>(VD->getLexicalDeclContext())
827       << VD->getSourceRange();
828     S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
829       << IsCapturedByBlock << Use.getUser()->getSourceRange();
830     return;
831 
832   case UninitUse::Maybe:
833   case UninitUse::Sometimes:
834     // Carry on to report sometimes-uninitialized branches, if possible,
835     // or a 'may be used uninitialized' diagnostic otherwise.
836     break;
837   }
838 
839   // Diagnose each branch which leads to a sometimes-uninitialized use.
840   for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
841        I != E; ++I) {
842     assert(Use.getKind() == UninitUse::Sometimes);
843 
844     const Expr *User = Use.getUser();
845     const Stmt *Term = I->Terminator;
846 
847     // Information used when building the diagnostic.
848     unsigned DiagKind;
849     StringRef Str;
850     SourceRange Range;
851 
852     // FixIts to suppress the diagnostic by removing the dead condition.
853     // For all binary terminators, branch 0 is taken if the condition is true,
854     // and branch 1 is taken if the condition is false.
855     int RemoveDiagKind = -1;
856     const char *FixitStr =
857         S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
858                                   : (I->Output ? "1" : "0");
859     FixItHint Fixit1, Fixit2;
860 
861     switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
862     default:
863       // Don't know how to report this. Just fall back to 'may be used
864       // uninitialized'. FIXME: Can this happen?
865       continue;
866 
867     // "condition is true / condition is false".
868     case Stmt::IfStmtClass: {
869       const IfStmt *IS = cast<IfStmt>(Term);
870       DiagKind = 0;
871       Str = "if";
872       Range = IS->getCond()->getSourceRange();
873       RemoveDiagKind = 0;
874       CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
875                     I->Output, Fixit1, Fixit2);
876       break;
877     }
878     case Stmt::ConditionalOperatorClass: {
879       const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
880       DiagKind = 0;
881       Str = "?:";
882       Range = CO->getCond()->getSourceRange();
883       RemoveDiagKind = 0;
884       CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
885                     I->Output, Fixit1, Fixit2);
886       break;
887     }
888     case Stmt::BinaryOperatorClass: {
889       const BinaryOperator *BO = cast<BinaryOperator>(Term);
890       if (!BO->isLogicalOp())
891         continue;
892       DiagKind = 0;
893       Str = BO->getOpcodeStr();
894       Range = BO->getLHS()->getSourceRange();
895       RemoveDiagKind = 0;
896       if ((BO->getOpcode() == BO_LAnd && I->Output) ||
897           (BO->getOpcode() == BO_LOr && !I->Output))
898         // true && y -> y, false || y -> y.
899         Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
900                                                       BO->getOperatorLoc()));
901       else
902         // false && y -> false, true || y -> true.
903         Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
904       break;
905     }
906 
907     // "loop is entered / loop is exited".
908     case Stmt::WhileStmtClass:
909       DiagKind = 1;
910       Str = "while";
911       Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
912       RemoveDiagKind = 1;
913       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
914       break;
915     case Stmt::ForStmtClass:
916       DiagKind = 1;
917       Str = "for";
918       Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
919       RemoveDiagKind = 1;
920       if (I->Output)
921         Fixit1 = FixItHint::CreateRemoval(Range);
922       else
923         Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
924       break;
925     case Stmt::CXXForRangeStmtClass:
926       if (I->Output == 1) {
927         // The use occurs if a range-based for loop's body never executes.
928         // That may be impossible, and there's no syntactic fix for this,
929         // so treat it as a 'may be uninitialized' case.
930         continue;
931       }
932       DiagKind = 1;
933       Str = "for";
934       Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
935       break;
936 
937     // "condition is true / loop is exited".
938     case Stmt::DoStmtClass:
939       DiagKind = 2;
940       Str = "do";
941       Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
942       RemoveDiagKind = 1;
943       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
944       break;
945 
946     // "switch case is taken".
947     case Stmt::CaseStmtClass:
948       DiagKind = 3;
949       Str = "case";
950       Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
951       break;
952     case Stmt::DefaultStmtClass:
953       DiagKind = 3;
954       Str = "default";
955       Range = cast<DefaultStmt>(Term)->getDefaultLoc();
956       break;
957     }
958 
959     S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
960       << VD->getDeclName() << IsCapturedByBlock << DiagKind
961       << Str << I->Output << Range;
962     S.Diag(User->getLocStart(), diag::note_uninit_var_use)
963       << IsCapturedByBlock << User->getSourceRange();
964     if (RemoveDiagKind != -1)
965       S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
966         << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
967 
968     Diagnosed = true;
969   }
970 
971   if (!Diagnosed)
972     S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
973         << VD->getDeclName() << IsCapturedByBlock
974         << Use.getUser()->getSourceRange();
975 }
976 
977 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
978 /// uninitialized variable. This manages the different forms of diagnostic
979 /// emitted for particular types of uses. Returns true if the use was diagnosed
980 /// as a warning. If a particular use is one we omit warnings for, returns
981 /// false.
982 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
983                                      const UninitUse &Use,
984                                      bool alwaysReportSelfInit = false) {
985   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
986     // Inspect the initializer of the variable declaration which is
987     // being referenced prior to its initialization. We emit
988     // specialized diagnostics for self-initialization, and we
989     // specifically avoid warning about self references which take the
990     // form of:
991     //
992     //   int x = x;
993     //
994     // This is used to indicate to GCC that 'x' is intentionally left
995     // uninitialized. Proven code paths which access 'x' in
996     // an uninitialized state after this will still warn.
997     if (const Expr *Initializer = VD->getInit()) {
998       if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
999         return false;
1000 
1001       ContainsReference CR(S.Context, DRE);
1002       CR.Visit(Initializer);
1003       if (CR.doesContainReference()) {
1004         S.Diag(DRE->getLocStart(),
1005                diag::warn_uninit_self_reference_in_init)
1006           << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1007         return true;
1008       }
1009     }
1010 
1011     DiagUninitUse(S, VD, Use, false);
1012   } else {
1013     const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
1014     if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1015       S.Diag(BE->getLocStart(),
1016              diag::warn_uninit_byref_blockvar_captured_by_block)
1017         << VD->getDeclName();
1018     else
1019       DiagUninitUse(S, VD, Use, true);
1020   }
1021 
1022   // Report where the variable was declared when the use wasn't within
1023   // the initializer of that declaration & we didn't already suggest
1024   // an initialization fixit.
1025   if (!SuggestInitializationFixit(S, VD))
1026     S.Diag(VD->getLocStart(), diag::note_var_declared_here)
1027       << VD->getDeclName();
1028 
1029   return true;
1030 }
1031 
1032 namespace {
1033   class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1034   public:
1035     FallthroughMapper(Sema &S)
1036       : FoundSwitchStatements(false),
1037         S(S) {
1038     }
1039 
1040     bool foundSwitchStatements() const { return FoundSwitchStatements; }
1041 
1042     void markFallthroughVisited(const AttributedStmt *Stmt) {
1043       bool Found = FallthroughStmts.erase(Stmt);
1044       assert(Found);
1045       (void)Found;
1046     }
1047 
1048     typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1049 
1050     const AttrStmts &getFallthroughStmts() const {
1051       return FallthroughStmts;
1052     }
1053 
1054     void fillReachableBlocks(CFG *Cfg) {
1055       assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1056       std::deque<const CFGBlock *> BlockQueue;
1057 
1058       ReachableBlocks.insert(&Cfg->getEntry());
1059       BlockQueue.push_back(&Cfg->getEntry());
1060       // Mark all case blocks reachable to avoid problems with switching on
1061       // constants, covered enums, etc.
1062       // These blocks can contain fall-through annotations, and we don't want to
1063       // issue a warn_fallthrough_attr_unreachable for them.
1064       for (const auto *B : *Cfg) {
1065         const Stmt *L = B->getLabel();
1066         if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1067           BlockQueue.push_back(B);
1068       }
1069 
1070       while (!BlockQueue.empty()) {
1071         const CFGBlock *P = BlockQueue.front();
1072         BlockQueue.pop_front();
1073         for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1074                                            E = P->succ_end();
1075              I != E; ++I) {
1076           if (*I && ReachableBlocks.insert(*I).second)
1077             BlockQueue.push_back(*I);
1078         }
1079       }
1080     }
1081 
1082     bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1083                                    bool IsTemplateInstantiation) {
1084       assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1085 
1086       int UnannotatedCnt = 0;
1087       AnnotatedCnt = 0;
1088 
1089       std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
1090       while (!BlockQueue.empty()) {
1091         const CFGBlock *P = BlockQueue.front();
1092         BlockQueue.pop_front();
1093         if (!P) continue;
1094 
1095         const Stmt *Term = P->getTerminator();
1096         if (Term && isa<SwitchStmt>(Term))
1097           continue; // Switch statement, good.
1098 
1099         const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1100         if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1101           continue; // Previous case label has no statements, good.
1102 
1103         const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1104         if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1105           continue; // Case label is preceded with a normal label, good.
1106 
1107         if (!ReachableBlocks.count(P)) {
1108           for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1109                                                 ElemEnd = P->rend();
1110                ElemIt != ElemEnd; ++ElemIt) {
1111             if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1112               if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1113                 // Don't issue a warning for an unreachable fallthrough
1114                 // attribute in template instantiations as it may not be
1115                 // unreachable in all instantiations of the template.
1116                 if (!IsTemplateInstantiation)
1117                   S.Diag(AS->getLocStart(),
1118                          diag::warn_fallthrough_attr_unreachable);
1119                 markFallthroughVisited(AS);
1120                 ++AnnotatedCnt;
1121                 break;
1122               }
1123               // Don't care about other unreachable statements.
1124             }
1125           }
1126           // If there are no unreachable statements, this may be a special
1127           // case in CFG:
1128           // case X: {
1129           //    A a;  // A has a destructor.
1130           //    break;
1131           // }
1132           // // <<<< This place is represented by a 'hanging' CFG block.
1133           // case Y:
1134           continue;
1135         }
1136 
1137         const Stmt *LastStmt = getLastStmt(*P);
1138         if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1139           markFallthroughVisited(AS);
1140           ++AnnotatedCnt;
1141           continue; // Fallthrough annotation, good.
1142         }
1143 
1144         if (!LastStmt) { // This block contains no executable statements.
1145           // Traverse its predecessors.
1146           std::copy(P->pred_begin(), P->pred_end(),
1147                     std::back_inserter(BlockQueue));
1148           continue;
1149         }
1150 
1151         ++UnannotatedCnt;
1152       }
1153       return !!UnannotatedCnt;
1154     }
1155 
1156     // RecursiveASTVisitor setup.
1157     bool shouldWalkTypesOfTypeLocs() const { return false; }
1158 
1159     bool VisitAttributedStmt(AttributedStmt *S) {
1160       if (asFallThroughAttr(S))
1161         FallthroughStmts.insert(S);
1162       return true;
1163     }
1164 
1165     bool VisitSwitchStmt(SwitchStmt *S) {
1166       FoundSwitchStatements = true;
1167       return true;
1168     }
1169 
1170     // We don't want to traverse local type declarations. We analyze their
1171     // methods separately.
1172     bool TraverseDecl(Decl *D) { return true; }
1173 
1174     // We analyze lambda bodies separately. Skip them here.
1175     bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1176 
1177   private:
1178 
1179     static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1180       if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1181         if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1182           return AS;
1183       }
1184       return nullptr;
1185     }
1186 
1187     static const Stmt *getLastStmt(const CFGBlock &B) {
1188       if (const Stmt *Term = B.getTerminator())
1189         return Term;
1190       for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1191                                             ElemEnd = B.rend();
1192                                             ElemIt != ElemEnd; ++ElemIt) {
1193         if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1194           return CS->getStmt();
1195       }
1196       // Workaround to detect a statement thrown out by CFGBuilder:
1197       //   case X: {} case Y:
1198       //   case X: ; case Y:
1199       if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1200         if (!isa<SwitchCase>(SW->getSubStmt()))
1201           return SW->getSubStmt();
1202 
1203       return nullptr;
1204     }
1205 
1206     bool FoundSwitchStatements;
1207     AttrStmts FallthroughStmts;
1208     Sema &S;
1209     llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1210   };
1211 } // anonymous namespace
1212 
1213 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1214                                             SourceLocation Loc) {
1215   TokenValue FallthroughTokens[] = {
1216     tok::l_square, tok::l_square,
1217     PP.getIdentifierInfo("fallthrough"),
1218     tok::r_square, tok::r_square
1219   };
1220 
1221   TokenValue ClangFallthroughTokens[] = {
1222     tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1223     tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1224     tok::r_square, tok::r_square
1225   };
1226 
1227   bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
1228 
1229   StringRef MacroName;
1230   if (PreferClangAttr)
1231     MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1232   if (MacroName.empty())
1233     MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1234   if (MacroName.empty() && !PreferClangAttr)
1235     MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1236   if (MacroName.empty())
1237     MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1238   return MacroName;
1239 }
1240 
1241 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1242                                             bool PerFunction) {
1243   // Only perform this analysis when using [[]] attributes. There is no good
1244   // workflow for this warning when not using C++11. There is no good way to
1245   // silence the warning (no attribute is available) unless we are using
1246   // [[]] attributes. One could use pragmas to silence the warning, but as a
1247   // general solution that is gross and not in the spirit of this warning.
1248   //
1249   // NOTE: This an intermediate solution. There are on-going discussions on
1250   // how to properly support this warning outside of C++11 with an annotation.
1251   if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
1252     return;
1253 
1254   FallthroughMapper FM(S);
1255   FM.TraverseStmt(AC.getBody());
1256 
1257   if (!FM.foundSwitchStatements())
1258     return;
1259 
1260   if (PerFunction && FM.getFallthroughStmts().empty())
1261     return;
1262 
1263   CFG *Cfg = AC.getCFG();
1264 
1265   if (!Cfg)
1266     return;
1267 
1268   FM.fillReachableBlocks(Cfg);
1269 
1270   for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1271     const Stmt *Label = B->getLabel();
1272 
1273     if (!Label || !isa<SwitchCase>(Label))
1274       continue;
1275 
1276     int AnnotatedCnt;
1277 
1278     bool IsTemplateInstantiation = false;
1279     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1280       IsTemplateInstantiation = Function->isTemplateInstantiation();
1281     if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1282                                       IsTemplateInstantiation))
1283       continue;
1284 
1285     S.Diag(Label->getLocStart(),
1286         PerFunction ? diag::warn_unannotated_fallthrough_per_function
1287                     : diag::warn_unannotated_fallthrough);
1288 
1289     if (!AnnotatedCnt) {
1290       SourceLocation L = Label->getLocStart();
1291       if (L.isMacroID())
1292         continue;
1293       if (S.getLangOpts().CPlusPlus11) {
1294         const Stmt *Term = B->getTerminator();
1295         // Skip empty cases.
1296         while (B->empty() && !Term && B->succ_size() == 1) {
1297           B = *B->succ_begin();
1298           Term = B->getTerminator();
1299         }
1300         if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1301           Preprocessor &PP = S.getPreprocessor();
1302           StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1303           SmallString<64> TextToInsert(AnnotationSpelling);
1304           TextToInsert += "; ";
1305           S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1306               AnnotationSpelling <<
1307               FixItHint::CreateInsertion(L, TextToInsert);
1308         }
1309       }
1310       S.Diag(L, diag::note_insert_break_fixit) <<
1311         FixItHint::CreateInsertion(L, "break; ");
1312     }
1313   }
1314 
1315   for (const auto *F : FM.getFallthroughStmts())
1316     S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1317 }
1318 
1319 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1320                      const Stmt *S) {
1321   assert(S);
1322 
1323   do {
1324     switch (S->getStmtClass()) {
1325     case Stmt::ForStmtClass:
1326     case Stmt::WhileStmtClass:
1327     case Stmt::CXXForRangeStmtClass:
1328     case Stmt::ObjCForCollectionStmtClass:
1329       return true;
1330     case Stmt::DoStmtClass: {
1331       const Expr *Cond = cast<DoStmt>(S)->getCond();
1332       llvm::APSInt Val;
1333       if (!Cond->EvaluateAsInt(Val, Ctx))
1334         return true;
1335       return Val.getBoolValue();
1336     }
1337     default:
1338       break;
1339     }
1340   } while ((S = PM.getParent(S)));
1341 
1342   return false;
1343 }
1344 
1345 static void diagnoseRepeatedUseOfWeak(Sema &S,
1346                                       const sema::FunctionScopeInfo *CurFn,
1347                                       const Decl *D,
1348                                       const ParentMap &PM) {
1349   typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1350   typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1351   typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1352   typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1353   StmtUsesPair;
1354 
1355   ASTContext &Ctx = S.getASTContext();
1356 
1357   const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1358 
1359   // Extract all weak objects that are referenced more than once.
1360   SmallVector<StmtUsesPair, 8> UsesByStmt;
1361   for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1362        I != E; ++I) {
1363     const WeakUseVector &Uses = I->second;
1364 
1365     // Find the first read of the weak object.
1366     WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1367     for ( ; UI != UE; ++UI) {
1368       if (UI->isUnsafe())
1369         break;
1370     }
1371 
1372     // If there were only writes to this object, don't warn.
1373     if (UI == UE)
1374       continue;
1375 
1376     // If there was only one read, followed by any number of writes, and the
1377     // read is not within a loop, don't warn. Additionally, don't warn in a
1378     // loop if the base object is a local variable -- local variables are often
1379     // changed in loops.
1380     if (UI == Uses.begin()) {
1381       WeakUseVector::const_iterator UI2 = UI;
1382       for (++UI2; UI2 != UE; ++UI2)
1383         if (UI2->isUnsafe())
1384           break;
1385 
1386       if (UI2 == UE) {
1387         if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1388           continue;
1389 
1390         const WeakObjectProfileTy &Profile = I->first;
1391         if (!Profile.isExactProfile())
1392           continue;
1393 
1394         const NamedDecl *Base = Profile.getBase();
1395         if (!Base)
1396           Base = Profile.getProperty();
1397         assert(Base && "A profile always has a base or property.");
1398 
1399         if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1400           if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1401             continue;
1402       }
1403     }
1404 
1405     UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1406   }
1407 
1408   if (UsesByStmt.empty())
1409     return;
1410 
1411   // Sort by first use so that we emit the warnings in a deterministic order.
1412   SourceManager &SM = S.getSourceManager();
1413   std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1414             [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1415     return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1416                                         RHS.first->getLocStart());
1417   });
1418 
1419   // Classify the current code body for better warning text.
1420   // This enum should stay in sync with the cases in
1421   // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1422   // FIXME: Should we use a common classification enum and the same set of
1423   // possibilities all throughout Sema?
1424   enum {
1425     Function,
1426     Method,
1427     Block,
1428     Lambda
1429   } FunctionKind;
1430 
1431   if (isa<sema::BlockScopeInfo>(CurFn))
1432     FunctionKind = Block;
1433   else if (isa<sema::LambdaScopeInfo>(CurFn))
1434     FunctionKind = Lambda;
1435   else if (isa<ObjCMethodDecl>(D))
1436     FunctionKind = Method;
1437   else
1438     FunctionKind = Function;
1439 
1440   // Iterate through the sorted problems and emit warnings for each.
1441   for (const auto &P : UsesByStmt) {
1442     const Stmt *FirstRead = P.first;
1443     const WeakObjectProfileTy &Key = P.second->first;
1444     const WeakUseVector &Uses = P.second->second;
1445 
1446     // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1447     // may not contain enough information to determine that these are different
1448     // properties. We can only be 100% sure of a repeated use in certain cases,
1449     // and we adjust the diagnostic kind accordingly so that the less certain
1450     // case can be turned off if it is too noisy.
1451     unsigned DiagKind;
1452     if (Key.isExactProfile())
1453       DiagKind = diag::warn_arc_repeated_use_of_weak;
1454     else
1455       DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1456 
1457     // Classify the weak object being accessed for better warning text.
1458     // This enum should stay in sync with the cases in
1459     // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1460     enum {
1461       Variable,
1462       Property,
1463       ImplicitProperty,
1464       Ivar
1465     } ObjectKind;
1466 
1467     const NamedDecl *KeyProp = Key.getProperty();
1468     if (isa<VarDecl>(KeyProp))
1469       ObjectKind = Variable;
1470     else if (isa<ObjCPropertyDecl>(KeyProp))
1471       ObjectKind = Property;
1472     else if (isa<ObjCMethodDecl>(KeyProp))
1473       ObjectKind = ImplicitProperty;
1474     else if (isa<ObjCIvarDecl>(KeyProp))
1475       ObjectKind = Ivar;
1476     else
1477       llvm_unreachable("Unexpected weak object kind!");
1478 
1479     // Do not warn about IBOutlet weak property receivers being set to null
1480     // since they are typically only used from the main thread.
1481     if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1482       if (Prop->hasAttr<IBOutletAttr>())
1483         continue;
1484 
1485     // Show the first time the object was read.
1486     S.Diag(FirstRead->getLocStart(), DiagKind)
1487       << int(ObjectKind) << KeyProp << int(FunctionKind)
1488       << FirstRead->getSourceRange();
1489 
1490     // Print all the other accesses as notes.
1491     for (const auto &Use : Uses) {
1492       if (Use.getUseExpr() == FirstRead)
1493         continue;
1494       S.Diag(Use.getUseExpr()->getLocStart(),
1495              diag::note_arc_weak_also_accessed_here)
1496           << Use.getUseExpr()->getSourceRange();
1497     }
1498   }
1499 }
1500 
1501 namespace {
1502 class UninitValsDiagReporter : public UninitVariablesHandler {
1503   Sema &S;
1504   typedef SmallVector<UninitUse, 2> UsesVec;
1505   typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1506   // Prefer using MapVector to DenseMap, so that iteration order will be
1507   // the same as insertion order. This is needed to obtain a deterministic
1508   // order of diagnostics when calling flushDiagnostics().
1509   typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1510   UsesMap uses;
1511 
1512 public:
1513   UninitValsDiagReporter(Sema &S) : S(S) {}
1514   ~UninitValsDiagReporter() override { flushDiagnostics(); }
1515 
1516   MappedType &getUses(const VarDecl *vd) {
1517     MappedType &V = uses[vd];
1518     if (!V.getPointer())
1519       V.setPointer(new UsesVec());
1520     return V;
1521   }
1522 
1523   void handleUseOfUninitVariable(const VarDecl *vd,
1524                                  const UninitUse &use) override {
1525     getUses(vd).getPointer()->push_back(use);
1526   }
1527 
1528   void handleSelfInit(const VarDecl *vd) override {
1529     getUses(vd).setInt(true);
1530   }
1531 
1532   void flushDiagnostics() {
1533     for (const auto &P : uses) {
1534       const VarDecl *vd = P.first;
1535       const MappedType &V = P.second;
1536 
1537       UsesVec *vec = V.getPointer();
1538       bool hasSelfInit = V.getInt();
1539 
1540       // Specially handle the case where we have uses of an uninitialized
1541       // variable, but the root cause is an idiomatic self-init.  We want
1542       // to report the diagnostic at the self-init since that is the root cause.
1543       if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1544         DiagnoseUninitializedUse(S, vd,
1545                                  UninitUse(vd->getInit()->IgnoreParenCasts(),
1546                                            /* isAlwaysUninit */ true),
1547                                  /* alwaysReportSelfInit */ true);
1548       else {
1549         // Sort the uses by their SourceLocations.  While not strictly
1550         // guaranteed to produce them in line/column order, this will provide
1551         // a stable ordering.
1552         std::sort(vec->begin(), vec->end(),
1553                   [](const UninitUse &a, const UninitUse &b) {
1554           // Prefer a more confident report over a less confident one.
1555           if (a.getKind() != b.getKind())
1556             return a.getKind() > b.getKind();
1557           return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1558         });
1559 
1560         for (const auto &U : *vec) {
1561           // If we have self-init, downgrade all uses to 'may be uninitialized'.
1562           UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1563 
1564           if (DiagnoseUninitializedUse(S, vd, Use))
1565             // Skip further diagnostics for this variable. We try to warn only
1566             // on the first point at which a variable is used uninitialized.
1567             break;
1568         }
1569       }
1570 
1571       // Release the uses vector.
1572       delete vec;
1573     }
1574 
1575     uses.clear();
1576   }
1577 
1578 private:
1579   static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1580     return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1581       return U.getKind() == UninitUse::Always ||
1582              U.getKind() == UninitUse::AfterCall ||
1583              U.getKind() == UninitUse::AfterDecl;
1584     });
1585   }
1586 };
1587 } // anonymous namespace
1588 
1589 namespace clang {
1590 namespace {
1591 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1592 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1593 typedef std::list<DelayedDiag> DiagList;
1594 
1595 struct SortDiagBySourceLocation {
1596   SourceManager &SM;
1597   SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1598 
1599   bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1600     // Although this call will be slow, this is only called when outputting
1601     // multiple warnings.
1602     return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1603   }
1604 };
1605 } // anonymous namespace
1606 } // namespace clang
1607 
1608 //===----------------------------------------------------------------------===//
1609 // -Wthread-safety
1610 //===----------------------------------------------------------------------===//
1611 namespace clang {
1612 namespace threadSafety {
1613 namespace {
1614 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1615   Sema &S;
1616   DiagList Warnings;
1617   SourceLocation FunLocation, FunEndLocation;
1618 
1619   const FunctionDecl *CurrentFunction;
1620   bool Verbose;
1621 
1622   OptionalNotes getNotes() const {
1623     if (Verbose && CurrentFunction) {
1624       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1625                                 S.PDiag(diag::note_thread_warning_in_fun)
1626                                     << CurrentFunction->getNameAsString());
1627       return OptionalNotes(1, FNote);
1628     }
1629     return OptionalNotes();
1630   }
1631 
1632   OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1633     OptionalNotes ONS(1, Note);
1634     if (Verbose && CurrentFunction) {
1635       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1636                                 S.PDiag(diag::note_thread_warning_in_fun)
1637                                     << CurrentFunction->getNameAsString());
1638       ONS.push_back(std::move(FNote));
1639     }
1640     return ONS;
1641   }
1642 
1643   OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1644                          const PartialDiagnosticAt &Note2) const {
1645     OptionalNotes ONS;
1646     ONS.push_back(Note1);
1647     ONS.push_back(Note2);
1648     if (Verbose && CurrentFunction) {
1649       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1650                                 S.PDiag(diag::note_thread_warning_in_fun)
1651                                     << CurrentFunction->getNameAsString());
1652       ONS.push_back(std::move(FNote));
1653     }
1654     return ONS;
1655   }
1656 
1657   // Helper functions
1658   void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1659                         SourceLocation Loc) {
1660     // Gracefully handle rare cases when the analysis can't get a more
1661     // precise source location.
1662     if (!Loc.isValid())
1663       Loc = FunLocation;
1664     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1665     Warnings.emplace_back(std::move(Warning), getNotes());
1666   }
1667 
1668  public:
1669   ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1670     : S(S), FunLocation(FL), FunEndLocation(FEL),
1671       CurrentFunction(nullptr), Verbose(false) {}
1672 
1673   void setVerbose(bool b) { Verbose = b; }
1674 
1675   /// \brief Emit all buffered diagnostics in order of sourcelocation.
1676   /// We need to output diagnostics produced while iterating through
1677   /// the lockset in deterministic order, so this function orders diagnostics
1678   /// and outputs them.
1679   void emitDiagnostics() {
1680     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1681     for (const auto &Diag : Warnings) {
1682       S.Diag(Diag.first.first, Diag.first.second);
1683       for (const auto &Note : Diag.second)
1684         S.Diag(Note.first, Note.second);
1685     }
1686   }
1687 
1688   void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1689     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1690                                          << Loc);
1691     Warnings.emplace_back(std::move(Warning), getNotes());
1692   }
1693 
1694   void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1695                              SourceLocation Loc) override {
1696     warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1697   }
1698 
1699   void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1700                                  LockKind Expected, LockKind Received,
1701                                  SourceLocation Loc) override {
1702     if (Loc.isInvalid())
1703       Loc = FunLocation;
1704     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1705                                          << Kind << LockName << Received
1706                                          << Expected);
1707     Warnings.emplace_back(std::move(Warning), getNotes());
1708   }
1709 
1710   void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1711     warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1712   }
1713 
1714   void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1715                                  SourceLocation LocLocked,
1716                                  SourceLocation LocEndOfScope,
1717                                  LockErrorKind LEK) override {
1718     unsigned DiagID = 0;
1719     switch (LEK) {
1720       case LEK_LockedSomePredecessors:
1721         DiagID = diag::warn_lock_some_predecessors;
1722         break;
1723       case LEK_LockedSomeLoopIterations:
1724         DiagID = diag::warn_expecting_lock_held_on_loop;
1725         break;
1726       case LEK_LockedAtEndOfFunction:
1727         DiagID = diag::warn_no_unlock;
1728         break;
1729       case LEK_NotLockedAtEndOfFunction:
1730         DiagID = diag::warn_expecting_locked;
1731         break;
1732     }
1733     if (LocEndOfScope.isInvalid())
1734       LocEndOfScope = FunEndLocation;
1735 
1736     PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1737                                                                << LockName);
1738     if (LocLocked.isValid()) {
1739       PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1740                                               << Kind);
1741       Warnings.emplace_back(std::move(Warning), getNotes(Note));
1742       return;
1743     }
1744     Warnings.emplace_back(std::move(Warning), getNotes());
1745   }
1746 
1747   void handleExclusiveAndShared(StringRef Kind, Name LockName,
1748                                 SourceLocation Loc1,
1749                                 SourceLocation Loc2) override {
1750     PartialDiagnosticAt Warning(Loc1,
1751                                 S.PDiag(diag::warn_lock_exclusive_and_shared)
1752                                     << Kind << LockName);
1753     PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1754                                        << Kind << LockName);
1755     Warnings.emplace_back(std::move(Warning), getNotes(Note));
1756   }
1757 
1758   void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1759                          ProtectedOperationKind POK, AccessKind AK,
1760                          SourceLocation Loc) override {
1761     assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1762            "Only works for variables");
1763     unsigned DiagID = POK == POK_VarAccess?
1764                         diag::warn_variable_requires_any_lock:
1765                         diag::warn_var_deref_requires_any_lock;
1766     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1767       << D->getNameAsString() << getLockKindFromAccessKind(AK));
1768     Warnings.emplace_back(std::move(Warning), getNotes());
1769   }
1770 
1771   void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1772                           ProtectedOperationKind POK, Name LockName,
1773                           LockKind LK, SourceLocation Loc,
1774                           Name *PossibleMatch) override {
1775     unsigned DiagID = 0;
1776     if (PossibleMatch) {
1777       switch (POK) {
1778         case POK_VarAccess:
1779           DiagID = diag::warn_variable_requires_lock_precise;
1780           break;
1781         case POK_VarDereference:
1782           DiagID = diag::warn_var_deref_requires_lock_precise;
1783           break;
1784         case POK_FunctionCall:
1785           DiagID = diag::warn_fun_requires_lock_precise;
1786           break;
1787         case POK_PassByRef:
1788           DiagID = diag::warn_guarded_pass_by_reference;
1789           break;
1790         case POK_PtPassByRef:
1791           DiagID = diag::warn_pt_guarded_pass_by_reference;
1792           break;
1793       }
1794       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1795                                                        << D->getNameAsString()
1796                                                        << LockName << LK);
1797       PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1798                                         << *PossibleMatch);
1799       if (Verbose && POK == POK_VarAccess) {
1800         PartialDiagnosticAt VNote(D->getLocation(),
1801                                  S.PDiag(diag::note_guarded_by_declared_here)
1802                                      << D->getNameAsString());
1803         Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1804       } else
1805         Warnings.emplace_back(std::move(Warning), getNotes(Note));
1806     } else {
1807       switch (POK) {
1808         case POK_VarAccess:
1809           DiagID = diag::warn_variable_requires_lock;
1810           break;
1811         case POK_VarDereference:
1812           DiagID = diag::warn_var_deref_requires_lock;
1813           break;
1814         case POK_FunctionCall:
1815           DiagID = diag::warn_fun_requires_lock;
1816           break;
1817         case POK_PassByRef:
1818           DiagID = diag::warn_guarded_pass_by_reference;
1819           break;
1820         case POK_PtPassByRef:
1821           DiagID = diag::warn_pt_guarded_pass_by_reference;
1822           break;
1823       }
1824       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1825                                                        << D->getNameAsString()
1826                                                        << LockName << LK);
1827       if (Verbose && POK == POK_VarAccess) {
1828         PartialDiagnosticAt Note(D->getLocation(),
1829                                  S.PDiag(diag::note_guarded_by_declared_here)
1830                                      << D->getNameAsString());
1831         Warnings.emplace_back(std::move(Warning), getNotes(Note));
1832       } else
1833         Warnings.emplace_back(std::move(Warning), getNotes());
1834     }
1835   }
1836 
1837   void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1838                              SourceLocation Loc) override {
1839     PartialDiagnosticAt Warning(Loc,
1840         S.PDiag(diag::warn_acquire_requires_negative_cap)
1841         << Kind << LockName << Neg);
1842     Warnings.emplace_back(std::move(Warning), getNotes());
1843   }
1844 
1845   void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1846                              SourceLocation Loc) override {
1847     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1848                                          << Kind << FunName << LockName);
1849     Warnings.emplace_back(std::move(Warning), getNotes());
1850   }
1851 
1852   void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1853                                 SourceLocation Loc) override {
1854     PartialDiagnosticAt Warning(Loc,
1855       S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1856     Warnings.emplace_back(std::move(Warning), getNotes());
1857   }
1858 
1859   void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1860     PartialDiagnosticAt Warning(Loc,
1861       S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1862     Warnings.emplace_back(std::move(Warning), getNotes());
1863   }
1864 
1865   void enterFunction(const FunctionDecl* FD) override {
1866     CurrentFunction = FD;
1867   }
1868 
1869   void leaveFunction(const FunctionDecl* FD) override {
1870     CurrentFunction = nullptr;
1871   }
1872 };
1873 } // anonymous namespace
1874 } // namespace threadSafety
1875 } // namespace clang
1876 
1877 //===----------------------------------------------------------------------===//
1878 // -Wconsumed
1879 //===----------------------------------------------------------------------===//
1880 
1881 namespace clang {
1882 namespace consumed {
1883 namespace {
1884 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1885 
1886   Sema &S;
1887   DiagList Warnings;
1888 
1889 public:
1890 
1891   ConsumedWarningsHandler(Sema &S) : S(S) {}
1892 
1893   void emitDiagnostics() override {
1894     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1895     for (const auto &Diag : Warnings) {
1896       S.Diag(Diag.first.first, Diag.first.second);
1897       for (const auto &Note : Diag.second)
1898         S.Diag(Note.first, Note.second);
1899     }
1900   }
1901 
1902   void warnLoopStateMismatch(SourceLocation Loc,
1903                              StringRef VariableName) override {
1904     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1905       VariableName);
1906 
1907     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1908   }
1909 
1910   void warnParamReturnTypestateMismatch(SourceLocation Loc,
1911                                         StringRef VariableName,
1912                                         StringRef ExpectedState,
1913                                         StringRef ObservedState) override {
1914 
1915     PartialDiagnosticAt Warning(Loc, S.PDiag(
1916       diag::warn_param_return_typestate_mismatch) << VariableName <<
1917         ExpectedState << ObservedState);
1918 
1919     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1920   }
1921 
1922   void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1923                                   StringRef ObservedState) override {
1924 
1925     PartialDiagnosticAt Warning(Loc, S.PDiag(
1926       diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1927 
1928     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1929   }
1930 
1931   void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1932                                               StringRef TypeName) override {
1933     PartialDiagnosticAt Warning(Loc, S.PDiag(
1934       diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1935 
1936     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1937   }
1938 
1939   void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1940                                    StringRef ObservedState) override {
1941 
1942     PartialDiagnosticAt Warning(Loc, S.PDiag(
1943       diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1944 
1945     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1946   }
1947 
1948   void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1949                                    SourceLocation Loc) override {
1950 
1951     PartialDiagnosticAt Warning(Loc, S.PDiag(
1952       diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1953 
1954     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1955   }
1956 
1957   void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1958                              StringRef State, SourceLocation Loc) override {
1959 
1960     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1961                                 MethodName << VariableName << State);
1962 
1963     Warnings.emplace_back(std::move(Warning), OptionalNotes());
1964   }
1965 };
1966 } // anonymous namespace
1967 } // namespace consumed
1968 } // namespace clang
1969 
1970 //===----------------------------------------------------------------------===//
1971 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1972 //  warnings on a function, method, or block.
1973 //===----------------------------------------------------------------------===//
1974 
1975 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1976   enableCheckFallThrough = 1;
1977   enableCheckUnreachable = 0;
1978   enableThreadSafetyAnalysis = 0;
1979   enableConsumedAnalysis = 0;
1980 }
1981 
1982 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1983   return (unsigned)!D.isIgnored(diag, SourceLocation());
1984 }
1985 
1986 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1987   : S(s),
1988     NumFunctionsAnalyzed(0),
1989     NumFunctionsWithBadCFGs(0),
1990     NumCFGBlocks(0),
1991     MaxCFGBlocksPerFunction(0),
1992     NumUninitAnalysisFunctions(0),
1993     NumUninitAnalysisVariables(0),
1994     MaxUninitAnalysisVariablesPerFunction(0),
1995     NumUninitAnalysisBlockVisits(0),
1996     MaxUninitAnalysisBlockVisitsPerFunction(0) {
1997 
1998   using namespace diag;
1999   DiagnosticsEngine &D = S.getDiagnostics();
2000 
2001   DefaultPolicy.enableCheckUnreachable =
2002     isEnabled(D, warn_unreachable) ||
2003     isEnabled(D, warn_unreachable_break) ||
2004     isEnabled(D, warn_unreachable_return) ||
2005     isEnabled(D, warn_unreachable_loop_increment);
2006 
2007   DefaultPolicy.enableThreadSafetyAnalysis =
2008     isEnabled(D, warn_double_lock);
2009 
2010   DefaultPolicy.enableConsumedAnalysis =
2011     isEnabled(D, warn_use_in_invalid_state);
2012 }
2013 
2014 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2015   for (const auto &D : fscope->PossiblyUnreachableDiags)
2016     S.Diag(D.Loc, D.PD);
2017 }
2018 
2019 void clang::sema::
2020 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
2021                                      sema::FunctionScopeInfo *fscope,
2022                                      const Decl *D, const BlockExpr *blkExpr) {
2023 
2024   // We avoid doing analysis-based warnings when there are errors for
2025   // two reasons:
2026   // (1) The CFGs often can't be constructed (if the body is invalid), so
2027   //     don't bother trying.
2028   // (2) The code already has problems; running the analysis just takes more
2029   //     time.
2030   DiagnosticsEngine &Diags = S.getDiagnostics();
2031 
2032   // Do not do any analysis if we are going to just ignore them.
2033   if (Diags.getIgnoreAllWarnings() ||
2034       (Diags.getSuppressSystemWarnings() &&
2035        S.SourceMgr.isInSystemHeader(D->getLocation())))
2036     return;
2037 
2038   // For code in dependent contexts, we'll do this at instantiation time.
2039   if (cast<DeclContext>(D)->isDependentContext())
2040     return;
2041 
2042   if (Diags.hasUncompilableErrorOccurred()) {
2043     // Flush out any possibly unreachable diagnostics.
2044     flushDiagnostics(S, fscope);
2045     return;
2046   }
2047 
2048   const Stmt *Body = D->getBody();
2049   assert(Body);
2050 
2051   // Construct the analysis context with the specified CFG build options.
2052   AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
2053 
2054   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
2055   // explosion for destructors that can result and the compile time hit.
2056   AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2057   AC.getCFGBuildOptions().AddEHEdges = false;
2058   AC.getCFGBuildOptions().AddInitializers = true;
2059   AC.getCFGBuildOptions().AddImplicitDtors = true;
2060   AC.getCFGBuildOptions().AddTemporaryDtors = true;
2061   AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2062   AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2063 
2064   // Force that certain expressions appear as CFGElements in the CFG.  This
2065   // is used to speed up various analyses.
2066   // FIXME: This isn't the right factoring.  This is here for initial
2067   // prototyping, but we need a way for analyses to say what expressions they
2068   // expect to always be CFGElements and then fill in the BuildOptions
2069   // appropriately.  This is essentially a layering violation.
2070   if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2071       P.enableConsumedAnalysis) {
2072     // Unreachable code analysis and thread safety require a linearized CFG.
2073     AC.getCFGBuildOptions().setAllAlwaysAdd();
2074   }
2075   else {
2076     AC.getCFGBuildOptions()
2077       .setAlwaysAdd(Stmt::BinaryOperatorClass)
2078       .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
2079       .setAlwaysAdd(Stmt::BlockExprClass)
2080       .setAlwaysAdd(Stmt::CStyleCastExprClass)
2081       .setAlwaysAdd(Stmt::DeclRefExprClass)
2082       .setAlwaysAdd(Stmt::ImplicitCastExprClass)
2083       .setAlwaysAdd(Stmt::UnaryOperatorClass)
2084       .setAlwaysAdd(Stmt::AttributedStmtClass);
2085   }
2086 
2087   // Install the logical handler for -Wtautological-overlap-compare
2088   std::unique_ptr<LogicalErrorHandler> LEH;
2089   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2090                        D->getLocStart())) {
2091     LEH.reset(new LogicalErrorHandler(S));
2092     AC.getCFGBuildOptions().Observer = LEH.get();
2093   }
2094 
2095   // Emit delayed diagnostics.
2096   if (!fscope->PossiblyUnreachableDiags.empty()) {
2097     bool analyzed = false;
2098 
2099     // Register the expressions with the CFGBuilder.
2100     for (const auto &D : fscope->PossiblyUnreachableDiags) {
2101       if (D.stmt)
2102         AC.registerForcedBlockExpression(D.stmt);
2103     }
2104 
2105     if (AC.getCFG()) {
2106       analyzed = true;
2107       for (const auto &D : fscope->PossiblyUnreachableDiags) {
2108         bool processed = false;
2109         if (D.stmt) {
2110           const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
2111           CFGReverseBlockReachabilityAnalysis *cra =
2112               AC.getCFGReachablityAnalysis();
2113           // FIXME: We should be able to assert that block is non-null, but
2114           // the CFG analysis can skip potentially-evaluated expressions in
2115           // edge cases; see test/Sema/vla-2.c.
2116           if (block && cra) {
2117             // Can this block be reached from the entrance?
2118             if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2119               S.Diag(D.Loc, D.PD);
2120             processed = true;
2121           }
2122         }
2123         if (!processed) {
2124           // Emit the warning anyway if we cannot map to a basic block.
2125           S.Diag(D.Loc, D.PD);
2126         }
2127       }
2128     }
2129 
2130     if (!analyzed)
2131       flushDiagnostics(S, fscope);
2132   }
2133 
2134   // Warning: check missing 'return'
2135   if (P.enableCheckFallThrough) {
2136     const CheckFallThroughDiagnostics &CD =
2137         (isa<BlockDecl>(D)
2138              ? CheckFallThroughDiagnostics::MakeForBlock()
2139              : (isa<CXXMethodDecl>(D) &&
2140                 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2141                 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2142                    ? CheckFallThroughDiagnostics::MakeForLambda()
2143                    : (fscope->isCoroutine()
2144                           ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2145                           : CheckFallThroughDiagnostics::MakeForFunction(D)));
2146     CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
2147   }
2148 
2149   // Warning: check for unreachable code
2150   if (P.enableCheckUnreachable) {
2151     // Only check for unreachable code on non-template instantiations.
2152     // Different template instantiations can effectively change the control-flow
2153     // and it is very difficult to prove that a snippet of code in a template
2154     // is unreachable for all instantiations.
2155     bool isTemplateInstantiation = false;
2156     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2157       isTemplateInstantiation = Function->isTemplateInstantiation();
2158     if (!isTemplateInstantiation)
2159       CheckUnreachable(S, AC);
2160   }
2161 
2162   // Check for thread safety violations
2163   if (P.enableThreadSafetyAnalysis) {
2164     SourceLocation FL = AC.getDecl()->getLocation();
2165     SourceLocation FEL = AC.getDecl()->getLocEnd();
2166     threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2167     if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2168       Reporter.setIssueBetaWarnings(true);
2169     if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2170       Reporter.setVerbose(true);
2171 
2172     threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2173                                           &S.ThreadSafetyDeclCache);
2174     Reporter.emitDiagnostics();
2175   }
2176 
2177   // Check for violations of consumed properties.
2178   if (P.enableConsumedAnalysis) {
2179     consumed::ConsumedWarningsHandler WarningHandler(S);
2180     consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2181     Analyzer.run(AC);
2182   }
2183 
2184   if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2185       !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2186       !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2187     if (CFG *cfg = AC.getCFG()) {
2188       UninitValsDiagReporter reporter(S);
2189       UninitVariablesAnalysisStats stats;
2190       std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2191       runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2192                                         reporter, stats);
2193 
2194       if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2195         ++NumUninitAnalysisFunctions;
2196         NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2197         NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2198         MaxUninitAnalysisVariablesPerFunction =
2199             std::max(MaxUninitAnalysisVariablesPerFunction,
2200                      stats.NumVariablesAnalyzed);
2201         MaxUninitAnalysisBlockVisitsPerFunction =
2202             std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2203                      stats.NumBlockVisits);
2204       }
2205     }
2206   }
2207 
2208   bool FallThroughDiagFull =
2209       !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2210   bool FallThroughDiagPerFunction = !Diags.isIgnored(
2211       diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2212   if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2213       fscope->HasFallthroughStmt) {
2214     DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2215   }
2216 
2217   if (S.getLangOpts().ObjCWeak &&
2218       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2219     diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2220 
2221 
2222   // Check for infinite self-recursion in functions
2223   if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2224                        D->getLocStart())) {
2225     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2226       checkRecursiveFunction(S, FD, Body, AC);
2227     }
2228   }
2229 
2230   // Check for throw out of non-throwing function.
2231   if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2232     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2233       if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2234         checkThrowInNonThrowingFunc(S, FD, AC);
2235 
2236   // If none of the previous checks caused a CFG build, trigger one here
2237   // for -Wtautological-overlap-compare
2238   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2239                                D->getLocStart())) {
2240     AC.getCFG();
2241   }
2242 
2243   // Collect statistics about the CFG if it was built.
2244   if (S.CollectStats && AC.isCFGBuilt()) {
2245     ++NumFunctionsAnalyzed;
2246     if (CFG *cfg = AC.getCFG()) {
2247       // If we successfully built a CFG for this context, record some more
2248       // detail information about it.
2249       NumCFGBlocks += cfg->getNumBlockIDs();
2250       MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2251                                          cfg->getNumBlockIDs());
2252     } else {
2253       ++NumFunctionsWithBadCFGs;
2254     }
2255   }
2256 }
2257 
2258 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2259   llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2260 
2261   unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2262   unsigned AvgCFGBlocksPerFunction =
2263       !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2264   llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2265                << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2266                << "  " << NumCFGBlocks << " CFG blocks built.\n"
2267                << "  " << AvgCFGBlocksPerFunction
2268                << " average CFG blocks per function.\n"
2269                << "  " << MaxCFGBlocksPerFunction
2270                << " max CFG blocks per function.\n";
2271 
2272   unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2273       : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2274   unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2275       : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2276   llvm::errs() << NumUninitAnalysisFunctions
2277                << " functions analyzed for uninitialiazed variables\n"
2278                << "  " << NumUninitAnalysisVariables << " variables analyzed.\n"
2279                << "  " << AvgUninitVariablesPerFunction
2280                << " average variables per function.\n"
2281                << "  " << MaxUninitAnalysisVariablesPerFunction
2282                << " max variables per function.\n"
2283                << "  " << NumUninitAnalysisBlockVisits << " block visits.\n"
2284                << "  " << AvgUninitBlockVisitsPerFunction
2285                << " average block visits per function.\n"
2286                << "  " << MaxUninitAnalysisBlockVisitsPerFunction
2287                << " max block visits per function.\n";
2288 }
2289