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