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