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