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