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