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