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