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