clang  9.0.0
SemaStmt.cpp
Go to the documentation of this file.
1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for statements.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Ownership.h"
15 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/SmallVector.h"
41 
42 using namespace clang;
43 using namespace sema;
44 
45 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
46  if (FE.isInvalid())
47  return StmtError();
48 
49  FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
50  if (FE.isInvalid())
51  return StmtError();
52 
53  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54  // void expression for its side effects. Conversion to void allows any
55  // operand, even incomplete types.
56 
57  // Same thing in for stmt first clause (when expr) and third clause.
58  return StmtResult(FE.getAs<Stmt>());
59 }
60 
61 
63  DiscardCleanupsInEvaluationContext();
64  return StmtError();
65 }
66 
68  bool HasLeadingEmptyMacro) {
69  return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
70 }
71 
73  SourceLocation EndLoc) {
74  DeclGroupRef DG = dg.get();
75 
76  // If we have an invalid decl, just return an error.
77  if (DG.isNull()) return StmtError();
78 
79  return new (Context) DeclStmt(DG, StartLoc, EndLoc);
80 }
81 
83  DeclGroupRef DG = dg.get();
84 
85  // If we don't have a declaration, or we have an invalid declaration,
86  // just return.
87  if (DG.isNull() || !DG.isSingleDecl())
88  return;
89 
90  Decl *decl = DG.getSingleDecl();
91  if (!decl || decl->isInvalidDecl())
92  return;
93 
94  // Only variable declarations are permitted.
95  VarDecl *var = dyn_cast<VarDecl>(decl);
96  if (!var) {
97  Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98  decl->setInvalidDecl();
99  return;
100  }
101 
102  // foreach variables are never actually initialized in the way that
103  // the parser came up with.
104  var->setInit(nullptr);
105 
106  // In ARC, we don't need to retain the iteration variable of a fast
107  // enumeration loop. Rather than actually trying to catch that
108  // during declaration processing, we remove the consequences here.
109  if (getLangOpts().ObjCAutoRefCount) {
110  QualType type = var->getType();
111 
112  // Only do this if we inferred the lifetime. Inferred lifetime
113  // will show up as a local qualifier because explicit lifetime
114  // should have shown up as an AttributedType instead.
116  // Add 'const' and mark the variable as pseudo-strong.
117  var->setType(type.withConst());
118  var->setARCPseudoStrong(true);
119  }
120  }
121 }
122 
123 /// Diagnose unused comparisons, both builtin and overloaded operators.
124 /// For '==' and '!=', suggest fixits for '=' or '|='.
125 ///
126 /// Adding a cast to void (or other expression wrappers) will prevent the
127 /// warning from firing.
128 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
129  SourceLocation Loc;
130  bool CanAssign;
131  enum { Equality, Inequality, Relational, ThreeWay } Kind;
132 
133  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
134  if (!Op->isComparisonOp())
135  return false;
136 
137  if (Op->getOpcode() == BO_EQ)
138  Kind = Equality;
139  else if (Op->getOpcode() == BO_NE)
140  Kind = Inequality;
141  else if (Op->getOpcode() == BO_Cmp)
142  Kind = ThreeWay;
143  else {
144  assert(Op->isRelationalOp());
145  Kind = Relational;
146  }
147  Loc = Op->getOperatorLoc();
148  CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
149  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
150  switch (Op->getOperator()) {
151  case OO_EqualEqual:
152  Kind = Equality;
153  break;
154  case OO_ExclaimEqual:
155  Kind = Inequality;
156  break;
157  case OO_Less:
158  case OO_Greater:
159  case OO_GreaterEqual:
160  case OO_LessEqual:
161  Kind = Relational;
162  break;
163  case OO_Spaceship:
164  Kind = ThreeWay;
165  break;
166  default:
167  return false;
168  }
169 
170  Loc = Op->getOperatorLoc();
171  CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
172  } else {
173  // Not a typo-prone comparison.
174  return false;
175  }
176 
177  // Suppress warnings when the operator, suspicious as it may be, comes from
178  // a macro expansion.
179  if (S.SourceMgr.isMacroBodyExpansion(Loc))
180  return false;
181 
182  S.Diag(Loc, diag::warn_unused_comparison)
183  << (unsigned)Kind << E->getSourceRange();
184 
185  // If the LHS is a plausible entity to assign to, provide a fixit hint to
186  // correct common typos.
187  if (CanAssign) {
188  if (Kind == Inequality)
189  S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
190  << FixItHint::CreateReplacement(Loc, "|=");
191  else if (Kind == Equality)
192  S.Diag(Loc, diag::note_equality_comparison_to_assign)
193  << FixItHint::CreateReplacement(Loc, "=");
194  }
195 
196  return true;
197 }
198 
200  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
201  return DiagnoseUnusedExprResult(Label->getSubStmt());
202 
203  const Expr *E = dyn_cast_or_null<Expr>(S);
204  if (!E)
205  return;
206 
207  // If we are in an unevaluated expression context, then there can be no unused
208  // results because the results aren't expected to be used in the first place.
209  if (isUnevaluatedContext())
210  return;
211 
212  SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
213  // In most cases, we don't want to warn if the expression is written in a
214  // macro body, or if the macro comes from a system header. If the offending
215  // expression is a call to a function with the warn_unused_result attribute,
216  // we warn no matter the location. Because of the order in which the various
217  // checks need to happen, we factor out the macro-related test here.
218  bool ShouldSuppress =
219  SourceMgr.isMacroBodyExpansion(ExprLoc) ||
220  SourceMgr.isInSystemMacro(ExprLoc);
221 
222  const Expr *WarnExpr;
223  SourceLocation Loc;
224  SourceRange R1, R2;
225  if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
226  return;
227 
228  // If this is a GNU statement expression expanded from a macro, it is probably
229  // unused because it is a function-like macro that can be used as either an
230  // expression or statement. Don't warn, because it is almost certainly a
231  // false positive.
232  if (isa<StmtExpr>(E) && Loc.isMacroID())
233  return;
234 
235  // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
236  // That macro is frequently used to suppress "unused parameter" warnings,
237  // but its implementation makes clang's -Wunused-value fire. Prevent this.
238  if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
239  SourceLocation SpellLoc = Loc;
240  if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
241  return;
242  }
243 
244  // Okay, we have an unused result. Depending on what the base expression is,
245  // we might want to make a more specific diagnostic. Check for one of these
246  // cases now.
247  unsigned DiagID = diag::warn_unused_expr;
248  if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
249  E = Temps->getSubExpr();
250  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
251  E = TempExpr->getSubExpr();
252 
253  if (DiagnoseUnusedComparison(*this, E))
254  return;
255 
256  E = WarnExpr;
257  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
258  if (E->getType()->isVoidType())
259  return;
260 
261  if (const Attr *A = CE->getUnusedResultAttr(Context)) {
262  Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
263  return;
264  }
265 
266  // If the callee has attribute pure, const, or warn_unused_result, warn with
267  // a more specific message to make it clear what is happening. If the call
268  // is written in a macro body, only warn if it has the warn_unused_result
269  // attribute.
270  if (const Decl *FD = CE->getCalleeDecl()) {
271  if (ShouldSuppress)
272  return;
273  if (FD->hasAttr<PureAttr>()) {
274  Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
275  return;
276  }
277  if (FD->hasAttr<ConstAttr>()) {
278  Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
279  return;
280  }
281  }
282  } else if (ShouldSuppress)
283  return;
284 
285  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
286  if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
287  Diag(Loc, diag::err_arc_unused_init_message) << R1;
288  return;
289  }
290  const ObjCMethodDecl *MD = ME->getMethodDecl();
291  if (MD) {
292  if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
293  Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
294  return;
295  }
296  }
297  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
298  const Expr *Source = POE->getSyntacticForm();
299  if (isa<ObjCSubscriptRefExpr>(Source))
300  DiagID = diag::warn_unused_container_subscript_expr;
301  else
302  DiagID = diag::warn_unused_property_expr;
303  } else if (const CXXFunctionalCastExpr *FC
304  = dyn_cast<CXXFunctionalCastExpr>(E)) {
305  const Expr *E = FC->getSubExpr();
306  if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
307  E = TE->getSubExpr();
308  if (isa<CXXTemporaryObjectExpr>(E))
309  return;
310  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
311  if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
312  if (!RD->getAttr<WarnUnusedAttr>())
313  return;
314  }
315  // Diagnose "(void*) blah" as a typo for "(void) blah".
316  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
317  TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
318  QualType T = TI->getType();
319 
320  // We really do want to use the non-canonical type here.
321  if (T == Context.VoidPtrTy) {
323 
324  Diag(Loc, diag::warn_unused_voidptr)
326  return;
327  }
328  }
329 
330  if (E->isGLValue() && E->getType().isVolatileQualified()) {
331  Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
332  return;
333  }
334 
335  DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
336 }
337 
338 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
339  PushCompoundScope(IsStmtExpr);
340 }
341 
343  PopCompoundScope();
344 }
345 
347  return getCurFunction()->CompoundScopes.back();
348 }
349 
351  ArrayRef<Stmt *> Elts, bool isStmtExpr) {
352  const unsigned NumElts = Elts.size();
353 
354  // If we're in C89 mode, check that we don't have any decls after stmts. If
355  // so, emit an extension diagnostic.
356  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
357  // Note that __extension__ can be around a decl.
358  unsigned i = 0;
359  // Skip over all declarations.
360  for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
361  /*empty*/;
362 
363  // We found the end of the list or a statement. Scan for another declstmt.
364  for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
365  /*empty*/;
366 
367  if (i != NumElts) {
368  Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
369  Diag(D->getLocation(), diag::ext_mixed_decls_code);
370  }
371  }
372 
373  // Check for suspicious empty body (null statement) in `for' and `while'
374  // statements. Don't do anything for template instantiations, this just adds
375  // noise.
376  if (NumElts != 0 && !CurrentInstantiationScope &&
377  getCurCompoundScope().HasEmptyLoopBodies) {
378  for (unsigned i = 0; i != NumElts - 1; ++i)
379  DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
380  }
381 
382  return CompoundStmt::Create(Context, Elts, L, R);
383 }
384 
387  if (!Val.get())
388  return Val;
389 
390  if (DiagnoseUnexpandedParameterPack(Val.get()))
391  return ExprError();
392 
393  // If we're not inside a switch, let the 'case' statement handling diagnose
394  // this. Just clean up after the expression as best we can.
395  if (!getCurFunction()->SwitchStack.empty()) {
396  Expr *CondExpr =
397  getCurFunction()->SwitchStack.back().getPointer()->getCond();
398  if (!CondExpr)
399  return ExprError();
400  QualType CondType = CondExpr->getType();
401 
402  auto CheckAndFinish = [&](Expr *E) {
403  if (CondType->isDependentType() || E->isTypeDependent())
404  return ExprResult(E);
405 
406  if (getLangOpts().CPlusPlus11) {
407  // C++11 [stmt.switch]p2: the constant-expression shall be a converted
408  // constant expression of the promoted type of the switch condition.
409  llvm::APSInt TempVal;
410  return CheckConvertedConstantExpression(E, CondType, TempVal,
411  CCEK_CaseValue);
412  }
413 
414  ExprResult ER = E;
415  if (!E->isValueDependent())
416  ER = VerifyIntegerConstantExpression(E);
417  if (!ER.isInvalid())
418  ER = DefaultLvalueConversion(ER.get());
419  if (!ER.isInvalid())
420  ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
421  return ER;
422  };
423 
424  ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
425  if (Converted.get() == Val.get())
426  Converted = CheckAndFinish(Val.get());
427  if (Converted.isInvalid())
428  return ExprError();
429  Val = Converted;
430  }
431 
432  return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
433  getLangOpts().CPlusPlus11);
434 }
435 
438  SourceLocation DotDotDotLoc, ExprResult RHSVal,
440  assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
441  assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
442  : RHSVal.isInvalid() || RHSVal.get()) &&
443  "missing RHS value");
444 
445  if (getCurFunction()->SwitchStack.empty()) {
446  Diag(CaseLoc, diag::err_case_not_in_switch);
447  return StmtError();
448  }
449 
450  if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
451  getCurFunction()->SwitchStack.back().setInt(true);
452  return StmtError();
453  }
454 
455  auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
456  CaseLoc, DotDotDotLoc, ColonLoc);
457  getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
458  return CS;
459 }
460 
461 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
462 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
463  cast<CaseStmt>(S)->setSubStmt(SubStmt);
464 }
465 
468  Stmt *SubStmt, Scope *CurScope) {
469  if (getCurFunction()->SwitchStack.empty()) {
470  Diag(DefaultLoc, diag::err_default_not_in_switch);
471  return SubStmt;
472  }
473 
474  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
475  getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
476  return DS;
477 }
478 
481  SourceLocation ColonLoc, Stmt *SubStmt) {
482  // If the label was multiply defined, reject it now.
483  if (TheDecl->getStmt()) {
484  Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
485  Diag(TheDecl->getLocation(), diag::note_previous_definition);
486  return SubStmt;
487  }
488 
489  // Otherwise, things are good. Fill in the declaration and return it.
490  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
491  TheDecl->setStmt(LS);
492  if (!TheDecl->isGnuLocal()) {
493  TheDecl->setLocStart(IdentLoc);
494  if (!TheDecl->isMSAsmLabel()) {
495  // Don't update the location of MS ASM labels. These will result in
496  // a diagnostic, and changing the location here will mess that up.
497  TheDecl->setLocation(IdentLoc);
498  }
499  }
500  return LS;
501 }
502 
504  ArrayRef<const Attr*> Attrs,
505  Stmt *SubStmt) {
506  // Fill in the declaration and return it.
507  AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
508  return LS;
509 }
510 
511 namespace {
512 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
513  typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
514  Sema &SemaRef;
515 public:
516  CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
517  void VisitBinaryOperator(BinaryOperator *E) {
518  if (E->getOpcode() == BO_Comma)
519  SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
521  }
522 };
523 }
524 
526 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
527  ConditionResult Cond,
528  Stmt *thenStmt, SourceLocation ElseLoc,
529  Stmt *elseStmt) {
530  if (Cond.isInvalid())
531  Cond = ConditionResult(
532  *this, nullptr,
533  MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
534  Context.BoolTy, VK_RValue),
535  IfLoc),
536  false);
537 
538  Expr *CondExpr = Cond.get().second;
539  // Only call the CommaVisitor when not C89 due to differences in scope flags.
540  if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
541  !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
542  CommaVisitor(*this).Visit(CondExpr);
543 
544  if (!elseStmt)
545  DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
546  diag::warn_empty_if_body);
547 
548  return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
549  elseStmt);
550 }
551 
553  Stmt *InitStmt, ConditionResult Cond,
554  Stmt *thenStmt, SourceLocation ElseLoc,
555  Stmt *elseStmt) {
556  if (Cond.isInvalid())
557  return StmtError();
558 
559  if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
560  setFunctionHasBranchProtectedScope();
561 
562  return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
563  Cond.get().second, thenStmt, ElseLoc, elseStmt);
564 }
565 
566 namespace {
567  struct CaseCompareFunctor {
568  bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
569  const llvm::APSInt &RHS) {
570  return LHS.first < RHS;
571  }
572  bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
573  const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
574  return LHS.first < RHS.first;
575  }
576  bool operator()(const llvm::APSInt &LHS,
577  const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
578  return LHS < RHS.first;
579  }
580  };
581 }
582 
583 /// CmpCaseVals - Comparison predicate for sorting case values.
584 ///
585 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
586  const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
587  if (lhs.first < rhs.first)
588  return true;
589 
590  if (lhs.first == rhs.first &&
591  lhs.second->getCaseLoc().getRawEncoding()
592  < rhs.second->getCaseLoc().getRawEncoding())
593  return true;
594  return false;
595 }
596 
597 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
598 ///
599 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
600  const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
601 {
602  return lhs.first < rhs.first;
603 }
604 
605 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
606 ///
607 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
608  const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
609 {
610  return lhs.first == rhs.first;
611 }
612 
613 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
614 /// potentially integral-promoted expression @p expr.
616  if (const auto *FE = dyn_cast<FullExpr>(E))
617  E = FE->getSubExpr();
618  while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
619  if (ImpCast->getCastKind() != CK_IntegralCast) break;
620  E = ImpCast->getSubExpr();
621  }
622  return E->getType();
623 }
624 
626  class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
627  Expr *Cond;
628 
629  public:
630  SwitchConvertDiagnoser(Expr *Cond)
631  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
632  Cond(Cond) {}
633 
634  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
635  QualType T) override {
636  return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
637  }
638 
639  SemaDiagnosticBuilder diagnoseIncomplete(
640  Sema &S, SourceLocation Loc, QualType T) override {
641  return S.Diag(Loc, diag::err_switch_incomplete_class_type)
642  << T << Cond->getSourceRange();
643  }
644 
645  SemaDiagnosticBuilder diagnoseExplicitConv(
646  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
647  return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
648  }
649 
650  SemaDiagnosticBuilder noteExplicitConv(
651  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
652  return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
653  << ConvTy->isEnumeralType() << ConvTy;
654  }
655 
656  SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
657  QualType T) override {
658  return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
659  }
660 
661  SemaDiagnosticBuilder noteAmbiguous(
662  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
663  return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
664  << ConvTy->isEnumeralType() << ConvTy;
665  }
666 
667  SemaDiagnosticBuilder diagnoseConversion(
668  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
669  llvm_unreachable("conversion functions are permitted");
670  }
671  } SwitchDiagnoser(Cond);
672 
673  ExprResult CondResult =
674  PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
675  if (CondResult.isInvalid())
676  return ExprError();
677 
678  // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
679  // failed and produced a diagnostic.
680  Cond = CondResult.get();
681  if (!Cond->isTypeDependent() &&
683  return ExprError();
684 
685  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
686  return UsualUnaryConversions(Cond);
687 }
688 
690  Stmt *InitStmt, ConditionResult Cond) {
691  Expr *CondExpr = Cond.get().second;
692  assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
693 
694  if (CondExpr && !CondExpr->isTypeDependent()) {
695  // We have already converted the expression to an integral or enumeration
696  // type, when we parsed the switch condition. If we don't have an
697  // appropriate type now, enter the switch scope but remember that it's
698  // invalid.
699  assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
700  "invalid condition type");
701  if (CondExpr->isKnownToHaveBooleanValue()) {
702  // switch(bool_expr) {...} is often a programmer error, e.g.
703  // switch(n && mask) { ... } // Doh - should be "n & mask".
704  // One can always use an if statement instead of switch(bool_expr).
705  Diag(SwitchLoc, diag::warn_bool_switch_condition)
706  << CondExpr->getSourceRange();
707  }
708  }
709 
710  setFunctionHasBranchIntoScope();
711 
712  auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
713  getCurFunction()->SwitchStack.push_back(
714  FunctionScopeInfo::SwitchInfo(SS, false));
715  return SS;
716 }
717 
718 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
719  Val = Val.extOrTrunc(BitWidth);
720  Val.setIsSigned(IsSigned);
721 }
722 
723 /// Check the specified case value is in range for the given unpromoted switch
724 /// type.
725 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
726  unsigned UnpromotedWidth, bool UnpromotedSign) {
727  // In C++11 onwards, this is checked by the language rules.
728  if (S.getLangOpts().CPlusPlus11)
729  return;
730 
731  // If the case value was signed and negative and the switch expression is
732  // unsigned, don't bother to warn: this is implementation-defined behavior.
733  // FIXME: Introduce a second, default-ignored warning for this case?
734  if (UnpromotedWidth < Val.getBitWidth()) {
735  llvm::APSInt ConvVal(Val);
736  AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
737  AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
738  // FIXME: Use different diagnostics for overflow in conversion to promoted
739  // type versus "switch expression cannot have this value". Use proper
740  // IntRange checking rather than just looking at the unpromoted type here.
741  if (ConvVal != Val)
742  S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
743  << ConvVal.toString(10);
744  }
745 }
746 
748 
749 /// Returns true if we should emit a diagnostic about this case expression not
750 /// being a part of the enum used in the switch controlling expression.
752  const EnumDecl *ED,
753  const Expr *CaseExpr,
754  EnumValsTy::iterator &EI,
755  EnumValsTy::iterator &EIEnd,
756  const llvm::APSInt &Val) {
757  if (!ED->isClosed())
758  return false;
759 
760  if (const DeclRefExpr *DRE =
761  dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
762  if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
763  QualType VarType = VD->getType();
765  if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
766  S.Context.hasSameUnqualifiedType(EnumType, VarType))
767  return false;
768  }
769  }
770 
771  if (ED->hasAttr<FlagEnumAttr>())
772  return !S.IsValueInFlagEnum(ED, Val, false);
773 
774  while (EI != EIEnd && EI->first < Val)
775  EI++;
776 
777  if (EI != EIEnd && EI->first == Val)
778  return false;
779 
780  return true;
781 }
782 
783 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
784  const Expr *Case) {
785  QualType CondType = Cond->getType();
786  QualType CaseType = Case->getType();
787 
788  const EnumType *CondEnumType = CondType->getAs<EnumType>();
789  const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
790  if (!CondEnumType || !CaseEnumType)
791  return;
792 
793  // Ignore anonymous enums.
794  if (!CondEnumType->getDecl()->getIdentifier() &&
795  !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
796  return;
797  if (!CaseEnumType->getDecl()->getIdentifier() &&
798  !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
799  return;
800 
801  if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
802  return;
803 
804  S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
805  << CondType << CaseType << Cond->getSourceRange()
806  << Case->getSourceRange();
807 }
808 
811  Stmt *BodyStmt) {
812  SwitchStmt *SS = cast<SwitchStmt>(Switch);
813  bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
814  assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
815  "switch stack missing push/pop!");
816 
817  getCurFunction()->SwitchStack.pop_back();
818 
819  if (!BodyStmt) return StmtError();
820  SS->setBody(BodyStmt, SwitchLoc);
821 
822  Expr *CondExpr = SS->getCond();
823  if (!CondExpr) return StmtError();
824 
825  QualType CondType = CondExpr->getType();
826 
827  // C++ 6.4.2.p2:
828  // Integral promotions are performed (on the switch condition).
829  //
830  // A case value unrepresentable by the original switch condition
831  // type (before the promotion) doesn't make sense, even when it can
832  // be represented by the promoted type. Therefore we need to find
833  // the pre-promotion type of the switch condition.
834  const Expr *CondExprBeforePromotion = CondExpr;
835  QualType CondTypeBeforePromotion =
836  GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
837 
838  // Get the bitwidth of the switched-on value after promotions. We must
839  // convert the integer case values to this width before comparison.
840  bool HasDependentValue
841  = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
842  unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
843  bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
844 
845  // Get the width and signedness that the condition might actually have, for
846  // warning purposes.
847  // FIXME: Grab an IntRange for the condition rather than using the unpromoted
848  // type.
849  unsigned CondWidthBeforePromotion
850  = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
851  bool CondIsSignedBeforePromotion
852  = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
853 
854  // Accumulate all of the case values in a vector so that we can sort them
855  // and detect duplicates. This vector contains the APInt for the case after
856  // it has been converted to the condition type.
857  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
858  CaseValsTy CaseVals;
859 
860  // Keep track of any GNU case ranges we see. The APSInt is the low value.
861  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
862  CaseRangesTy CaseRanges;
863 
864  DefaultStmt *TheDefaultStmt = nullptr;
865 
866  bool CaseListIsErroneous = false;
867 
868  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
869  SC = SC->getNextSwitchCase()) {
870 
871  if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
872  if (TheDefaultStmt) {
873  Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
874  Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
875 
876  // FIXME: Remove the default statement from the switch block so that
877  // we'll return a valid AST. This requires recursing down the AST and
878  // finding it, not something we are set up to do right now. For now,
879  // just lop the entire switch stmt out of the AST.
880  CaseListIsErroneous = true;
881  }
882  TheDefaultStmt = DS;
883 
884  } else {
885  CaseStmt *CS = cast<CaseStmt>(SC);
886 
887  Expr *Lo = CS->getLHS();
888 
889  if (Lo->isValueDependent()) {
890  HasDependentValue = true;
891  break;
892  }
893 
894  // We already verified that the expression has a constant value;
895  // get that value (prior to conversions).
896  const Expr *LoBeforePromotion = Lo;
897  GetTypeBeforeIntegralPromotion(LoBeforePromotion);
898  llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
899 
900  // Check the unconverted value is within the range of possible values of
901  // the switch expression.
902  checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
903  CondIsSignedBeforePromotion);
904 
905  // FIXME: This duplicates the check performed for warn_not_in_enum below.
906  checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
907  LoBeforePromotion);
908 
909  // Convert the value to the same width/sign as the condition.
910  AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
911 
912  // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
913  if (CS->getRHS()) {
914  if (CS->getRHS()->isValueDependent()) {
915  HasDependentValue = true;
916  break;
917  }
918  CaseRanges.push_back(std::make_pair(LoVal, CS));
919  } else
920  CaseVals.push_back(std::make_pair(LoVal, CS));
921  }
922  }
923 
924  if (!HasDependentValue) {
925  // If we don't have a default statement, check whether the
926  // condition is constant.
927  llvm::APSInt ConstantCondValue;
928  bool HasConstantCond = false;
929  if (!HasDependentValue && !TheDefaultStmt) {
930  Expr::EvalResult Result;
931  HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
933  if (Result.Val.isInt())
934  ConstantCondValue = Result.Val.getInt();
935  assert(!HasConstantCond ||
936  (ConstantCondValue.getBitWidth() == CondWidth &&
937  ConstantCondValue.isSigned() == CondIsSigned));
938  }
939  bool ShouldCheckConstantCond = HasConstantCond;
940 
941  // Sort all the scalar case values so we can easily detect duplicates.
942  llvm::stable_sort(CaseVals, CmpCaseVals);
943 
944  if (!CaseVals.empty()) {
945  for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
946  if (ShouldCheckConstantCond &&
947  CaseVals[i].first == ConstantCondValue)
948  ShouldCheckConstantCond = false;
949 
950  if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
951  // If we have a duplicate, report it.
952  // First, determine if either case value has a name
953  StringRef PrevString, CurrString;
954  Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
955  Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
956  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
957  PrevString = DeclRef->getDecl()->getName();
958  }
959  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
960  CurrString = DeclRef->getDecl()->getName();
961  }
962  SmallString<16> CaseValStr;
963  CaseVals[i-1].first.toString(CaseValStr);
964 
965  if (PrevString == CurrString)
966  Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
967  diag::err_duplicate_case)
968  << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
969  else
970  Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
971  diag::err_duplicate_case_differing_expr)
972  << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
973  << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
974  << CaseValStr;
975 
976  Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
977  diag::note_duplicate_case_prev);
978  // FIXME: We really want to remove the bogus case stmt from the
979  // substmt, but we have no way to do this right now.
980  CaseListIsErroneous = true;
981  }
982  }
983  }
984 
985  // Detect duplicate case ranges, which usually don't exist at all in
986  // the first place.
987  if (!CaseRanges.empty()) {
988  // Sort all the case ranges by their low value so we can easily detect
989  // overlaps between ranges.
990  llvm::stable_sort(CaseRanges);
991 
992  // Scan the ranges, computing the high values and removing empty ranges.
993  std::vector<llvm::APSInt> HiVals;
994  for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
995  llvm::APSInt &LoVal = CaseRanges[i].first;
996  CaseStmt *CR = CaseRanges[i].second;
997  Expr *Hi = CR->getRHS();
998 
999  const Expr *HiBeforePromotion = Hi;
1000  GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1001  llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1002 
1003  // Check the unconverted value is within the range of possible values of
1004  // the switch expression.
1005  checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1006  CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1007 
1008  // Convert the value to the same width/sign as the condition.
1009  AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1010 
1011  // If the low value is bigger than the high value, the case is empty.
1012  if (LoVal > HiVal) {
1013  Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1014  << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1015  CaseRanges.erase(CaseRanges.begin()+i);
1016  --i;
1017  --e;
1018  continue;
1019  }
1020 
1021  if (ShouldCheckConstantCond &&
1022  LoVal <= ConstantCondValue &&
1023  ConstantCondValue <= HiVal)
1024  ShouldCheckConstantCond = false;
1025 
1026  HiVals.push_back(HiVal);
1027  }
1028 
1029  // Rescan the ranges, looking for overlap with singleton values and other
1030  // ranges. Since the range list is sorted, we only need to compare case
1031  // ranges with their neighbors.
1032  for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1033  llvm::APSInt &CRLo = CaseRanges[i].first;
1034  llvm::APSInt &CRHi = HiVals[i];
1035  CaseStmt *CR = CaseRanges[i].second;
1036 
1037  // Check to see whether the case range overlaps with any
1038  // singleton cases.
1039  CaseStmt *OverlapStmt = nullptr;
1040  llvm::APSInt OverlapVal(32);
1041 
1042  // Find the smallest value >= the lower bound. If I is in the
1043  // case range, then we have overlap.
1044  CaseValsTy::iterator I =
1045  llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1046  if (I != CaseVals.end() && I->first < CRHi) {
1047  OverlapVal = I->first; // Found overlap with scalar.
1048  OverlapStmt = I->second;
1049  }
1050 
1051  // Find the smallest value bigger than the upper bound.
1052  I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1053  if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1054  OverlapVal = (I-1)->first; // Found overlap with scalar.
1055  OverlapStmt = (I-1)->second;
1056  }
1057 
1058  // Check to see if this case stmt overlaps with the subsequent
1059  // case range.
1060  if (i && CRLo <= HiVals[i-1]) {
1061  OverlapVal = HiVals[i-1]; // Found overlap with range.
1062  OverlapStmt = CaseRanges[i-1].second;
1063  }
1064 
1065  if (OverlapStmt) {
1066  // If we have a duplicate, report it.
1067  Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1068  << OverlapVal.toString(10);
1069  Diag(OverlapStmt->getLHS()->getBeginLoc(),
1070  diag::note_duplicate_case_prev);
1071  // FIXME: We really want to remove the bogus case stmt from the
1072  // substmt, but we have no way to do this right now.
1073  CaseListIsErroneous = true;
1074  }
1075  }
1076  }
1077 
1078  // Complain if we have a constant condition and we didn't find a match.
1079  if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1080  ShouldCheckConstantCond) {
1081  // TODO: it would be nice if we printed enums as enums, chars as
1082  // chars, etc.
1083  Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1084  << ConstantCondValue.toString(10)
1085  << CondExpr->getSourceRange();
1086  }
1087 
1088  // Check to see if switch is over an Enum and handles all of its
1089  // values. We only issue a warning if there is not 'default:', but
1090  // we still do the analysis to preserve this information in the AST
1091  // (which can be used by flow-based analyes).
1092  //
1093  const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1094 
1095  // If switch has default case, then ignore it.
1096  if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1097  ET && ET->getDecl()->isCompleteDefinition()) {
1098  const EnumDecl *ED = ET->getDecl();
1099  EnumValsTy EnumVals;
1100 
1101  // Gather all enum values, set their type and sort them,
1102  // allowing easier comparison with CaseVals.
1103  for (auto *EDI : ED->enumerators()) {
1104  llvm::APSInt Val = EDI->getInitVal();
1105  AdjustAPSInt(Val, CondWidth, CondIsSigned);
1106  EnumVals.push_back(std::make_pair(Val, EDI));
1107  }
1108  llvm::stable_sort(EnumVals, CmpEnumVals);
1109  auto EI = EnumVals.begin(), EIEnd =
1110  std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1111 
1112  // See which case values aren't in enum.
1113  for (CaseValsTy::const_iterator CI = CaseVals.begin();
1114  CI != CaseVals.end(); CI++) {
1115  Expr *CaseExpr = CI->second->getLHS();
1116  if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1117  CI->first))
1118  Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1119  << CondTypeBeforePromotion;
1120  }
1121 
1122  // See which of case ranges aren't in enum
1123  EI = EnumVals.begin();
1124  for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1125  RI != CaseRanges.end(); RI++) {
1126  Expr *CaseExpr = RI->second->getLHS();
1127  if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1128  RI->first))
1129  Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1130  << CondTypeBeforePromotion;
1131 
1132  llvm::APSInt Hi =
1133  RI->second->getRHS()->EvaluateKnownConstInt(Context);
1134  AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1135 
1136  CaseExpr = RI->second->getRHS();
1137  if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1138  Hi))
1139  Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1140  << CondTypeBeforePromotion;
1141  }
1142 
1143  // Check which enum vals aren't in switch
1144  auto CI = CaseVals.begin();
1145  auto RI = CaseRanges.begin();
1146  bool hasCasesNotInSwitch = false;
1147 
1148  SmallVector<DeclarationName,8> UnhandledNames;
1149 
1150  for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1151  // Don't warn about omitted unavailable EnumConstantDecls.
1152  switch (EI->second->getAvailability()) {
1153  case AR_Deprecated:
1154  // Omitting a deprecated constant is ok; it should never materialize.
1155  case AR_Unavailable:
1156  continue;
1157 
1158  case AR_NotYetIntroduced:
1159  // Partially available enum constants should be present. Note that we
1160  // suppress -Wunguarded-availability diagnostics for such uses.
1161  case AR_Available:
1162  break;
1163  }
1164 
1165  if (EI->second->hasAttr<UnusedAttr>())
1166  continue;
1167 
1168  // Drop unneeded case values
1169  while (CI != CaseVals.end() && CI->first < EI->first)
1170  CI++;
1171 
1172  if (CI != CaseVals.end() && CI->first == EI->first)
1173  continue;
1174 
1175  // Drop unneeded case ranges
1176  for (; RI != CaseRanges.end(); RI++) {
1177  llvm::APSInt Hi =
1178  RI->second->getRHS()->EvaluateKnownConstInt(Context);
1179  AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1180  if (EI->first <= Hi)
1181  break;
1182  }
1183 
1184  if (RI == CaseRanges.end() || EI->first < RI->first) {
1185  hasCasesNotInSwitch = true;
1186  UnhandledNames.push_back(EI->second->getDeclName());
1187  }
1188  }
1189 
1190  if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1191  Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1192 
1193  // Produce a nice diagnostic if multiple values aren't handled.
1194  if (!UnhandledNames.empty()) {
1195  DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1196  TheDefaultStmt ? diag::warn_def_missing_case
1197  : diag::warn_missing_case)
1198  << (int)UnhandledNames.size();
1199 
1200  for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1201  I != E; ++I)
1202  DB << UnhandledNames[I];
1203  }
1204 
1205  if (!hasCasesNotInSwitch)
1206  SS->setAllEnumCasesCovered();
1207  }
1208  }
1209 
1210  if (BodyStmt)
1211  DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1212  diag::warn_empty_switch_body);
1213 
1214  // FIXME: If the case list was broken is some way, we don't have a good system
1215  // to patch it up. Instead, just return the whole substmt as broken.
1216  if (CaseListIsErroneous)
1217  return StmtError();
1218 
1219  return SS;
1220 }
1221 
1222 void
1224  Expr *SrcExpr) {
1225  if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1226  return;
1227 
1228  if (const EnumType *ET = DstType->getAs<EnumType>())
1229  if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1230  SrcType->isIntegerType()) {
1231  if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1232  SrcExpr->isIntegerConstantExpr(Context)) {
1233  // Get the bitwidth of the enum value before promotions.
1234  unsigned DstWidth = Context.getIntWidth(DstType);
1235  bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1236 
1237  llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1238  AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1239  const EnumDecl *ED = ET->getDecl();
1240 
1241  if (!ED->isClosed())
1242  return;
1243 
1244  if (ED->hasAttr<FlagEnumAttr>()) {
1245  if (!IsValueInFlagEnum(ED, RhsVal, true))
1246  Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1247  << DstType.getUnqualifiedType();
1248  } else {
1250  EnumValsTy;
1251  EnumValsTy EnumVals;
1252 
1253  // Gather all enum values, set their type and sort them,
1254  // allowing easier comparison with rhs constant.
1255  for (auto *EDI : ED->enumerators()) {
1256  llvm::APSInt Val = EDI->getInitVal();
1257  AdjustAPSInt(Val, DstWidth, DstIsSigned);
1258  EnumVals.push_back(std::make_pair(Val, EDI));
1259  }
1260  if (EnumVals.empty())
1261  return;
1262  llvm::stable_sort(EnumVals, CmpEnumVals);
1263  EnumValsTy::iterator EIend =
1264  std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1265 
1266  // See which values aren't in the enum.
1267  EnumValsTy::const_iterator EI = EnumVals.begin();
1268  while (EI != EIend && EI->first < RhsVal)
1269  EI++;
1270  if (EI == EIend || EI->first != RhsVal) {
1271  Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1272  << DstType.getUnqualifiedType();
1273  }
1274  }
1275  }
1276  }
1277 }
1278 
1280  Stmt *Body) {
1281  if (Cond.isInvalid())
1282  return StmtError();
1283 
1284  auto CondVal = Cond.get();
1285  CheckBreakContinueBinding(CondVal.second);
1286 
1287  if (CondVal.second &&
1288  !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1289  CommaVisitor(*this).Visit(CondVal.second);
1290 
1291  if (isa<NullStmt>(Body))
1292  getCurCompoundScope().setHasEmptyLoopBodies();
1293 
1294  return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1295  WhileLoc);
1296 }
1297 
1298 StmtResult
1300  SourceLocation WhileLoc, SourceLocation CondLParen,
1301  Expr *Cond, SourceLocation CondRParen) {
1302  assert(Cond && "ActOnDoStmt(): missing expression");
1303 
1304  CheckBreakContinueBinding(Cond);
1305  ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1306  if (CondResult.isInvalid())
1307  return StmtError();
1308  Cond = CondResult.get();
1309 
1310  CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1311  if (CondResult.isInvalid())
1312  return StmtError();
1313  Cond = CondResult.get();
1314 
1315  // Only call the CommaVisitor for C89 due to differences in scope flags.
1316  if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1317  !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1318  CommaVisitor(*this).Visit(Cond);
1319 
1320  return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1321 }
1322 
1323 namespace {
1324  // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1325  using DeclSetVector =
1326  llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1327  llvm::SmallPtrSet<VarDecl *, 8>>;
1328 
1329  // This visitor will traverse a conditional statement and store all
1330  // the evaluated decls into a vector. Simple is set to true if none
1331  // of the excluded constructs are used.
1332  class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1333  DeclSetVector &Decls;
1335  bool Simple;
1336  public:
1337  typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1338 
1339  DeclExtractor(Sema &S, DeclSetVector &Decls,
1340  SmallVectorImpl<SourceRange> &Ranges) :
1341  Inherited(S.Context),
1342  Decls(Decls),
1343  Ranges(Ranges),
1344  Simple(true) {}
1345 
1346  bool isSimple() { return Simple; }
1347 
1348  // Replaces the method in EvaluatedExprVisitor.
1349  void VisitMemberExpr(MemberExpr* E) {
1350  Simple = false;
1351  }
1352 
1353  // Any Stmt not whitelisted will cause the condition to be marked complex.
1354  void VisitStmt(Stmt *S) {
1355  Simple = false;
1356  }
1357 
1358  void VisitBinaryOperator(BinaryOperator *E) {
1359  Visit(E->getLHS());
1360  Visit(E->getRHS());
1361  }
1362 
1363  void VisitCastExpr(CastExpr *E) {
1364  Visit(E->getSubExpr());
1365  }
1366 
1367  void VisitUnaryOperator(UnaryOperator *E) {
1368  // Skip checking conditionals with derefernces.
1369  if (E->getOpcode() == UO_Deref)
1370  Simple = false;
1371  else
1372  Visit(E->getSubExpr());
1373  }
1374 
1375  void VisitConditionalOperator(ConditionalOperator *E) {
1376  Visit(E->getCond());
1377  Visit(E->getTrueExpr());
1378  Visit(E->getFalseExpr());
1379  }
1380 
1381  void VisitParenExpr(ParenExpr *E) {
1382  Visit(E->getSubExpr());
1383  }
1384 
1385  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1386  Visit(E->getOpaqueValue()->getSourceExpr());
1387  Visit(E->getFalseExpr());
1388  }
1389 
1390  void VisitIntegerLiteral(IntegerLiteral *E) { }
1391  void VisitFloatingLiteral(FloatingLiteral *E) { }
1392  void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1393  void VisitCharacterLiteral(CharacterLiteral *E) { }
1394  void VisitGNUNullExpr(GNUNullExpr *E) { }
1395  void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1396 
1397  void VisitDeclRefExpr(DeclRefExpr *E) {
1398  VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1399  if (!VD) {
1400  // Don't allow unhandled Decl types.
1401  Simple = false;
1402  return;
1403  }
1404 
1405  Ranges.push_back(E->getSourceRange());
1406 
1407  Decls.insert(VD);
1408  }
1409 
1410  }; // end class DeclExtractor
1411 
1412  // DeclMatcher checks to see if the decls are used in a non-evaluated
1413  // context.
1414  class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1415  DeclSetVector &Decls;
1416  bool FoundDecl;
1417 
1418  public:
1419  typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1420 
1421  DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1422  Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1423  if (!Statement) return;
1424 
1425  Visit(Statement);
1426  }
1427 
1428  void VisitReturnStmt(ReturnStmt *S) {
1429  FoundDecl = true;
1430  }
1431 
1432  void VisitBreakStmt(BreakStmt *S) {
1433  FoundDecl = true;
1434  }
1435 
1436  void VisitGotoStmt(GotoStmt *S) {
1437  FoundDecl = true;
1438  }
1439 
1440  void VisitCastExpr(CastExpr *E) {
1441  if (E->getCastKind() == CK_LValueToRValue)
1442  CheckLValueToRValueCast(E->getSubExpr());
1443  else
1444  Visit(E->getSubExpr());
1445  }
1446 
1447  void CheckLValueToRValueCast(Expr *E) {
1448  E = E->IgnoreParenImpCasts();
1449 
1450  if (isa<DeclRefExpr>(E)) {
1451  return;
1452  }
1453 
1454  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1455  Visit(CO->getCond());
1456  CheckLValueToRValueCast(CO->getTrueExpr());
1457  CheckLValueToRValueCast(CO->getFalseExpr());
1458  return;
1459  }
1460 
1461  if (BinaryConditionalOperator *BCO =
1462  dyn_cast<BinaryConditionalOperator>(E)) {
1463  CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1464  CheckLValueToRValueCast(BCO->getFalseExpr());
1465  return;
1466  }
1467 
1468  Visit(E);
1469  }
1470 
1471  void VisitDeclRefExpr(DeclRefExpr *E) {
1472  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1473  if (Decls.count(VD))
1474  FoundDecl = true;
1475  }
1476 
1477  void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1478  // Only need to visit the semantics for POE.
1479  // SyntaticForm doesn't really use the Decal.
1480  for (auto *S : POE->semantics()) {
1481  if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1482  // Look past the OVE into the expression it binds.
1483  Visit(OVE->getSourceExpr());
1484  else
1485  Visit(S);
1486  }
1487  }
1488 
1489  bool FoundDeclInUse() { return FoundDecl; }
1490 
1491  }; // end class DeclMatcher
1492 
1493  void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1494  Expr *Third, Stmt *Body) {
1495  // Condition is empty
1496  if (!Second) return;
1497 
1498  if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1499  Second->getBeginLoc()))
1500  return;
1501 
1502  PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1503  DeclSetVector Decls;
1505  DeclExtractor DE(S, Decls, Ranges);
1506  DE.Visit(Second);
1507 
1508  // Don't analyze complex conditionals.
1509  if (!DE.isSimple()) return;
1510 
1511  // No decls found.
1512  if (Decls.size() == 0) return;
1513 
1514  // Don't warn on volatile, static, or global variables.
1515  for (auto *VD : Decls)
1516  if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1517  return;
1518 
1519  if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1520  DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1521  DeclMatcher(S, Decls, Body).FoundDeclInUse())
1522  return;
1523 
1524  // Load decl names into diagnostic.
1525  if (Decls.size() > 4) {
1526  PDiag << 0;
1527  } else {
1528  PDiag << (unsigned)Decls.size();
1529  for (auto *VD : Decls)
1530  PDiag << VD->getDeclName();
1531  }
1532 
1533  for (auto Range : Ranges)
1534  PDiag << Range;
1535 
1536  S.Diag(Ranges.begin()->getBegin(), PDiag);
1537  }
1538 
1539  // If Statement is an incemement or decrement, return true and sets the
1540  // variables Increment and DRE.
1541  bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1542  DeclRefExpr *&DRE) {
1543  if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1544  if (!Cleanups->cleanupsHaveSideEffects())
1545  Statement = Cleanups->getSubExpr();
1546 
1547  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1548  switch (UO->getOpcode()) {
1549  default: return false;
1550  case UO_PostInc:
1551  case UO_PreInc:
1552  Increment = true;
1553  break;
1554  case UO_PostDec:
1555  case UO_PreDec:
1556  Increment = false;
1557  break;
1558  }
1559  DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1560  return DRE;
1561  }
1562 
1563  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1564  FunctionDecl *FD = Call->getDirectCallee();
1565  if (!FD || !FD->isOverloadedOperator()) return false;
1566  switch (FD->getOverloadedOperator()) {
1567  default: return false;
1568  case OO_PlusPlus:
1569  Increment = true;
1570  break;
1571  case OO_MinusMinus:
1572  Increment = false;
1573  break;
1574  }
1575  DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1576  return DRE;
1577  }
1578 
1579  return false;
1580  }
1581 
1582  // A visitor to determine if a continue or break statement is a
1583  // subexpression.
1584  class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1585  SourceLocation BreakLoc;
1586  SourceLocation ContinueLoc;
1587  bool InSwitch = false;
1588 
1589  public:
1590  BreakContinueFinder(Sema &S, const Stmt* Body) :
1591  Inherited(S.Context) {
1592  Visit(Body);
1593  }
1594 
1596 
1597  void VisitContinueStmt(const ContinueStmt* E) {
1598  ContinueLoc = E->getContinueLoc();
1599  }
1600 
1601  void VisitBreakStmt(const BreakStmt* E) {
1602  if (!InSwitch)
1603  BreakLoc = E->getBreakLoc();
1604  }
1605 
1606  void VisitSwitchStmt(const SwitchStmt* S) {
1607  if (const Stmt *Init = S->getInit())
1608  Visit(Init);
1609  if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1610  Visit(CondVar);
1611  if (const Stmt *Cond = S->getCond())
1612  Visit(Cond);
1613 
1614  // Don't return break statements from the body of a switch.
1615  InSwitch = true;
1616  if (const Stmt *Body = S->getBody())
1617  Visit(Body);
1618  InSwitch = false;
1619  }
1620 
1621  void VisitForStmt(const ForStmt *S) {
1622  // Only visit the init statement of a for loop; the body
1623  // has a different break/continue scope.
1624  if (const Stmt *Init = S->getInit())
1625  Visit(Init);
1626  }
1627 
1628  void VisitWhileStmt(const WhileStmt *) {
1629  // Do nothing; the children of a while loop have a different
1630  // break/continue scope.
1631  }
1632 
1633  void VisitDoStmt(const DoStmt *) {
1634  // Do nothing; the children of a while loop have a different
1635  // break/continue scope.
1636  }
1637 
1638  void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1639  // Only visit the initialization of a for loop; the body
1640  // has a different break/continue scope.
1641  if (const Stmt *Init = S->getInit())
1642  Visit(Init);
1643  if (const Stmt *Range = S->getRangeStmt())
1644  Visit(Range);
1645  if (const Stmt *Begin = S->getBeginStmt())
1646  Visit(Begin);
1647  if (const Stmt *End = S->getEndStmt())
1648  Visit(End);
1649  }
1650 
1651  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1652  // Only visit the initialization of a for loop; the body
1653  // has a different break/continue scope.
1654  if (const Stmt *Element = S->getElement())
1655  Visit(Element);
1656  if (const Stmt *Collection = S->getCollection())
1657  Visit(Collection);
1658  }
1659 
1660  bool ContinueFound() { return ContinueLoc.isValid(); }
1661  bool BreakFound() { return BreakLoc.isValid(); }
1662  SourceLocation GetContinueLoc() { return ContinueLoc; }
1663  SourceLocation GetBreakLoc() { return BreakLoc; }
1664 
1665  }; // end class BreakContinueFinder
1666 
1667  // Emit a warning when a loop increment/decrement appears twice per loop
1668  // iteration. The conditions which trigger this warning are:
1669  // 1) The last statement in the loop body and the third expression in the
1670  // for loop are both increment or both decrement of the same variable
1671  // 2) No continue statements in the loop body.
1672  void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1673  // Return when there is nothing to check.
1674  if (!Body || !Third) return;
1675 
1676  if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1677  Third->getBeginLoc()))
1678  return;
1679 
1680  // Get the last statement from the loop body.
1681  CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1682  if (!CS || CS->body_empty()) return;
1683  Stmt *LastStmt = CS->body_back();
1684  if (!LastStmt) return;
1685 
1686  bool LoopIncrement, LastIncrement;
1687  DeclRefExpr *LoopDRE, *LastDRE;
1688 
1689  if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1690  if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1691 
1692  // Check that the two statements are both increments or both decrements
1693  // on the same variable.
1694  if (LoopIncrement != LastIncrement ||
1695  LoopDRE->getDecl() != LastDRE->getDecl()) return;
1696 
1697  if (BreakContinueFinder(S, Body).ContinueFound()) return;
1698 
1699  S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1700  << LastDRE->getDecl() << LastIncrement;
1701  S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1702  << LoopIncrement;
1703  }
1704 
1705 } // end namespace
1706 
1707 
1708 void Sema::CheckBreakContinueBinding(Expr *E) {
1709  if (!E || getLangOpts().CPlusPlus)
1710  return;
1711  BreakContinueFinder BCFinder(*this, E);
1712  Scope *BreakParent = CurScope->getBreakParent();
1713  if (BCFinder.BreakFound() && BreakParent) {
1714  if (BreakParent->getFlags() & Scope::SwitchScope) {
1715  Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1716  } else {
1717  Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1718  << "break";
1719  }
1720  } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1721  Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1722  << "continue";
1723  }
1724 }
1725 
1727  Stmt *First, ConditionResult Second,
1728  FullExprArg third, SourceLocation RParenLoc,
1729  Stmt *Body) {
1730  if (Second.isInvalid())
1731  return StmtError();
1732 
1733  if (!getLangOpts().CPlusPlus) {
1734  if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1735  // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1736  // declare identifiers for objects having storage class 'auto' or
1737  // 'register'.
1738  for (auto *DI : DS->decls()) {
1739  VarDecl *VD = dyn_cast<VarDecl>(DI);
1740  if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1741  VD = nullptr;
1742  if (!VD) {
1743  Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1744  DI->setInvalidDecl();
1745  }
1746  }
1747  }
1748  }
1749 
1750  CheckBreakContinueBinding(Second.get().second);
1751  CheckBreakContinueBinding(third.get());
1752 
1753  if (!Second.get().first)
1754  CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1755  Body);
1756  CheckForRedundantIteration(*this, third.get(), Body);
1757 
1758  if (Second.get().second &&
1759  !Diags.isIgnored(diag::warn_comma_operator,
1760  Second.get().second->getExprLoc()))
1761  CommaVisitor(*this).Visit(Second.get().second);
1762 
1763  Expr *Third = third.release().getAs<Expr>();
1764  if (isa<NullStmt>(Body))
1765  getCurCompoundScope().setHasEmptyLoopBodies();
1766 
1767  return new (Context)
1768  ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1769  Body, ForLoc, LParenLoc, RParenLoc);
1770 }
1771 
1772 /// In an Objective C collection iteration statement:
1773 /// for (x in y)
1774 /// x can be an arbitrary l-value expression. Bind it up as a
1775 /// full-expression.
1777  // Reduce placeholder expressions here. Note that this rejects the
1778  // use of pseudo-object l-values in this position.
1779  ExprResult result = CheckPlaceholderExpr(E);
1780  if (result.isInvalid()) return StmtError();
1781  E = result.get();
1782 
1783  ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
1784  if (FullExpr.isInvalid())
1785  return StmtError();
1786  return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1787 }
1788 
1789 ExprResult
1791  if (!collection)
1792  return ExprError();
1793 
1794  ExprResult result = CorrectDelayedTyposInExpr(collection);
1795  if (!result.isUsable())
1796  return ExprError();
1797  collection = result.get();
1798 
1799  // Bail out early if we've got a type-dependent expression.
1800  if (collection->isTypeDependent()) return collection;
1801 
1802  // Perform normal l-value conversion.
1803  result = DefaultFunctionArrayLvalueConversion(collection);
1804  if (result.isInvalid())
1805  return ExprError();
1806  collection = result.get();
1807 
1808  // The operand needs to have object-pointer type.
1809  // TODO: should we do a contextual conversion?
1811  collection->getType()->getAs<ObjCObjectPointerType>();
1812  if (!pointerType)
1813  return Diag(forLoc, diag::err_collection_expr_type)
1814  << collection->getType() << collection->getSourceRange();
1815 
1816  // Check that the operand provides
1817  // - countByEnumeratingWithState:objects:count:
1818  const ObjCObjectType *objectType = pointerType->getObjectType();
1819  ObjCInterfaceDecl *iface = objectType->getInterface();
1820 
1821  // If we have a forward-declared type, we can't do this check.
1822  // Under ARC, it is an error not to have a forward-declared class.
1823  if (iface &&
1824  (getLangOpts().ObjCAutoRefCount
1825  ? RequireCompleteType(forLoc, QualType(objectType, 0),
1826  diag::err_arc_collection_forward, collection)
1827  : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1828  // Otherwise, if we have any useful type information, check that
1829  // the type declares the appropriate method.
1830  } else if (iface || !objectType->qual_empty()) {
1831  IdentifierInfo *selectorIdents[] = {
1832  &Context.Idents.get("countByEnumeratingWithState"),
1833  &Context.Idents.get("objects"),
1834  &Context.Idents.get("count")
1835  };
1836  Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1837 
1838  ObjCMethodDecl *method = nullptr;
1839 
1840  // If there's an interface, look in both the public and private APIs.
1841  if (iface) {
1842  method = iface->lookupInstanceMethod(selector);
1843  if (!method) method = iface->lookupPrivateMethod(selector);
1844  }
1845 
1846  // Also check protocol qualifiers.
1847  if (!method)
1848  method = LookupMethodInQualifiedType(selector, pointerType,
1849  /*instance*/ true);
1850 
1851  // If we didn't find it anywhere, give up.
1852  if (!method) {
1853  Diag(forLoc, diag::warn_collection_expr_type)
1854  << collection->getType() << selector << collection->getSourceRange();
1855  }
1856 
1857  // TODO: check for an incompatible signature?
1858  }
1859 
1860  // Wrap up any cleanups in the expression.
1861  return collection;
1862 }
1863 
1864 StmtResult
1866  Stmt *First, Expr *collection,
1867  SourceLocation RParenLoc) {
1868  setFunctionHasBranchProtectedScope();
1869 
1870  ExprResult CollectionExprResult =
1871  CheckObjCForCollectionOperand(ForLoc, collection);
1872 
1873  if (First) {
1874  QualType FirstType;
1875  if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1876  if (!DS->isSingleDecl())
1877  return StmtError(Diag((*DS->decl_begin())->getLocation(),
1878  diag::err_toomany_element_decls));
1879 
1880  VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1881  if (!D || D->isInvalidDecl())
1882  return StmtError();
1883 
1884  FirstType = D->getType();
1885  // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1886  // declare identifiers for objects having storage class 'auto' or
1887  // 'register'.
1888  if (!D->hasLocalStorage())
1889  return StmtError(Diag(D->getLocation(),
1890  diag::err_non_local_variable_decl_in_for));
1891 
1892  // If the type contained 'auto', deduce the 'auto' to 'id'.
1893  if (FirstType->getContainedAutoType()) {
1894  OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1895  VK_RValue);
1896  Expr *DeducedInit = &OpaqueId;
1897  if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1898  DAR_Failed)
1899  DiagnoseAutoDeductionFailure(D, DeducedInit);
1900  if (FirstType.isNull()) {
1901  D->setInvalidDecl();
1902  return StmtError();
1903  }
1904 
1905  D->setType(FirstType);
1906 
1907  if (!inTemplateInstantiation()) {
1908  SourceLocation Loc =
1910  Diag(Loc, diag::warn_auto_var_is_id)
1911  << D->getDeclName();
1912  }
1913  }
1914 
1915  } else {
1916  Expr *FirstE = cast<Expr>(First);
1917  if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1918  return StmtError(
1919  Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1920  << First->getSourceRange());
1921 
1922  FirstType = static_cast<Expr*>(First)->getType();
1923  if (FirstType.isConstQualified())
1924  Diag(ForLoc, diag::err_selector_element_const_type)
1925  << FirstType << First->getSourceRange();
1926  }
1927  if (!FirstType->isDependentType() &&
1928  !FirstType->isObjCObjectPointerType() &&
1929  !FirstType->isBlockPointerType())
1930  return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1931  << FirstType << First->getSourceRange());
1932  }
1933 
1934  if (CollectionExprResult.isInvalid())
1935  return StmtError();
1936 
1937  CollectionExprResult =
1938  ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
1939  if (CollectionExprResult.isInvalid())
1940  return StmtError();
1941 
1942  return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1943  nullptr, ForLoc, RParenLoc);
1944 }
1945 
1946 /// Finish building a variable declaration for a for-range statement.
1947 /// \return true if an error occurs.
1948 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1949  SourceLocation Loc, int DiagID) {
1950  if (Decl->getType()->isUndeducedType()) {
1951  ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1952  if (!Res.isUsable()) {
1953  Decl->setInvalidDecl();
1954  return true;
1955  }
1956  Init = Res.get();
1957  }
1958 
1959  // Deduce the type for the iterator variable now rather than leaving it to
1960  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1961  QualType InitType;
1962  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1963  SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1965  SemaRef.Diag(Loc, DiagID) << Init->getType();
1966  if (InitType.isNull()) {
1967  Decl->setInvalidDecl();
1968  return true;
1969  }
1970  Decl->setType(InitType);
1971 
1972  // In ARC, infer lifetime.
1973  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1974  // we're doing the equivalent of fast iteration.
1975  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1976  SemaRef.inferObjCARCLifetime(Decl))
1977  Decl->setInvalidDecl();
1978 
1979  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1980  SemaRef.FinalizeDeclaration(Decl);
1981  SemaRef.CurContext->addHiddenDecl(Decl);
1982  return false;
1983 }
1984 
1985 namespace {
1986 // An enum to represent whether something is dealing with a call to begin()
1987 // or a call to end() in a range-based for loop.
1989  BEF_begin,
1990  BEF_end
1991 };
1992 
1993 /// Produce a note indicating which begin/end function was implicitly called
1994 /// by a C++11 for-range statement. This is often not obvious from the code,
1995 /// nor from the diagnostics produced when analysing the implicit expressions
1996 /// required in a for-range statement.
1997 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1998  BeginEndFunction BEF) {
1999  CallExpr *CE = dyn_cast<CallExpr>(E);
2000  if (!CE)
2001  return;
2002  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2003  if (!D)
2004  return;
2005  SourceLocation Loc = D->getLocation();
2006 
2007  std::string Description;
2008  bool IsTemplate = false;
2009  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2010  Description = SemaRef.getTemplateArgumentBindingsText(
2011  FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2012  IsTemplate = true;
2013  }
2014 
2015  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2016  << BEF << IsTemplate << Description << E->getType();
2017 }
2018 
2019 /// Build a variable declaration for a for-range statement.
2020 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2021  QualType Type, StringRef Name) {
2022  DeclContext *DC = SemaRef.CurContext;
2023  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2024  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2025  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2026  TInfo, SC_None);
2027  Decl->setImplicit();
2028  return Decl;
2029 }
2030 
2031 }
2032 
2033 static bool ObjCEnumerationCollection(Expr *Collection) {
2034  return !Collection->isTypeDependent()
2035  && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2036 }
2037 
2038 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2039 ///
2040 /// C++11 [stmt.ranged]:
2041 /// A range-based for statement is equivalent to
2042 ///
2043 /// {
2044 /// auto && __range = range-init;
2045 /// for ( auto __begin = begin-expr,
2046 /// __end = end-expr;
2047 /// __begin != __end;
2048 /// ++__begin ) {
2049 /// for-range-declaration = *__begin;
2050 /// statement
2051 /// }
2052 /// }
2053 ///
2054 /// The body of the loop is not available yet, since it cannot be analysed until
2055 /// we have determined the type of the for-range-declaration.
2057  SourceLocation CoawaitLoc, Stmt *InitStmt,
2058  Stmt *First, SourceLocation ColonLoc,
2059  Expr *Range, SourceLocation RParenLoc,
2061  if (!First)
2062  return StmtError();
2063 
2064  if (Range && ObjCEnumerationCollection(Range)) {
2065  // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2066  if (InitStmt)
2067  return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2068  << InitStmt->getSourceRange();
2069  return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2070  }
2071 
2072  DeclStmt *DS = dyn_cast<DeclStmt>(First);
2073  assert(DS && "first part of for range not a decl stmt");
2074 
2075  if (!DS->isSingleDecl()) {
2076  Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2077  return StmtError();
2078  }
2079 
2080  Decl *LoopVar = DS->getSingleDecl();
2081  if (LoopVar->isInvalidDecl() || !Range ||
2082  DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2083  LoopVar->setInvalidDecl();
2084  return StmtError();
2085  }
2086 
2087  // Build the coroutine state immediately and not later during template
2088  // instantiation
2089  if (!CoawaitLoc.isInvalid()) {
2090  if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2091  return StmtError();
2092  }
2093 
2094  // Build auto && __range = range-init
2095  // Divide by 2, since the variables are in the inner scope (loop body).
2096  const auto DepthStr = std::to_string(S->getDepth() / 2);
2097  SourceLocation RangeLoc = Range->getBeginLoc();
2098  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2099  Context.getAutoRRefDeductType(),
2100  std::string("__range") + DepthStr);
2101  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2102  diag::err_for_range_deduction_failure)) {
2103  LoopVar->setInvalidDecl();
2104  return StmtError();
2105  }
2106 
2107  // Claim the type doesn't contain auto: we've already done the checking.
2108  DeclGroupPtrTy RangeGroup =
2109  BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2110  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2111  if (RangeDecl.isInvalid()) {
2112  LoopVar->setInvalidDecl();
2113  return StmtError();
2114  }
2115 
2116  return BuildCXXForRangeStmt(
2117  ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2118  /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2119  /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2120 }
2121 
2122 /// Create the initialization, compare, and increment steps for
2123 /// the range-based for loop expression.
2124 /// This function does not handle array-based for loops,
2125 /// which are created in Sema::BuildCXXForRangeStmt.
2126 ///
2127 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2128 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2129 /// CandidateSet and BEF are set and some non-success value is returned on
2130 /// failure.
2131 static Sema::ForRangeStatus
2132 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2133  QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2135  OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2136  ExprResult *EndExpr, BeginEndFunction *BEF) {
2137  DeclarationNameInfo BeginNameInfo(
2138  &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2139  DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2140  ColonLoc);
2141 
2142  LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2144  LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2145 
2146  auto BuildBegin = [&] {
2147  *BEF = BEF_begin;
2148  Sema::ForRangeStatus RangeStatus =
2149  SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2150  BeginMemberLookup, CandidateSet,
2151  BeginRange, BeginExpr);
2152 
2153  if (RangeStatus != Sema::FRS_Success) {
2154  if (RangeStatus == Sema::FRS_DiagnosticIssued)
2155  SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2156  << ColonLoc << BEF_begin << BeginRange->getType();
2157  return RangeStatus;
2158  }
2159  if (!CoawaitLoc.isInvalid()) {
2160  // FIXME: getCurScope() should not be used during template instantiation.
2161  // We should pick up the set of unqualified lookup results for operator
2162  // co_await during the initial parse.
2163  *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2164  BeginExpr->get());
2165  if (BeginExpr->isInvalid())
2167  }
2168  if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2169  diag::err_for_range_iter_deduction_failure)) {
2170  NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2172  }
2173  return Sema::FRS_Success;
2174  };
2175 
2176  auto BuildEnd = [&] {
2177  *BEF = BEF_end;
2178  Sema::ForRangeStatus RangeStatus =
2179  SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2180  EndMemberLookup, CandidateSet,
2181  EndRange, EndExpr);
2182  if (RangeStatus != Sema::FRS_Success) {
2183  if (RangeStatus == Sema::FRS_DiagnosticIssued)
2184  SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2185  << ColonLoc << BEF_end << EndRange->getType();
2186  return RangeStatus;
2187  }
2188  if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2189  diag::err_for_range_iter_deduction_failure)) {
2190  NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2192  }
2193  return Sema::FRS_Success;
2194  };
2195 
2196  if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2197  // - if _RangeT is a class type, the unqualified-ids begin and end are
2198  // looked up in the scope of class _RangeT as if by class member access
2199  // lookup (3.4.5), and if either (or both) finds at least one
2200  // declaration, begin-expr and end-expr are __range.begin() and
2201  // __range.end(), respectively;
2202  SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2203  if (BeginMemberLookup.isAmbiguous())
2205 
2206  SemaRef.LookupQualifiedName(EndMemberLookup, D);
2207  if (EndMemberLookup.isAmbiguous())
2209 
2210  if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2211  // Look up the non-member form of the member we didn't find, first.
2212  // This way we prefer a "no viable 'end'" diagnostic over a "i found
2213  // a 'begin' but ignored it because there was no member 'end'"
2214  // diagnostic.
2215  auto BuildNonmember = [&](
2216  BeginEndFunction BEFFound, LookupResult &Found,
2217  llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2218  llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2219  LookupResult OldFound = std::move(Found);
2220  Found.clear();
2221 
2222  if (Sema::ForRangeStatus Result = BuildNotFound())
2223  return Result;
2224 
2225  switch (BuildFound()) {
2226  case Sema::FRS_Success:
2227  return Sema::FRS_Success;
2228 
2230  CandidateSet->NoteCandidates(
2231  PartialDiagnosticAt(BeginRange->getBeginLoc(),
2232  SemaRef.PDiag(diag::err_for_range_invalid)
2233  << BeginRange->getType() << BEFFound),
2234  SemaRef, OCD_AllCandidates, BeginRange);
2235  LLVM_FALLTHROUGH;
2236 
2238  for (NamedDecl *D : OldFound) {
2239  SemaRef.Diag(D->getLocation(),
2240  diag::note_for_range_member_begin_end_ignored)
2241  << BeginRange->getType() << BEFFound;
2242  }
2244  }
2245  llvm_unreachable("unexpected ForRangeStatus");
2246  };
2247  if (BeginMemberLookup.empty())
2248  return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2249  return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2250  }
2251  } else {
2252  // - otherwise, begin-expr and end-expr are begin(__range) and
2253  // end(__range), respectively, where begin and end are looked up with
2254  // argument-dependent lookup (3.4.2). For the purposes of this name
2255  // lookup, namespace std is an associated namespace.
2256  }
2257 
2258  if (Sema::ForRangeStatus Result = BuildBegin())
2259  return Result;
2260  return BuildEnd();
2261 }
2262 
2263 /// Speculatively attempt to dereference an invalid range expression.
2264 /// If the attempt fails, this function will return a valid, null StmtResult
2265 /// and emit no diagnostics.
2267  SourceLocation ForLoc,
2268  SourceLocation CoawaitLoc,
2269  Stmt *InitStmt,
2270  Stmt *LoopVarDecl,
2272  Expr *Range,
2273  SourceLocation RangeLoc,
2274  SourceLocation RParenLoc) {
2275  // Determine whether we can rebuild the for-range statement with a
2276  // dereferenced range expression.
2277  ExprResult AdjustedRange;
2278  {
2279  Sema::SFINAETrap Trap(SemaRef);
2280 
2281  AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2282  if (AdjustedRange.isInvalid())
2283  return StmtResult();
2284 
2285  StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2286  S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2287  AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2288  if (SR.isInvalid())
2289  return StmtResult();
2290  }
2291 
2292  // The attempt to dereference worked well enough that it could produce a valid
2293  // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2294  // case there are any other (non-fatal) problems with it.
2295  SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2296  << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2297  return SemaRef.ActOnCXXForRangeStmt(
2298  S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2299  AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2300 }
2301 
2302 namespace {
2303 /// RAII object to automatically invalidate a declaration if an error occurs.
2304 struct InvalidateOnErrorScope {
2305  InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2306  : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2307  ~InvalidateOnErrorScope() {
2308  if (Enabled && Trap.hasErrorOccurred())
2309  D->setInvalidDecl();
2310  }
2311 
2312  DiagnosticErrorTrap Trap;
2313  Decl *D;
2314  bool Enabled;
2315 };
2316 }
2317 
2318 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2320  SourceLocation CoawaitLoc, Stmt *InitStmt,
2321  SourceLocation ColonLoc, Stmt *RangeDecl,
2322  Stmt *Begin, Stmt *End, Expr *Cond,
2323  Expr *Inc, Stmt *LoopVarDecl,
2324  SourceLocation RParenLoc,
2326  // FIXME: This should not be used during template instantiation. We should
2327  // pick up the set of unqualified lookup results for the != and + operators
2328  // in the initial parse.
2329  //
2330  // Testcase (accepts-invalid):
2331  // template<typename T> void f() { for (auto x : T()) {} }
2332  // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2333  // bool operator!=(N::X, N::X); void operator++(N::X);
2334  // void g() { f<N::X>(); }
2335  Scope *S = getCurScope();
2336 
2337  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2338  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2339  QualType RangeVarType = RangeVar->getType();
2340 
2341  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2342  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2343 
2344  // If we hit any errors, mark the loop variable as invalid if its type
2345  // contains 'auto'.
2346  InvalidateOnErrorScope Invalidate(*this, LoopVar,
2347  LoopVar->getType()->isUndeducedType());
2348 
2349  StmtResult BeginDeclStmt = Begin;
2350  StmtResult EndDeclStmt = End;
2351  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2352 
2353  if (RangeVarType->isDependentType()) {
2354  // The range is implicitly used as a placeholder when it is dependent.
2355  RangeVar->markUsed(Context);
2356 
2357  // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2358  // them in properly when we instantiate the loop.
2359  if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2360  if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2361  for (auto *Binding : DD->bindings())
2362  Binding->setType(Context.DependentTy);
2363  LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2364  }
2365  } else if (!BeginDeclStmt.get()) {
2366  SourceLocation RangeLoc = RangeVar->getLocation();
2367 
2368  const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2369 
2370  ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2371  VK_LValue, ColonLoc);
2372  if (BeginRangeRef.isInvalid())
2373  return StmtError();
2374 
2375  ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2376  VK_LValue, ColonLoc);
2377  if (EndRangeRef.isInvalid())
2378  return StmtError();
2379 
2380  QualType AutoType = Context.getAutoDeductType();
2381  Expr *Range = RangeVar->getInit();
2382  if (!Range)
2383  return StmtError();
2384  QualType RangeType = Range->getType();
2385 
2386  if (RequireCompleteType(RangeLoc, RangeType,
2387  diag::err_for_range_incomplete_type))
2388  return StmtError();
2389 
2390  // Build auto __begin = begin-expr, __end = end-expr.
2391  // Divide by 2, since the variables are in the inner scope (loop body).
2392  const auto DepthStr = std::to_string(S->getDepth() / 2);
2393  VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2394  std::string("__begin") + DepthStr);
2395  VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2396  std::string("__end") + DepthStr);
2397 
2398  // Build begin-expr and end-expr and attach to __begin and __end variables.
2399  ExprResult BeginExpr, EndExpr;
2400  if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2401  // - if _RangeT is an array type, begin-expr and end-expr are __range and
2402  // __range + __bound, respectively, where __bound is the array bound. If
2403  // _RangeT is an array of unknown size or an array of incomplete type,
2404  // the program is ill-formed;
2405 
2406  // begin-expr is __range.
2407  BeginExpr = BeginRangeRef;
2408  if (!CoawaitLoc.isInvalid()) {
2409  BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2410  if (BeginExpr.isInvalid())
2411  return StmtError();
2412  }
2413  if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2414  diag::err_for_range_iter_deduction_failure)) {
2415  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2416  return StmtError();
2417  }
2418 
2419  // Find the array bound.
2420  ExprResult BoundExpr;
2421  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2422  BoundExpr = IntegerLiteral::Create(
2423  Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2424  else if (const VariableArrayType *VAT =
2425  dyn_cast<VariableArrayType>(UnqAT)) {
2426  // For a variably modified type we can't just use the expression within
2427  // the array bounds, since we don't want that to be re-evaluated here.
2428  // Rather, we need to determine what it was when the array was first
2429  // created - so we resort to using sizeof(vla)/sizeof(element).
2430  // For e.g.
2431  // void f(int b) {
2432  // int vla[b];
2433  // b = -1; <-- This should not affect the num of iterations below
2434  // for (int &c : vla) { .. }
2435  // }
2436 
2437  // FIXME: This results in codegen generating IR that recalculates the
2438  // run-time number of elements (as opposed to just using the IR Value
2439  // that corresponds to the run-time value of each bound that was
2440  // generated when the array was created.) If this proves too embarrassing
2441  // even for unoptimized IR, consider passing a magic-value/cookie to
2442  // codegen that then knows to simply use that initial llvm::Value (that
2443  // corresponds to the bound at time of array creation) within
2444  // getelementptr. But be prepared to pay the price of increasing a
2445  // customized form of coupling between the two components - which could
2446  // be hard to maintain as the codebase evolves.
2447 
2448  ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2449  EndVar->getLocation(), UETT_SizeOf,
2450  /*IsType=*/true,
2451  CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2452  VAT->desugar(), RangeLoc))
2453  .getAsOpaquePtr(),
2454  EndVar->getSourceRange());
2455  if (SizeOfVLAExprR.isInvalid())
2456  return StmtError();
2457 
2458  ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2459  EndVar->getLocation(), UETT_SizeOf,
2460  /*IsType=*/true,
2461  CreateParsedType(VAT->desugar(),
2462  Context.getTrivialTypeSourceInfo(
2463  VAT->getElementType(), RangeLoc))
2464  .getAsOpaquePtr(),
2465  EndVar->getSourceRange());
2466  if (SizeOfEachElementExprR.isInvalid())
2467  return StmtError();
2468 
2469  BoundExpr =
2470  ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2471  SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2472  if (BoundExpr.isInvalid())
2473  return StmtError();
2474 
2475  } else {
2476  // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2477  // UnqAT is not incomplete and Range is not type-dependent.
2478  llvm_unreachable("Unexpected array type in for-range");
2479  }
2480 
2481  // end-expr is __range + __bound.
2482  EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2483  BoundExpr.get());
2484  if (EndExpr.isInvalid())
2485  return StmtError();
2486  if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2487  diag::err_for_range_iter_deduction_failure)) {
2488  NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2489  return StmtError();
2490  }
2491  } else {
2492  OverloadCandidateSet CandidateSet(RangeLoc,
2494  BeginEndFunction BEFFailure;
2495  ForRangeStatus RangeStatus = BuildNonArrayForRange(
2496  *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2497  EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2498  &BEFFailure);
2499 
2500  if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2501  BEFFailure == BEF_begin) {
2502  // If the range is being built from an array parameter, emit a
2503  // a diagnostic that it is being treated as a pointer.
2504  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2505  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2506  QualType ArrayTy = PVD->getOriginalType();
2507  QualType PointerTy = PVD->getType();
2508  if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2509  Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2510  << RangeLoc << PVD << ArrayTy << PointerTy;
2511  Diag(PVD->getLocation(), diag::note_declared_at);
2512  return StmtError();
2513  }
2514  }
2515  }
2516 
2517  // If building the range failed, try dereferencing the range expression
2518  // unless a diagnostic was issued or the end function is problematic.
2519  StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2520  CoawaitLoc, InitStmt,
2521  LoopVarDecl, ColonLoc,
2522  Range, RangeLoc,
2523  RParenLoc);
2524  if (SR.isInvalid() || SR.isUsable())
2525  return SR;
2526  }
2527 
2528  // Otherwise, emit diagnostics if we haven't already.
2529  if (RangeStatus == FRS_NoViableFunction) {
2530  Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2531  CandidateSet.NoteCandidates(
2533  PDiag(diag::err_for_range_invalid)
2534  << RangeLoc << Range->getType()
2535  << BEFFailure),
2536  *this, OCD_AllCandidates, Range);
2537  }
2538  // Return an error if no fix was discovered.
2539  if (RangeStatus != FRS_Success)
2540  return StmtError();
2541  }
2542 
2543  assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2544  "invalid range expression in for loop");
2545 
2546  // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2547  // C++1z removes this restriction.
2548  QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2549  if (!Context.hasSameType(BeginType, EndType)) {
2550  Diag(RangeLoc, getLangOpts().CPlusPlus17
2551  ? diag::warn_for_range_begin_end_types_differ
2552  : diag::ext_for_range_begin_end_types_differ)
2553  << BeginType << EndType;
2554  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2555  NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2556  }
2557 
2558  BeginDeclStmt =
2559  ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2560  EndDeclStmt =
2561  ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2562 
2563  const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2564  ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2565  VK_LValue, ColonLoc);
2566  if (BeginRef.isInvalid())
2567  return StmtError();
2568 
2569  ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2570  VK_LValue, ColonLoc);
2571  if (EndRef.isInvalid())
2572  return StmtError();
2573 
2574  // Build and check __begin != __end expression.
2575  NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2576  BeginRef.get(), EndRef.get());
2577  if (!NotEqExpr.isInvalid())
2578  NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2579  if (!NotEqExpr.isInvalid())
2580  NotEqExpr =
2581  ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2582  if (NotEqExpr.isInvalid()) {
2583  Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2584  << RangeLoc << 0 << BeginRangeRef.get()->getType();
2585  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2586  if (!Context.hasSameType(BeginType, EndType))
2587  NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2588  return StmtError();
2589  }
2590 
2591  // Build and check ++__begin expression.
2592  BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2593  VK_LValue, ColonLoc);
2594  if (BeginRef.isInvalid())
2595  return StmtError();
2596 
2597  IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2598  if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2599  // FIXME: getCurScope() should not be used during template instantiation.
2600  // We should pick up the set of unqualified lookup results for operator
2601  // co_await during the initial parse.
2602  IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2603  if (!IncrExpr.isInvalid())
2604  IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2605  if (IncrExpr.isInvalid()) {
2606  Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2607  << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2608  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2609  return StmtError();
2610  }
2611 
2612  // Build and check *__begin expression.
2613  BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2614  VK_LValue, ColonLoc);
2615  if (BeginRef.isInvalid())
2616  return StmtError();
2617 
2618  ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2619  if (DerefExpr.isInvalid()) {
2620  Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2621  << RangeLoc << 1 << BeginRangeRef.get()->getType();
2622  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2623  return StmtError();
2624  }
2625 
2626  // Attach *__begin as initializer for VD. Don't touch it if we're just
2627  // trying to determine whether this would be a valid range.
2628  if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2629  AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2630  if (LoopVar->isInvalidDecl())
2631  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2632  }
2633  }
2634 
2635  // Don't bother to actually allocate the result if we're just trying to
2636  // determine whether it would be valid.
2637  if (Kind == BFRK_Check)
2638  return StmtResult();
2639 
2640  return new (Context) CXXForRangeStmt(
2641  InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2642  cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2643  IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2644  ColonLoc, RParenLoc);
2645 }
2646 
2647 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2648 /// statement.
2650  if (!S || !B)
2651  return StmtError();
2652  ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2653 
2654  ForStmt->setBody(B);
2655  return S;
2656 }
2657 
2658 // Warn when the loop variable is a const reference that creates a copy.
2659 // Suggest using the non-reference type for copies. If a copy can be prevented
2660 // suggest the const reference type that would do so.
2661 // For instance, given "for (const &Foo : Range)", suggest
2662 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2663 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2664 // the copy altogether.
2666  const VarDecl *VD,
2667  QualType RangeInitType) {
2668  const Expr *InitExpr = VD->getInit();
2669  if (!InitExpr)
2670  return;
2671 
2672  QualType VariableType = VD->getType();
2673 
2674  if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2675  if (!Cleanups->cleanupsHaveSideEffects())
2676  InitExpr = Cleanups->getSubExpr();
2677 
2678  const MaterializeTemporaryExpr *MTE =
2679  dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2680 
2681  // No copy made.
2682  if (!MTE)
2683  return;
2684 
2685  const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2686 
2687  // Searching for either UnaryOperator for dereference of a pointer or
2688  // CXXOperatorCallExpr for handling iterators.
2689  while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2690  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2691  E = CCE->getArg(0);
2692  } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2693  const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2694  E = ME->getBase();
2695  } else {
2696  const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2697  E = MTE->GetTemporaryExpr();
2698  }
2699  E = E->IgnoreImpCasts();
2700  }
2701 
2702  bool ReturnsReference = false;
2703  if (isa<UnaryOperator>(E)) {
2704  ReturnsReference = true;
2705  } else {
2706  const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2707  const FunctionDecl *FD = Call->getDirectCallee();
2708  QualType ReturnType = FD->getReturnType();
2709  ReturnsReference = ReturnType->isReferenceType();
2710  }
2711 
2712  if (ReturnsReference) {
2713  // Loop variable creates a temporary. Suggest either to go with
2714  // non-reference loop variable to indicate a copy is made, or
2715  // the correct time to bind a const reference.
2716  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2717  << VD << VariableType << E->getType();
2718  QualType NonReferenceType = VariableType.getNonReferenceType();
2719  NonReferenceType.removeLocalConst();
2720  QualType NewReferenceType =
2722  SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2723  << NonReferenceType << NewReferenceType << VD->getSourceRange();
2724  } else {
2725  // The range always returns a copy, so a temporary is always created.
2726  // Suggest removing the reference from the loop variable.
2727  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2728  << VD << RangeInitType;
2729  QualType NonReferenceType = VariableType.getNonReferenceType();
2730  NonReferenceType.removeLocalConst();
2731  SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2732  << NonReferenceType << VD->getSourceRange();
2733  }
2734 }
2735 
2736 // Warns when the loop variable can be changed to a reference type to
2737 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2738 // "for (const Foo &x : Range)" if this form does not make a copy.
2740  const VarDecl *VD) {
2741  const Expr *InitExpr = VD->getInit();
2742  if (!InitExpr)
2743  return;
2744 
2745  QualType VariableType = VD->getType();
2746 
2747  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2748  if (!CE->getConstructor()->isCopyConstructor())
2749  return;
2750  } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2751  if (CE->getCastKind() != CK_LValueToRValue)
2752  return;
2753  } else {
2754  return;
2755  }
2756 
2757  // TODO: Determine a maximum size that a POD type can be before a diagnostic
2758  // should be emitted. Also, only ignore POD types with trivial copy
2759  // constructors.
2760  if (VariableType.isPODType(SemaRef.Context))
2761  return;
2762 
2763  // Suggest changing from a const variable to a const reference variable
2764  // if doing so will prevent a copy.
2765  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2766  << VD << VariableType << InitExpr->getType();
2767  SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
2768  << SemaRef.Context.getLValueReferenceType(VariableType)
2769  << VD->getSourceRange();
2770 }
2771 
2772 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2773 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2774 /// using "const foo x" to show that a copy is made
2775 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2776 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2777 /// prevent the copy.
2778 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2779 /// Suggest "const foo &x" to prevent the copy.
2781  const CXXForRangeStmt *ForStmt) {
2782  if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2783  ForStmt->getBeginLoc()) &&
2784  SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2785  ForStmt->getBeginLoc()) &&
2786  SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2787  ForStmt->getBeginLoc())) {
2788  return;
2789  }
2790 
2791  const VarDecl *VD = ForStmt->getLoopVariable();
2792  if (!VD)
2793  return;
2794 
2795  QualType VariableType = VD->getType();
2796 
2797  if (VariableType->isIncompleteType())
2798  return;
2799 
2800  const Expr *InitExpr = VD->getInit();
2801  if (!InitExpr)
2802  return;
2803 
2804  if (VariableType->isReferenceType()) {
2806  ForStmt->getRangeInit()->getType());
2807  } else if (VariableType.isConstQualified()) {
2809  }
2810 }
2811 
2812 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2813 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2814 /// body cannot be performed until after the type of the range variable is
2815 /// determined.
2817  if (!S || !B)
2818  return StmtError();
2819 
2820  if (isa<ObjCForCollectionStmt>(S))
2821  return FinishObjCForCollectionStmt(S, B);
2822 
2823  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2824  ForStmt->setBody(B);
2825 
2826  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2827  diag::warn_empty_range_based_for_body);
2828 
2829  DiagnoseForRangeVariableCopies(*this, ForStmt);
2830 
2831  return S;
2832 }
2833 
2835  SourceLocation LabelLoc,
2836  LabelDecl *TheDecl) {
2837  setFunctionHasBranchIntoScope();
2838  TheDecl->markUsed(Context);
2839  return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2840 }
2841 
2842 StmtResult
2844  Expr *E) {
2845  // Convert operand to void*
2846  if (!E->isTypeDependent()) {
2847  QualType ETy = E->getType();
2848  QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2849  ExprResult ExprRes = E;
2850  AssignConvertType ConvTy =
2851  CheckSingleAssignmentConstraints(DestTy, ExprRes);
2852  if (ExprRes.isInvalid())
2853  return StmtError();
2854  E = ExprRes.get();
2855  if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2856  return StmtError();
2857  }
2858 
2859  ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2860  if (ExprRes.isInvalid())
2861  return StmtError();
2862  E = ExprRes.get();
2863 
2864  setFunctionHasIndirectGoto();
2865 
2866  return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2867 }
2868 
2870  const Scope &DestScope) {
2871  if (!S.CurrentSEHFinally.empty() &&
2872  DestScope.Contains(*S.CurrentSEHFinally.back())) {
2873  S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2874  }
2875 }
2876 
2877 StmtResult
2879  Scope *S = CurScope->getContinueParent();
2880  if (!S) {
2881  // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2882  return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2883  }
2884  CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2885 
2886  return new (Context) ContinueStmt(ContinueLoc);
2887 }
2888 
2889 StmtResult
2891  Scope *S = CurScope->getBreakParent();
2892  if (!S) {
2893  // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2894  return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2895  }
2896  if (S->isOpenMPLoopScope())
2897  return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2898  << "break");
2899  CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2900 
2901  return new (Context) BreakStmt(BreakLoc);
2902 }
2903 
2904 /// Determine whether the given expression is a candidate for
2905 /// copy elision in either a return statement or a throw expression.
2906 ///
2907 /// \param ReturnType If we're determining the copy elision candidate for
2908 /// a return statement, this is the return type of the function. If we're
2909 /// determining the copy elision candidate for a throw expression, this will
2910 /// be a NULL type.
2911 ///
2912 /// \param E The expression being returned from the function or block, or
2913 /// being thrown.
2914 ///
2915 /// \param CESK Whether we allow function parameters or
2916 /// id-expressions that could be moved out of the function to be considered NRVO
2917 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2918 /// determine whether we should try to move as part of a return or throw (which
2919 /// does allow function parameters).
2920 ///
2921 /// \returns The NRVO candidate variable, if the return statement may use the
2922 /// NRVO, or NULL if there is no such candidate.
2924  CopyElisionSemanticsKind CESK) {
2925  // - in a return statement in a function [where] ...
2926  // ... the expression is the name of a non-volatile automatic object ...
2927  DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2928  if (!DR || DR->refersToEnclosingVariableOrCapture())
2929  return nullptr;
2930  VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2931  if (!VD)
2932  return nullptr;
2933 
2934  if (isCopyElisionCandidate(ReturnType, VD, CESK))
2935  return VD;
2936  return nullptr;
2937 }
2938 
2939 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2940  CopyElisionSemanticsKind CESK) {
2941  QualType VDType = VD->getType();
2942  // - in a return statement in a function with ...
2943  // ... a class return type ...
2944  if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2945  if (!ReturnType->isRecordType())
2946  return false;
2947  // ... the same cv-unqualified type as the function return type ...
2948  // When considering moving this expression out, allow dissimilar types.
2949  if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
2950  !Context.hasSameUnqualifiedType(ReturnType, VDType))
2951  return false;
2952  }
2953 
2954  // ...object (other than a function or catch-clause parameter)...
2955  if (VD->getKind() != Decl::Var &&
2956  !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
2957  return false;
2958  if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2959  return false;
2960 
2961  // ...automatic...
2962  if (!VD->hasLocalStorage()) return false;
2963 
2964  // Return false if VD is a __block variable. We don't want to implicitly move
2965  // out of a __block variable during a return because we cannot assume the
2966  // variable will no longer be used.
2967  if (VD->hasAttr<BlocksAttr>()) return false;
2968 
2969  if (CESK & CES_AllowDifferentTypes)
2970  return true;
2971 
2972  // ...non-volatile...
2973  if (VD->getType().isVolatileQualified()) return false;
2974 
2975  // Variables with higher required alignment than their type's ABI
2976  // alignment cannot use NRVO.
2977  if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2978  Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2979  return false;
2980 
2981  return true;
2982 }
2983 
2984 /// Try to perform the initialization of a potentially-movable value,
2985 /// which is the operand to a return or throw statement.
2986 ///
2987 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2988 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2989 /// then falls back to treating them as lvalues if that failed.
2990 ///
2991 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2992 /// resolutions that find non-constructors, such as derived-to-base conversions
2993 /// or `operator T()&&` member functions. If false, do consider such
2994 /// conversion sequences.
2995 ///
2996 /// \param Res We will fill this in if move-initialization was possible.
2997 /// If move-initialization is not possible, such that we must fall back to
2998 /// treating the operand as an lvalue, we will leave Res in its original
2999 /// invalid state.
3001  const InitializedEntity &Entity,
3002  const VarDecl *NRVOCandidate,
3003  QualType ResultType,
3004  Expr *&Value,
3005  bool ConvertingConstructorsOnly,
3006  ExprResult &Res) {
3008  CK_NoOp, Value, VK_XValue);
3009 
3010  Expr *InitExpr = &AsRvalue;
3011 
3013  Value->getBeginLoc(), Value->getBeginLoc());
3014 
3015  InitializationSequence Seq(S, Entity, Kind, InitExpr);
3016 
3017  if (!Seq)
3018  return;
3019 
3020  for (const InitializationSequence::Step &Step : Seq.steps()) {
3023  continue;
3024 
3025  FunctionDecl *FD = Step.Function.Function;
3026  if (ConvertingConstructorsOnly) {
3027  if (isa<CXXConstructorDecl>(FD)) {
3028  // C++14 [class.copy]p32:
3029  // [...] If the first overload resolution fails or was not performed,
3030  // or if the type of the first parameter of the selected constructor
3031  // is not an rvalue reference to the object's type (possibly
3032  // cv-qualified), overload resolution is performed again, considering
3033  // the object as an lvalue.
3034  const RValueReferenceType *RRefType =
3036  if (!RRefType)
3037  break;
3038  if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3039  NRVOCandidate->getType()))
3040  break;
3041  } else {
3042  continue;
3043  }
3044  } else {
3045  if (isa<CXXConstructorDecl>(FD)) {
3046  // Check that overload resolution selected a constructor taking an
3047  // rvalue reference. If it selected an lvalue reference, then we
3048  // didn't need to cast this thing to an rvalue in the first place.
3049  if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3050  break;
3051  } else if (isa<CXXMethodDecl>(FD)) {
3052  // Check that overload resolution selected a conversion operator
3053  // taking an rvalue reference.
3054  if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3055  break;
3056  } else {
3057  continue;
3058  }
3059  }
3060 
3061  // Promote "AsRvalue" to the heap, since we now need this
3062  // expression node to persist.
3063  Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3064  Value, nullptr, VK_XValue);
3065 
3066  // Complete type-checking the initialization of the return type
3067  // using the constructor we found.
3068  Res = Seq.Perform(S, Entity, Kind, Value);
3069  }
3070 }
3071 
3072 /// Perform the initialization of a potentially-movable value, which
3073 /// is the result of return value.
3074 ///
3075 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3076 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3077 /// then falls back to treating them as lvalues if that failed.
3078 ExprResult
3080  const VarDecl *NRVOCandidate,
3081  QualType ResultType,
3082  Expr *Value,
3083  bool AllowNRVO) {
3084  // C++14 [class.copy]p32:
3085  // When the criteria for elision of a copy/move operation are met, but not for
3086  // an exception-declaration, and the object to be copied is designated by an
3087  // lvalue, or when the expression in a return statement is a (possibly
3088  // parenthesized) id-expression that names an object with automatic storage
3089  // duration declared in the body or parameter-declaration-clause of the
3090  // innermost enclosing function or lambda-expression, overload resolution to
3091  // select the constructor for the copy is first performed as if the object
3092  // were designated by an rvalue.
3093  ExprResult Res = ExprError();
3094 
3095  if (AllowNRVO) {
3096  bool AffectedByCWG1579 = false;
3097 
3098  if (!NRVOCandidate) {
3099  NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3100  if (NRVOCandidate &&
3101  !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3102  Value->getExprLoc())) {
3103  const VarDecl *NRVOCandidateInCXX11 =
3104  getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3105  AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3106  }
3107  }
3108 
3109  if (NRVOCandidate) {
3110  TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3111  true, Res);
3112  }
3113 
3114  if (!Res.isInvalid() && AffectedByCWG1579) {
3115  QualType QT = NRVOCandidate->getType();
3116  if (QT.getNonReferenceType()
3118  .isTriviallyCopyableType(Context)) {
3119  // Adding 'std::move' around a trivially copyable variable is probably
3120  // pointless. Don't suggest it.
3121  } else {
3122  // Common cases for this are returning unique_ptr<Derived> from a
3123  // function of return type unique_ptr<Base>, or returning T from a
3124  // function of return type Expected<T>. This is totally fine in a
3125  // post-CWG1579 world, but was not fine before.
3126  assert(!ResultType.isNull());
3127  SmallString<32> Str;
3128  Str += "std::move(";
3129  Str += NRVOCandidate->getDeclName().getAsString();
3130  Str += ")";
3131  Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3132  << Value->getSourceRange()
3133  << NRVOCandidate->getDeclName() << ResultType << QT;
3134  Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3135  << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3136  }
3137  } else if (Res.isInvalid() &&
3138  !getDiagnostics().isIgnored(diag::warn_return_std_move,
3139  Value->getExprLoc())) {
3140  const VarDecl *FakeNRVOCandidate =
3141  getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3142  if (FakeNRVOCandidate) {
3143  QualType QT = FakeNRVOCandidate->getType();
3144  if (QT->isLValueReferenceType()) {
3145  // Adding 'std::move' around an lvalue reference variable's name is
3146  // dangerous. Don't suggest it.
3147  } else if (QT.getNonReferenceType()
3149  .isTriviallyCopyableType(Context)) {
3150  // Adding 'std::move' around a trivially copyable variable is probably
3151  // pointless. Don't suggest it.
3152  } else {
3153  ExprResult FakeRes = ExprError();
3154  Expr *FakeValue = Value;
3155  TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3156  FakeValue, false, FakeRes);
3157  if (!FakeRes.isInvalid()) {
3158  bool IsThrow =
3160  SmallString<32> Str;
3161  Str += "std::move(";
3162  Str += FakeNRVOCandidate->getDeclName().getAsString();
3163  Str += ")";
3164  Diag(Value->getExprLoc(), diag::warn_return_std_move)
3165  << Value->getSourceRange()
3166  << FakeNRVOCandidate->getDeclName() << IsThrow;
3167  Diag(Value->getExprLoc(), diag::note_add_std_move)
3168  << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3169  }
3170  }
3171  }
3172  }
3173  }
3174 
3175  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3176  // above, or overload resolution failed. Either way, we need to try
3177  // (again) now with the return value expression as written.
3178  if (Res.isInvalid())
3179  Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3180 
3181  return Res;
3182 }
3183 
3184 /// Determine whether the declared return type of the specified function
3185 /// contains 'auto'.
3187  const FunctionProtoType *FPT =
3189  return FPT->getReturnType()->isUndeducedType();
3190 }
3191 
3192 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3193 /// for capturing scopes.
3194 ///
3195 StmtResult
3197  // If this is the first return we've seen, infer the return type.
3198  // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3199  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3200  QualType FnRetType = CurCap->ReturnType;
3201  LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3202  bool HasDeducedReturnType =
3203  CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3204 
3205  if (ExprEvalContexts.back().Context ==
3206  ExpressionEvaluationContext::DiscardedStatement &&
3207  (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3208  if (RetValExp) {
3209  ExprResult ER =
3210  ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3211  if (ER.isInvalid())
3212  return StmtError();
3213  RetValExp = ER.get();
3214  }
3215  return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3216  /* NRVOCandidate=*/nullptr);
3217  }
3218 
3219  if (HasDeducedReturnType) {
3220  // In C++1y, the return type may involve 'auto'.
3221  // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3222  FunctionDecl *FD = CurLambda->CallOperator;
3223  if (CurCap->ReturnType.isNull())
3224  CurCap->ReturnType = FD->getReturnType();
3225 
3226  AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3227  assert(AT && "lost auto type from lambda return type");
3228  if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3229  FD->setInvalidDecl();
3230  return StmtError();
3231  }
3232  CurCap->ReturnType = FnRetType = FD->getReturnType();
3233  } else if (CurCap->HasImplicitReturnType) {
3234  // For blocks/lambdas with implicit return types, we check each return
3235  // statement individually, and deduce the common return type when the block
3236  // or lambda is completed.
3237  // FIXME: Fold this into the 'auto' codepath above.
3238  if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3239  ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3240  if (Result.isInvalid())
3241  return StmtError();
3242  RetValExp = Result.get();
3243 
3244  // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3245  // when deducing a return type for a lambda-expression (or by extension
3246  // for a block). These rules differ from the stated C++11 rules only in
3247  // that they remove top-level cv-qualifiers.
3248  if (!CurContext->isDependentContext())
3249  FnRetType = RetValExp->getType().getUnqualifiedType();
3250  else
3251  FnRetType = CurCap->ReturnType = Context.DependentTy;
3252  } else {
3253  if (RetValExp) {
3254  // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3255  // initializer list, because it is not an expression (even
3256  // though we represent it as one). We still deduce 'void'.
3257  Diag(ReturnLoc, diag::err_lambda_return_init_list)
3258  << RetValExp->getSourceRange();
3259  }
3260 
3261  FnRetType = Context.VoidTy;
3262  }
3263 
3264  // Although we'll properly infer the type of the block once it's completed,
3265  // make sure we provide a return type now for better error recovery.
3266  if (CurCap->ReturnType.isNull())
3267  CurCap->ReturnType = FnRetType;
3268  }
3269  assert(!FnRetType.isNull());
3270 
3271  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3272  if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3273  Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3274  return StmtError();
3275  }
3276  } else if (CapturedRegionScopeInfo *CurRegion =
3277  dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3278  Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3279  return StmtError();
3280  } else {
3281  assert(CurLambda && "unknown kind of captured scope");
3282  if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3283  ->getNoReturnAttr()) {
3284  Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3285  return StmtError();
3286  }
3287  }
3288 
3289  // Otherwise, verify that this result type matches the previous one. We are
3290  // pickier with blocks than for normal functions because we don't have GCC
3291  // compatibility to worry about here.
3292  const VarDecl *NRVOCandidate = nullptr;
3293  if (FnRetType->isDependentType()) {
3294  // Delay processing for now. TODO: there are lots of dependent
3295  // types we can conclusively prove aren't void.
3296  } else if (FnRetType->isVoidType()) {
3297  if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3298  !(getLangOpts().CPlusPlus &&
3299  (RetValExp->isTypeDependent() ||
3300  RetValExp->getType()->isVoidType()))) {
3301  if (!getLangOpts().CPlusPlus &&
3302  RetValExp->getType()->isVoidType())
3303  Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3304  else {
3305  Diag(ReturnLoc, diag::err_return_block_has_expr);
3306  RetValExp = nullptr;
3307  }
3308  }
3309  } else if (!RetValExp) {
3310  return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3311  } else if (!RetValExp->isTypeDependent()) {
3312  // we have a non-void block with an expression, continue checking
3313 
3314  // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3315  // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3316  // function return.
3317 
3318  // In C++ the return statement is handled via a copy initialization.
3319  // the C version of which boils down to CheckSingleAssignmentConstraints.
3320  NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3322  FnRetType,
3323  NRVOCandidate != nullptr);
3324  ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3325  FnRetType, RetValExp);
3326  if (Res.isInvalid()) {
3327  // FIXME: Cleanup temporaries here, anyway?
3328  return StmtError();
3329  }
3330  RetValExp = Res.get();
3331  CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3332  } else {
3333  NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3334  }
3335 
3336  if (RetValExp) {
3337  ExprResult ER =
3338  ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3339  if (ER.isInvalid())
3340  return StmtError();
3341  RetValExp = ER.get();
3342  }
3343  auto *Result =
3344  ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3345 
3346  // If we need to check for the named return value optimization,
3347  // or if we need to infer the return type,
3348  // save the return statement in our scope for later processing.
3349  if (CurCap->HasImplicitReturnType || NRVOCandidate)
3350  FunctionScopes.back()->Returns.push_back(Result);
3351 
3352  if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3353  FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3354 
3355  return Result;
3356 }
3357 
3358 namespace {
3359 /// Marks all typedefs in all local classes in a type referenced.
3360 ///
3361 /// In a function like
3362 /// auto f() {
3363 /// struct S { typedef int a; };
3364 /// return S();
3365 /// }
3366 ///
3367 /// the local type escapes and could be referenced in some TUs but not in
3368 /// others. Pretend that all local typedefs are always referenced, to not warn
3369 /// on this. This isn't necessary if f has internal linkage, or the typedef
3370 /// is private.
3371 class LocalTypedefNameReferencer
3372  : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3373 public:
3374  LocalTypedefNameReferencer(Sema &S) : S(S) {}
3375  bool VisitRecordType(const RecordType *RT);
3376 private:
3377  Sema &S;
3378 };
3379 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3380  auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3381  if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3382  R->isDependentType())
3383  return true;
3384  for (auto *TmpD : R->decls())
3385  if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3386  if (T->getAccess() != AS_private || R->hasFriends())
3387  S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3388  return true;
3389 }
3390 }
3391 
3393  return FD->getTypeSourceInfo()
3394  ->getTypeLoc()
3396  .getReturnLoc();
3397 }
3398 
3399 /// Deduce the return type for a function from a returned expression, per
3400 /// C++1y [dcl.spec.auto]p6.
3402  SourceLocation ReturnLoc,
3403  Expr *&RetExpr,
3404  AutoType *AT) {
3405  // If this is the conversion function for a lambda, we choose to deduce it
3406  // type from the corresponding call operator, not from the synthesized return
3407  // statement within it. See Sema::DeduceReturnType.
3409  return false;
3410 
3411  TypeLoc OrigResultType = getReturnTypeLoc(FD);
3412  QualType Deduced;
3413 
3414  if (RetExpr && isa<InitListExpr>(RetExpr)) {
3415  // If the deduction is for a return statement and the initializer is
3416  // a braced-init-list, the program is ill-formed.
3417  Diag(RetExpr->getExprLoc(),
3418  getCurLambda() ? diag::err_lambda_return_init_list
3419  : diag::err_auto_fn_return_init_list)
3420  << RetExpr->getSourceRange();
3421  return true;
3422  }
3423 
3424  if (FD->isDependentContext()) {
3425  // C++1y [dcl.spec.auto]p12:
3426  // Return type deduction [...] occurs when the definition is
3427  // instantiated even if the function body contains a return
3428  // statement with a non-type-dependent operand.
3429  assert(AT->isDeduced() && "should have deduced to dependent type");
3430  return false;
3431  }
3432 
3433  if (RetExpr) {
3434  // Otherwise, [...] deduce a value for U using the rules of template
3435  // argument deduction.
3436  DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3437 
3438  if (DAR == DAR_Failed && !FD->isInvalidDecl())
3439  Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3440  << OrigResultType.getType() << RetExpr->getType();
3441 
3442  if (DAR != DAR_Succeeded)
3443  return true;
3444 
3445  // If a local type is part of the returned type, mark its fields as
3446  // referenced.
3447  LocalTypedefNameReferencer Referencer(*this);
3448  Referencer.TraverseType(RetExpr->getType());
3449  } else {
3450  // In the case of a return with no operand, the initializer is considered
3451  // to be void().
3452  //
3453  // Deduction here can only succeed if the return type is exactly 'cv auto'
3454  // or 'decltype(auto)', so just check for that case directly.
3455  if (!OrigResultType.getType()->getAs<AutoType>()) {
3456  Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3457  << OrigResultType.getType();
3458  return true;
3459  }
3460  // We always deduce U = void in this case.
3461  Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3462  if (Deduced.isNull())
3463  return true;
3464  }
3465 
3466  // If a function with a declared return type that contains a placeholder type
3467  // has multiple return statements, the return type is deduced for each return
3468  // statement. [...] if the type deduced is not the same in each deduction,
3469  // the program is ill-formed.
3470  QualType DeducedT = AT->getDeducedType();
3471  if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3472  AutoType *NewAT = Deduced->getContainedAutoType();
3473  // It is possible that NewAT->getDeducedType() is null. When that happens,
3474  // we should not crash, instead we ignore this deduction.
3475  if (NewAT->getDeducedType().isNull())
3476  return false;
3477 
3478  CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3479  DeducedT);
3480  CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3481  NewAT->getDeducedType());
3482  if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3483  const LambdaScopeInfo *LambdaSI = getCurLambda();
3484  if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3485  Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3486  << NewAT->getDeducedType() << DeducedT
3487  << true /*IsLambda*/;
3488  } else {
3489  Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3490  << (AT->isDecltypeAuto() ? 1 : 0)
3491  << NewAT->getDeducedType() << DeducedT;
3492  }
3493  return true;
3494  }
3495  } else if (!FD->isInvalidDecl()) {
3496  // Update all declarations of the function to have the deduced return type.
3497  Context.adjustDeducedFunctionResultType(FD, Deduced);
3498  }
3499 
3500  return false;
3501 }
3502 
3503 StmtResult
3505  Scope *CurScope) {
3506  // Correct typos, in case the containing function returns 'auto' and
3507  // RetValExp should determine the deduced type.
3508  ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
3509  if (RetVal.isInvalid())
3510  return StmtError();
3511  StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
3512  if (R.isInvalid() || ExprEvalContexts.back().Context ==
3513  ExpressionEvaluationContext::DiscardedStatement)
3514  return R;
3515 
3516  if (VarDecl *VD =
3517  const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3518  CurScope->addNRVOCandidate(VD);
3519  } else {
3520  CurScope->setNoNRVO();
3521  }
3522 
3523  CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3524 
3525  return R;
3526 }
3527 
3529  // Check for unexpanded parameter packs.
3530  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3531  return StmtError();
3532 
3533  if (isa<CapturingScopeInfo>(getCurFunction()))
3534  return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3535 
3536  QualType FnRetType;
3537  QualType RelatedRetType;
3538  const AttrVec *Attrs = nullptr;
3539  bool isObjCMethod = false;
3540 
3541  if (const FunctionDecl *FD = getCurFunctionDecl()) {
3542  FnRetType = FD->getReturnType();
3543  if (FD->hasAttrs())
3544  Attrs = &FD->getAttrs();
3545  if (FD->isNoReturn())
3546  Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3547  << FD->getDeclName();
3548  if (FD->isMain() && RetValExp)
3549  if (isa<CXXBoolLiteralExpr>(RetValExp))
3550  Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3551  << RetValExp->getSourceRange();
3552  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3553  FnRetType = MD->getReturnType();
3554  isObjCMethod = true;
3555  if (MD->hasAttrs())
3556  Attrs = &MD->getAttrs();
3557  if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3558  // In the implementation of a method with a related return type, the
3559  // type used to type-check the validity of return statements within the
3560  // method body is a pointer to the type of the class being implemented.
3561  RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3562  RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3563  }
3564  } else // If we don't have a function/method context, bail.
3565  return StmtError();
3566 
3567  // C++1z: discarded return statements are not considered when deducing a
3568  // return type.
3569  if (ExprEvalContexts.back().Context ==
3570  ExpressionEvaluationContext::DiscardedStatement &&
3571  FnRetType->getContainedAutoType()) {
3572  if (RetValExp) {
3573  ExprResult ER =
3574  ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3575  if (ER.isInvalid())
3576  return StmtError();
3577  RetValExp = ER.get();
3578  }
3579  return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3580  /* NRVOCandidate=*/nullptr);
3581  }
3582 
3583  // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3584  // deduction.
3585  if (getLangOpts().CPlusPlus14) {
3586  if (AutoType *AT = FnRetType->getContainedAutoType()) {
3587  FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3588  if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3589  FD->setInvalidDecl();
3590  return StmtError();
3591  } else {
3592  FnRetType = FD->getReturnType();
3593  }
3594  }
3595  }
3596 
3597  bool HasDependentReturnType = FnRetType->isDependentType();
3598 
3599  ReturnStmt *Result = nullptr;
3600  if (FnRetType->isVoidType()) {
3601  if (RetValExp) {
3602  if (isa<InitListExpr>(RetValExp)) {
3603  // We simply never allow init lists as the return value of void
3604  // functions. This is compatible because this was never allowed before,
3605  // so there's no legacy code to deal with.
3606  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3607  int FunctionKind = 0;
3608  if (isa<ObjCMethodDecl>(CurDecl))
3609  FunctionKind = 1;
3610  else if (isa<CXXConstructorDecl>(CurDecl))
3611  FunctionKind = 2;
3612  else if (isa<CXXDestructorDecl>(CurDecl))
3613  FunctionKind = 3;
3614 
3615  Diag(ReturnLoc, diag::err_return_init_list)
3616  << CurDecl->getDeclName() << FunctionKind
3617  << RetValExp->getSourceRange();
3618 
3619  // Drop the expression.
3620  RetValExp = nullptr;
3621  } else if (!RetValExp->isTypeDependent()) {
3622  // C99 6.8.6.4p1 (ext_ since GCC warns)
3623  unsigned D = diag::ext_return_has_expr;
3624  if (RetValExp->getType()->isVoidType()) {
3625  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3626  if (isa<CXXConstructorDecl>(CurDecl) ||
3627  isa<CXXDestructorDecl>(CurDecl))
3628  D = diag::err_ctor_dtor_returns_void;
3629  else
3630  D = diag::ext_return_has_void_expr;
3631  }
3632  else {
3633  ExprResult Result = RetValExp;
3634  Result = IgnoredValueConversions(Result.get());
3635  if (Result.isInvalid())
3636  return StmtError();
3637  RetValExp = Result.get();
3638  RetValExp = ImpCastExprToType(RetValExp,
3639  Context.VoidTy, CK_ToVoid).get();
3640  }
3641  // return of void in constructor/destructor is illegal in C++.
3642  if (D == diag::err_ctor_dtor_returns_void) {
3643  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3644  Diag(ReturnLoc, D)
3645  << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3646  << RetValExp->getSourceRange();
3647  }
3648  // return (some void expression); is legal in C++.
3649  else if (D != diag::ext_return_has_void_expr ||
3650  !getLangOpts().CPlusPlus) {
3651  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3652 
3653  int FunctionKind = 0;
3654  if (isa<ObjCMethodDecl>(CurDecl))
3655  FunctionKind = 1;
3656  else if (isa<CXXConstructorDecl>(CurDecl))
3657  FunctionKind = 2;
3658  else if (isa<CXXDestructorDecl>(CurDecl))
3659  FunctionKind = 3;
3660 
3661  Diag(ReturnLoc, D)
3662  << CurDecl->getDeclName() << FunctionKind
3663  << RetValExp->getSourceRange();
3664  }
3665  }
3666 
3667  if (RetValExp) {
3668  ExprResult ER =
3669  ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3670  if (ER.isInvalid())
3671  return StmtError();
3672  RetValExp = ER.get();
3673  }
3674  }
3675 
3676  Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3677  /* NRVOCandidate=*/nullptr);
3678  } else if (!RetValExp && !HasDependentReturnType) {
3679  FunctionDecl *FD = getCurFunctionDecl();
3680 
3681  unsigned DiagID;
3682  if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3683  // C++11 [stmt.return]p2
3684  DiagID = diag::err_constexpr_return_missing_expr;
3685  FD->setInvalidDecl();
3686  } else if (getLangOpts().C99) {
3687  // C99 6.8.6.4p1 (ext_ since GCC warns)
3688  DiagID = diag::ext_return_missing_expr;
3689  } else {
3690  // C90 6.6.6.4p4
3691  DiagID = diag::warn_return_missing_expr;
3692  }
3693 
3694  if (FD)
3695  Diag(ReturnLoc, DiagID)
3696  << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
3697  else
3698  Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3699 
3700  Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3701  /* NRVOCandidate=*/nullptr);
3702  } else {
3703  assert(RetValExp || HasDependentReturnType);
3704  const VarDecl *NRVOCandidate = nullptr;
3705 
3706  QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3707 
3708  // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3709  // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3710  // function return.
3711 
3712  // In C++ the return statement is handled via a copy initialization,
3713  // the C version of which boils down to CheckSingleAssignmentConstraints.
3714  if (RetValExp)
3715  NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3716  if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3717  // we have a non-void function with an expression, continue checking
3719  RetType,
3720  NRVOCandidate != nullptr);
3721  ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3722  RetType, RetValExp);
3723  if (Res.isInvalid()) {
3724  // FIXME: Clean up temporaries here anyway?
3725  return StmtError();
3726  }
3727  RetValExp = Res.getAs<Expr>();
3728 
3729  // If we have a related result type, we need to implicitly
3730  // convert back to the formal result type. We can't pretend to
3731  // initialize the result again --- we might end double-retaining
3732  // --- so instead we initialize a notional temporary.
3733  if (!RelatedRetType.isNull()) {
3734  Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3735  FnRetType);
3736  Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3737  if (Res.isInvalid()) {
3738  // FIXME: Clean up temporaries here anyway?
3739  return StmtError();
3740  }
3741  RetValExp = Res.getAs<Expr>();
3742  }
3743 
3744  CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3745  getCurFunctionDecl());
3746  }
3747 
3748  if (RetValExp) {
3749  ExprResult ER =
3750  ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3751  if (ER.isInvalid())
3752  return StmtError();
3753  RetValExp = ER.get();
3754  }
3755  Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3756  }
3757 
3758  // If we need to check for the named return value optimization, save the
3759  // return statement in our scope for later processing.
3760  if (Result->getNRVOCandidate())
3761  FunctionScopes.back()->Returns.push_back(Result);
3762 
3763  if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3764  FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3765 
3766  return Result;
3767 }
3768 
3769 StmtResult
3771  SourceLocation RParen, Decl *Parm,
3772  Stmt *Body) {
3773  VarDecl *Var = cast_or_null<VarDecl>(Parm);
3774  if (Var && Var->isInvalidDecl())
3775  return StmtError();
3776 
3777  return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3778 }
3779 
3780 StmtResult
3782  return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3783 }
3784 
3785 StmtResult
3787  MultiStmtArg CatchStmts, Stmt *Finally) {
3788  if (!getLangOpts().ObjCExceptions)
3789  Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3790 
3791  setFunctionHasBranchProtectedScope();
3792  unsigned NumCatchStmts = CatchStmts.size();
3793  return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3794  NumCatchStmts, Finally);
3795 }
3796 
3798  if (Throw) {
3799  ExprResult Result = DefaultLvalueConversion(Throw);
3800  if (Result.isInvalid())
3801  return StmtError();
3802 
3803  Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
3804  if (Result.isInvalid())
3805  return StmtError();
3806  Throw = Result.get();
3807 
3808  QualType ThrowType = Throw->getType();
3809  // Make sure the expression type is an ObjC pointer or "void *".
3810  if (!ThrowType->isDependentType() &&
3811  !ThrowType->isObjCObjectPointerType()) {
3812  const PointerType *PT = ThrowType->getAs<PointerType>();
3813  if (!PT || !PT->getPointeeType()->isVoidType())
3814  return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3815  << Throw->getType() << Throw->getSourceRange());
3816  }
3817  }
3818 
3819  return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3820 }
3821 
3822 StmtResult
3824  Scope *CurScope) {
3825  if (!getLangOpts().ObjCExceptions)
3826  Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3827 
3828  if (!Throw) {
3829  // @throw without an expression designates a rethrow (which must occur
3830  // in the context of an @catch clause).
3831  Scope *AtCatchParent = CurScope;
3832  while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3833  AtCatchParent = AtCatchParent->getParent();
3834  if (!AtCatchParent)
3835  return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3836  }
3837  return BuildObjCAtThrowStmt(AtLoc, Throw);
3838 }
3839 
3840 ExprResult
3842  ExprResult result = DefaultLvalueConversion(operand);
3843  if (result.isInvalid())
3844  return ExprError();
3845  operand = result.get();
3846 
3847  // Make sure the expression type is an ObjC pointer or "void *".
3848  QualType type = operand->getType();
3849  if (!type->isDependentType() &&
3850  !type->isObjCObjectPointerType()) {
3851  const PointerType *pointerType = type->getAs<PointerType>();
3852  if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3853  if (getLangOpts().CPlusPlus) {
3854  if (RequireCompleteType(atLoc, type,
3855  diag::err_incomplete_receiver_type))
3856  return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3857  << type << operand->getSourceRange();
3858 
3859  ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3860  if (result.isInvalid())
3861  return ExprError();
3862  if (!result.isUsable())
3863  return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3864  << type << operand->getSourceRange();
3865 
3866  operand = result.get();
3867  } else {
3868  return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3869  << type << operand->getSourceRange();
3870  }
3871  }
3872  }
3873 
3874  // The operand to @synchronized is a full-expression.
3875  return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
3876 }
3877 
3878 StmtResult
3880  Stmt *SyncBody) {
3881  // We can't jump into or indirect-jump out of a @synchronized block.
3882  setFunctionHasBranchProtectedScope();
3883  return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3884 }
3885 
3886 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3887 /// and creates a proper catch handler from them.
3888 StmtResult
3890  Stmt *HandlerBlock) {
3891  // There's nothing to test that ActOnExceptionDecl didn't already test.
3892  return new (Context)
3893  CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3894 }
3895 
3896 StmtResult
3898  setFunctionHasBranchProtectedScope();
3899  return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3900 }
3901 
3902 namespace {
3903 class CatchHandlerType {
3904  QualType QT;
3905  unsigned IsPointer : 1;
3906 
3907  // This is a special constructor to be used only with DenseMapInfo's
3908  // getEmptyKey() and getTombstoneKey() functions.
3909  friend struct llvm::DenseMapInfo<CatchHandlerType>;
3910  enum Unique { ForDenseMap };
3911  CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3912 
3913 public:
3914  /// Used when creating a CatchHandlerType from a handler type; will determine
3915  /// whether the type is a pointer or reference and will strip off the top
3916  /// level pointer and cv-qualifiers.
3917  CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3918  if (QT->isPointerType())
3919  IsPointer = true;
3920 
3921  if (IsPointer || QT->isReferenceType())
3922  QT = QT->getPointeeType();
3923  QT = QT.getUnqualifiedType();
3924  }
3925 
3926  /// Used when creating a CatchHandlerType from a base class type; pretends the
3927  /// type passed in had the pointer qualifier, does not need to get an
3928  /// unqualified type.
3929  CatchHandlerType(QualType QT, bool IsPointer)
3930  : QT(QT), IsPointer(IsPointer) {}
3931 
3932  QualType underlying() const { return QT; }
3933  bool isPointer() const { return IsPointer; }
3934 
3935  friend bool operator==(const CatchHandlerType &LHS,
3936  const CatchHandlerType &RHS) {
3937  // If the pointer qualification does not match, we can return early.
3938  if (LHS.IsPointer != RHS.IsPointer)
3939  return false;
3940  // Otherwise, check the underlying type without cv-qualifiers.
3941  return LHS.QT == RHS.QT;
3942  }
3943 };
3944 } // namespace
3945 
3946 namespace llvm {
3947 template <> struct DenseMapInfo<CatchHandlerType> {
3948  static CatchHandlerType getEmptyKey() {
3949  return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3950  CatchHandlerType::ForDenseMap);
3951  }
3952 
3953  static CatchHandlerType getTombstoneKey() {
3954  return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3955  CatchHandlerType::ForDenseMap);
3956  }
3957 
3958  static unsigned getHashValue(const CatchHandlerType &Base) {
3959  return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3960  }
3961 
3962  static bool isEqual(const CatchHandlerType &LHS,
3963  const CatchHandlerType &RHS) {
3964  return LHS == RHS;
3965  }
3966 };
3967 }
3968 
3969 namespace {
3970 class CatchTypePublicBases {
3971  ASTContext &Ctx;
3972  const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3973  const bool CheckAgainstPointer;
3974 
3975  CXXCatchStmt *FoundHandler;
3976  CanQualType FoundHandlerType;
3977 
3978 public:
3979  CatchTypePublicBases(
3980  ASTContext &Ctx,
3981  const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3982  : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3983  FoundHandler(nullptr) {}
3984 
3985  CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3986  CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3987 
3988  bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3990  CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3991  const auto &M = TypesToCheck;
3992  auto I = M.find(Check);
3993  if (I != M.end()) {
3994  FoundHandler = I->second;
3995  FoundHandlerType = Ctx.getCanonicalType(S->getType());
3996  return true;
3997  }
3998  }
3999  return false;
4000  }
4001 };
4002 }
4003 
4004 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4005 /// handlers and creates a try statement from them.
4007  ArrayRef<Stmt *> Handlers) {
4008  // Don't report an error if 'try' is used in system headers.
4009  if (!getLangOpts().CXXExceptions &&
4010  !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
4011  // Delay error emission for the OpenMP device code.
4012  targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4013  }
4014 
4015  // Exceptions aren't allowed in CUDA device code.
4016  if (getLangOpts().CUDA)
4017  CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4018  << "try" << CurrentCUDATarget();
4019 
4020  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4021  Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4022 
4023  sema::FunctionScopeInfo *FSI = getCurFunction();
4024 
4025  // C++ try is incompatible with SEH __try.
4026  if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4027  Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4028  Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4029  }
4030 
4031  const unsigned NumHandlers = Handlers.size();
4032  assert(!Handlers.empty() &&
4033  "The parser shouldn't call this if there are no handlers.");
4034 
4035  llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4036  for (unsigned i = 0; i < NumHandlers; ++i) {
4037  CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4038 
4039  // Diagnose when the handler is a catch-all handler, but it isn't the last
4040  // handler for the try block. [except.handle]p5. Also, skip exception
4041  // declarations that are invalid, since we can't usefully report on them.
4042  if (!H->getExceptionDecl()) {
4043  if (i < NumHandlers - 1)
4044  return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4045  continue;
4046  } else if (H->getExceptionDecl()->isInvalidDecl())
4047  continue;
4048 
4049  // Walk the type hierarchy to diagnose when this type has already been
4050  // handled (duplication), or cannot be handled (derivation inversion). We
4051  // ignore top-level cv-qualifiers, per [except.handle]p3
4052  CatchHandlerType HandlerCHT =
4053  (QualType)Context.getCanonicalType(H->getCaughtType());
4054 
4055  // We can ignore whether the type is a reference or a pointer; we need the
4056  // underlying declaration type in order to get at the underlying record
4057  // decl, if there is one.
4058  QualType Underlying = HandlerCHT.underlying();
4059  if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4060  if (!RD->hasDefinition())
4061  continue;
4062  // Check that none of the public, unambiguous base classes are in the
4063  // map ([except.handle]p1). Give the base classes the same pointer
4064  // qualification as the original type we are basing off of. This allows
4065  // comparison against the handler type using the same top-level pointer
4066  // as the original type.
4067  CXXBasePaths Paths;
4068  Paths.setOrigin(RD);
4069  CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4070  if (RD->lookupInBases(CTPB, Paths)) {
4071  const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4072  if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4074  diag::warn_exception_caught_by_earlier_handler)
4075  << H->getCaughtType();
4077  diag::note_previous_exception_handler)
4078  << Problem->getCaughtType();
4079  }
4080  }
4081  }
4082 
4083  // Add the type the list of ones we have handled; diagnose if we've already
4084  // handled it.
4085  auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4086  if (!R.second) {
4087  const CXXCatchStmt *Problem = R.first->second;
4089  diag::warn_exception_caught_by_earlier_handler)
4090  << H->getCaughtType();
4092  diag::note_previous_exception_handler)
4093  << Problem->getCaughtType();
4094  }
4095  }
4096 
4097  FSI->setHasCXXTry(TryLoc);
4098 
4099  return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4100 }
4101 
4103  Stmt *TryBlock, Stmt *Handler) {
4104  assert(TryBlock && Handler);
4105 
4106  sema::FunctionScopeInfo *FSI = getCurFunction();
4107 
4108  // SEH __try is incompatible with C++ try. Borland appears to support this,
4109  // however.
4110  if (!getLangOpts().Borland) {
4111  if (FSI->FirstCXXTryLoc.isValid()) {
4112  Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4113  Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4114  }
4115  }
4116 
4117  FSI->setHasSEHTry(TryLoc);
4118 
4119  // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4120  // track if they use SEH.
4121  DeclContext *DC = CurContext;
4122  while (DC && !DC->isFunctionOrMethod())
4123  DC = DC->getParent();
4124  FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4125  if (FD)
4126  FD->setUsesSEHTry(true);
4127  else
4128  Diag(TryLoc, diag::err_seh_try_outside_functions);
4129 
4130  // Reject __try on unsupported targets.
4131  if (!Context.getTargetInfo().isSEHTrySupported())
4132  Diag(TryLoc, diag::err_seh_try_unsupported);
4133 
4134  return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4135 }
4136 
4137 StmtResult
4139  Expr *FilterExpr,
4140  Stmt *Block) {
4141  assert(FilterExpr && Block);
4142 
4143  if(!FilterExpr->getType()->isIntegerType()) {
4144  return StmtError(Diag(FilterExpr->getExprLoc(),
4145  diag::err_filter_expression_integral)
4146  << FilterExpr->getType());
4147  }
4148 
4149  return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
4150 }
4151 
4153  CurrentSEHFinally.push_back(CurScope);
4154 }
4155 
4157  CurrentSEHFinally.pop_back();
4158 }
4159 
4161  assert(Block);
4162  CurrentSEHFinally.pop_back();
4163  return SEHFinallyStmt::Create(Context, Loc, Block);
4164 }
4165 
4166 StmtResult
4168  Scope *SEHTryParent = CurScope;
4169  while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4170  SEHTryParent = SEHTryParent->getParent();
4171  if (!SEHTryParent)
4172  return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4173  CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4174 
4175  return new (Context) SEHLeaveStmt(Loc);
4176 }
4177 
4179  bool IsIfExists,
4180  NestedNameSpecifierLoc QualifierLoc,
4181  DeclarationNameInfo NameInfo,
4182  Stmt *Nested)
4183 {
4184  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4185  QualifierLoc, NameInfo,
4186  cast<CompoundStmt>(Nested));
4187 }
4188 
4189 
4191  bool IsIfExists,
4192  CXXScopeSpec &SS,
4193  UnqualifiedId &Name,
4194  Stmt *Nested) {
4195  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4196  SS.getWithLocInContext(Context),
4197  GetNameFromUnqualifiedId(Name),
4198  Nested);
4199 }
4200 
4201 RecordDecl*
4203  unsigned NumParams) {
4204  DeclContext *DC = CurContext;
4205  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4206  DC = DC->getParent();
4207 
4208  RecordDecl *RD = nullptr;
4209  if (getLangOpts().CPlusPlus)
4210  RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4211  /*Id=*/nullptr);
4212  else
4213  RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4214 
4215  RD->setCapturedRecord();
4216  DC->addDecl(RD);
4217  RD->setImplicit();
4218  RD->startDefinition();
4219 
4220  assert(NumParams > 0 && "CapturedStmt requires context parameter");
4221  CD = CapturedDecl::Create(Context, CurContext, NumParams);
4222  DC->addDecl(CD);
4223  return RD;
4224 }
4225 
4226 static bool
4229  SmallVectorImpl<Expr *> &CaptureInits) {
4230  for (const sema::Capture &Cap : RSI->Captures) {
4231  if (Cap.isInvalid())
4232  continue;
4233 
4234  // Form the initializer for the capture.
4235  ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4236  RSI->CapRegionKind == CR_OpenMP);
4237 
4238  // FIXME: Bail out now if the capture is not used and the initializer has
4239  // no side-effects.
4240 
4241  // Create a field for this capture.
4242  FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4243 
4244  // Add the capture to our list of captures.
4245  if (Cap.isThisCapture()) {
4246  Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4248  } else if (Cap.isVLATypeCapture()) {
4249  Captures.push_back(
4251  } else {
4252  assert(Cap.isVariableCapture() && "unknown kind of capture");
4253 
4254  if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4255  S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
4256 
4257  Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4258  Cap.isReferenceCapture()
4261  Cap.getVariable()));
4262  }
4263  CaptureInits.push_back(Init.get());
4264  }
4265  return false;
4266 }
4267 
4270  unsigned NumParams) {
4271  CapturedDecl *CD = nullptr;
4272  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4273 
4274  // Build the context parameter
4276  IdentifierInfo *ParamName = &Context.Idents.get("__context");
4277  QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4278  auto *Param =
4279  ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4281  DC->addDecl(Param);
4282 
4283  CD->setContextParam(0, Param);
4284 
4285  // Enter the capturing scope for this captured region.
4286  PushCapturedRegionScope(CurScope, CD, RD, Kind);
4287 
4288  if (CurScope)
4289  PushDeclContext(CurScope, CD);
4290  else
4291  CurContext = CD;
4292 
4293  PushExpressionEvaluationContext(
4294  ExpressionEvaluationContext::PotentiallyEvaluated);
4295 }
4296 
4300  CapturedDecl *CD = nullptr;
4301  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4302 
4303  // Build the context parameter
4305  bool ContextIsFound = false;
4306  unsigned ParamNum = 0;
4307  for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4308  E = Params.end();
4309  I != E; ++I, ++ParamNum) {
4310  if (I->second.isNull()) {
4311  assert(!ContextIsFound &&
4312  "null type has been found already for '__context' parameter");
4313  IdentifierInfo *ParamName = &Context.Idents.get("__context");
4314  QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4315  .withConst()
4316  .withRestrict();
4317  auto *Param =
4318  ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4320  DC->addDecl(Param);
4321  CD->setContextParam(ParamNum, Param);
4322  ContextIsFound = true;
4323  } else {
4324  IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4325  auto *Param =
4326  ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4328  DC->addDecl(Param);
4329  CD->setParam(ParamNum, Param);
4330  }
4331  }
4332  assert(ContextIsFound && "no null type for '__context' parameter");
4333  if (!ContextIsFound) {
4334  // Add __context implicitly if it is not specified.
4335  IdentifierInfo *ParamName = &Context.Idents.get("__context");
4336  QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4337  auto *Param =
4338  ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4340  DC->addDecl(Param);
4341  CD->setContextParam(ParamNum, Param);
4342  }
4343  // Enter the capturing scope for this captured region.
4344  PushCapturedRegionScope(CurScope, CD, RD, Kind);
4345 
4346  if (CurScope)
4347  PushDeclContext(CurScope, CD);
4348  else
4349  CurContext = CD;
4350 
4351  PushExpressionEvaluationContext(
4352  ExpressionEvaluationContext::PotentiallyEvaluated);
4353 }
4354 
4356  DiscardCleanupsInEvaluationContext();
4357  PopExpressionEvaluationContext();
4358  PopDeclContext();
4359  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4360  CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4361 
4362  RecordDecl *Record = RSI->TheRecordDecl;
4363  Record->setInvalidDecl();
4364 
4365  SmallVector<Decl*, 4> Fields(Record->fields());
4366  ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4368 }
4369 
4371  // Leave the captured scope before we start creating captures in the
4372  // enclosing scope.
4373  DiscardCleanupsInEvaluationContext();
4374  PopExpressionEvaluationContext();
4375  PopDeclContext();
4376  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4377  CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4378 
4380  SmallVector<Expr *, 4> CaptureInits;
4381  if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4382  return StmtError();
4383 
4384  CapturedDecl *CD = RSI->TheCapturedDecl;
4385  RecordDecl *RD = RSI->TheRecordDecl;
4386 
4388  getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4389  Captures, CaptureInits, CD, RD);
4390 
4391  CD->setBody(Res->getCapturedStmt());
4392  RD->completeDefinition();
4393 
4394  return Res;
4395 }
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:77
Defines the clang::ASTContext interface.
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it&#39;s either not been deduced or was deduce...
Definition: Type.h:4803
QualType withConst() const
Retrieves a version of this type with const applied.
void setImplicit(bool I=true)
Definition: DeclBase.h:559
Represents a function declaration or definition.
Definition: Decl.h:1748
Stmt * body_back()
Definition: Stmt.h:1348
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.
void setOrigin(CXXRecordDecl *Rec)
bool isClosedNonFlag() const
Returns true if this enum is annotated with neither flag_enum nor enum_extensibility(open).
Definition: Decl.cpp:4177
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1854
PtrTy get() const
Definition: Ownership.h:80
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2569
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
QualType getPointeeType() const
Definition: Type.h:2582
CanQualType VoidPtrTy
Definition: ASTContext.h:1042
A (possibly-)qualified type.
Definition: Type.h:643
bool isBlockPointerType() const
Definition: Type.h:6392
static void TryMoveInitialization(Sema &S, const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *&Value, bool ConvertingConstructorsOnly, ExprResult &Res)
Try to perform the initialization of a potentially-movable value, which is the operand to a return or...
Definition: SemaStmt.cpp:3000
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2132
bool isArrayType() const
Definition: Type.h:6440
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:47
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2403
Instantiation or recovery rebuild of a for-range statement.
Definition: Sema.h:3972
SourceLocation getExprLoc() const
Definition: Expr.h:3436
static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned)
Definition: SemaStmt.cpp:718
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams)
Definition: SemaStmt.cpp:4268
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock)
ActOnCXXCatchBlock - Takes an exception declaration and a handler block and creates a proper catch ha...
Definition: SemaStmt.cpp:3889
bool operator==(CanQual< T > x, CanQual< U > y)
static unsigned getHashValue(const CatchHandlerType &Base)
Definition: SemaStmt.cpp:3958
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Definition: Dominators.h:30
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
Stmt - This represents one statement.
Definition: Stmt.h:66
static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVarDecl, SourceLocation ColonLoc, Expr *Range, SourceLocation RangeLoc, SourceLocation RParenLoc)
Speculatively attempt to dereference an invalid range expression.
Definition: SemaStmt.cpp:2266
VarDecl * getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK)
Determine whether the given expression is a candidate for copy elision in either a return statement o...
Definition: SemaStmt.cpp:2923
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3387
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt *> Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:350
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:658
void setParam(unsigned i, ImplicitParamDecl *P)
Definition: Decl.h:4159
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc)
Definition: SemaStmt.cpp:1865
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2108
bool isRecordType() const
Definition: Type.h:6464
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond)
Definition: SemaStmt.cpp:689
Expr * getBase() const
Definition: Expr.h:2884
SmallVector< Scope *, 2 > CurrentSEHFinally
Stack of active SEH __finally scopes. Can be empty.
Definition: Sema.h:403
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
bool isDecltypeAuto() const
Definition: Type.h:4828
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1362
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
void setType(QualType t)
Definition: Expr.h:138
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:9872
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
Opcode getOpcode() const
Definition: Expr.h:3440
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4817
Represents an attribute applied to a statement.
Definition: Stmt.h:1754
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1964
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6333
The base class of the type hierarchy.
Definition: Type.h:1433
Represents Objective-C&#39;s @throw statement.
Definition: StmtObjC.h:332
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2844
ForRangeStatus
Definition: Sema.h:3123
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1331
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1229
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body)
Definition: SemaStmt.cpp:3770
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4310
QualType withConst() const
Definition: Type.h:815
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:693
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3653
A container of type source information.
Definition: Decl.h:86
Wrapper for void* pointer.
Definition: Ownership.h:50
static AttributedStmt * Create(const ASTContext &C, SourceLocation Loc, ArrayRef< const Attr *> Attrs, Stmt *SubStmt)
Definition: Stmt.cpp:344
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope)
Definition: SemaStmt.cpp:2878
Scope * getContinueParent()
getContinueParent - Return the closest scope that a continue statement would be affected by...
Definition: Scope.h:242
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition: Scope.h:266
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4325
Determining whether a for-range statement could be built.
Definition: Sema.h:3975
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3202
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition: SemaStmt.cpp:386
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:97
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen)
Definition: SemaStmt.cpp:1299
This file provides some common utility functions for processing Lambda related AST Constructs...
enumerator_range enumerators() const
Definition: Decl.h:3486
Represents a variable declaration or definition.
Definition: Decl.h:812
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:264
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
const VarDecl * getNRVOCandidate() const
Retrieve the variable that might be used for the named return value optimization. ...
Definition: Stmt.h:2652
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally)
Definition: SemaStmt.cpp:3786
QualType getReturnType() const
Definition: Decl.h:2329
DiagnosticsEngine & Diags
Definition: Sema.h:376
bool isEnumeralType() const
Definition: Type.h:6468
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6851
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl)
Definition: SemaStmt.cpp:82
static bool ObjCEnumerationCollection(Expr *Collection)
Definition: SemaStmt.cpp:2033
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1240
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1001
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
bool isAmbiguous() const
Definition: Lookup.h:301
bool isInvalidDecl() const
Definition: DeclBase.h:553
static InitializedEntity InitializeResult(SourceLocation ReturnLoc, QualType Type, bool NRVO)
Create the initialization entity for the result of a function.
Defines the Objective-C statement AST node classes.
EntityKind getKind() const
Determine the kind of initialization.
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body)
FinishObjCForCollectionStmt - Attach the body to a objective-C foreach statement. ...
Definition: SemaStmt.cpp:2649
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
Definition: SemaExpr.cpp:13357
llvm::PointerIntPair< SwitchStmt *, 1, bool > SwitchInfo
A SwitchStmt, along with a flag indicating if its list of case statements is incomplete (because we d...
Definition: ScopeInfo.h:181
Represents a parameter to a function.
Definition: Decl.h:1564
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isUnset() const
Definition: Ownership.h:168
long i
Definition: xmmintrin.h:1456
CapturedDecl * TheCapturedDecl
The CapturedDecl for this statement.
Definition: ScopeInfo.h:744
static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val, unsigned UnpromotedWidth, bool UnpromotedSign)
Check the specified case value is in range for the given unpromoted switch type.
Definition: SemaStmt.cpp:725
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1710
Represents a struct/union/class.
Definition: Decl.h:3626
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc)
Definition: SemaStmt.cpp:437
One of these records is kept for each identifier that is lexed.
bool isAtCatchScope() const
isAtCatchScope - Return true if this scope is @catch.
Definition: Scope.h:389
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4366
Expr * getFalseExpr() const
Definition: Expr.h:3746
Step
Definition: OpenMPClause.h:151
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:199
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition: SemaStmt.cpp:45
Represents a class type in Objective C.
Definition: Type.h:5608
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4263
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition: Stmt.h:2134
ObjCMethodDecl * lookupInstanceMethod(Selector Sel) const
Lookup an instance method for a given selector.
Definition: DeclObjC.h:1846
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
A C++ nested-name-specifier augmented with source location information.
QualType getCaughtType() const
Definition: StmtCXX.cpp:19
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:920
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:263
Represents a member of a struct/union/class.
Definition: Decl.h:2607
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind)
ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Definition: SemaStmt.cpp:2056
void setLocStart(SourceLocation L)
Definition: Decl.h:496
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection)
Definition: SemaStmt.cpp:1790
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4030
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4178
bool isReferenceType() const
Definition: Type.h:6396
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:552
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c-base.h:40
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1103
bool isInvalid() const
Definition: Sema.h:10264
void setNoNRVO()
Definition: Scope.h:483
std::pair< VarDecl *, Expr * > get() const
Definition: Sema.h:10265
Expr * getSubExpr()
Definition: Expr.h:3173
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:738
bool isGnuLocal() const
Definition: Decl.h:495
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6747
Scope * getBreakParent()
getBreakParent - Return the closest scope that a break statement would be affected by...
Definition: Scope.h:252
IdentifierTable & Idents
Definition: ASTContext.h:569
SourceLocation FirstSEHTryLoc
First SEH &#39;__try&#39; statement in the current function.
Definition: ScopeInfo.h:174
void ActOnAbortSEHFinallyBlock()
Definition: SemaStmt.cpp:4156
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6161
void setARCPseudoStrong(bool PS)
Definition: Decl.h:1365
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:124
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef< const Attr *> Attrs, Stmt *SubStmt)
Definition: SemaStmt.cpp:503
static bool buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI, SmallVectorImpl< CapturedStmt::Capture > &Captures, SmallVectorImpl< Expr *> &CaptureInits)
Definition: SemaStmt.cpp:4227
Represents Objective-C&#39;s @catch statement.
Definition: StmtObjC.h:77
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested)
Definition: SemaStmt.cpp:4178
IndirectGotoStmt - This represents an indirect goto.
Definition: Stmt.h:2494
static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange, QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar, SourceLocation ColonLoc, SourceLocation CoawaitLoc, OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr, ExprResult *EndExpr, BeginEndFunction *BEF)
Create the initialization, compare, and increment steps for the range-based for loop expression...
Definition: SemaStmt.cpp:2132
static CapturedStmt * Create(const ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef< Capture > Captures, ArrayRef< Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD)
Definition: Stmt.cpp:1230
bool isThisCapture() const
Definition: ScopeInfo.h:578
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:944
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2770
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
ForStmt - This represents a &#39;for (init;cond;inc)&#39; stmt.
Definition: Stmt.h:2384
Represents the results of name lookup.
Definition: Lookup.h:46
PtrTy get() const
Definition: Ownership.h:170
static IfStmt * Create(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL=SourceLocation(), Stmt *Else=nullptr)
Create an IfStmt.
Definition: Stmt.cpp:852
Decl * getSingleDecl()
Definition: DeclGroup.h:83
This is a scope that corresponds to a switch statement.
Definition: Scope.h:98
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:582
void ActOnStartSEHFinallyBlock()
Definition: SemaStmt.cpp:4152
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:272
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2236
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6902
Parameter for captured context.
Definition: Decl.h:1521
SourceLocation getRParenLoc() const
Definition: StmtCXX.h:204
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:133
static CaseStmt * Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc)
Build a case statement.
Definition: Stmt.cpp:1091
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
RecordDecl * CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams)
Definition: SemaStmt.cpp:4202
StmtResult StmtError()
Definition: Ownership.h:280
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3405
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6212
Stmt * getInit()
Definition: Stmt.h:2397
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:307
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope)
Definition: SemaStmt.cpp:2890
CXXForRangeStmt - This represents C++0x [stmt.ranged]&#39;s ranged for statement, represented as &#39;for (ra...
Definition: StmtCXX.h:134
SmallVector< std::pair< llvm::APSInt, EnumConstantDecl * >, 64 > EnumValsTy
Definition: SemaStmt.cpp:747
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
Definition: SemaStmt.cpp:2834
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2947
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond, const Expr *Case)
Definition: SemaStmt.cpp:783
bool isNull() const
Definition: DeclGroup.h:79
CaseStmt - Represent a case statement.
Definition: Stmt.h:1478
SourceLocation getContinueLoc() const
Definition: Stmt.h:2552
bool isInt() const
Definition: APValue.h:317
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3121
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:17110
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:625
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1282
Preprocessor & PP
Definition: Sema.h:373
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1952
const LangOptions & getLangOpts() const
Definition: Sema.h:1285
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:919
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
static CatchHandlerType getTombstoneKey()
Definition: SemaStmt.cpp:3953
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block)
Definition: SemaStmt.cpp:4160
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope)
Definition: SemaStmt.cpp:4167
Perform initialization via a constructor.
Perform a user-defined conversion, either via a conversion function or via a constructor.
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to &#39;begin&#39; or &#39;end&#39; for a C++11 for-range statement.
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4108
Represents an ObjC class declaration.
Definition: DeclObjC.h:1171
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3232
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5843
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1799
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:142
Stmt * getBody()
Definition: Stmt.h:2089
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope)
Definition: SemaStmt.cpp:3823
void setStmt(LabelStmt *T)
Definition: Decl.h:493
static SEHTryStmt * Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: Stmt.cpp:1118
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2926
bool isSEHTrySupported() const
Whether the target supports SEH __try.
Definition: TargetInfo.h:1189
Contains information about the compound statement currently being parsed.
Definition: ScopeInfo.h:67
SourceLocation FirstCXXTryLoc
First C++ &#39;try&#39; statement in the current function.
Definition: ScopeInfo.h:171
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3536
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:7856
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:4561
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:220
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
bool hasAttr() const
Definition: DeclBase.h:542
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3703
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:328
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1045
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:72
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1310
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1636
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3719
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:16534
Describes the capture of either a variable, or &#39;this&#39;, or variable-length array type.
Definition: Stmt.h:3363
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3384
Retains information about a captured region.
Definition: ScopeInfo.h:741
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:5948
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1975
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
Definition: SemaStmt.cpp:3528
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: StmtCXX.h:43
SourceLocation getLocation() const
Definition: Expr.h:1225
void ActOnFinishOfCompoundStmt()
Definition: SemaStmt.cpp:342
bool isClosed() const
Returns true if this enum is either annotated with enum_extensibility(closed) or isn&#39;t annotated with...
Definition: Decl.cpp:4167
QualType getAutoRRefDeductType() const
C++11 deduction pattern for &#39;auto &&&#39; type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body)
Definition: SemaStmt.cpp:3781
Scope * getCurScope() const
Retrieve the parser&#39;s current scope.
Definition: Sema.h:11132
bool isVariableCapture() const
Definition: ScopeInfo.h:579
bool isConsteval() const
Definition: Decl.h:2120
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:189
Allows QualTypes to be sorted and hence used in maps and sets.
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:715
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:795
Expr * getCond() const
Definition: Expr.h:3737
bool isInvalid() const
Definition: ScopeInfo.h:590
This represents one expression.
Definition: Expr.h:108
QualType getPointeeType() const
Definition: Type.h:2726
DeclStmt * getEndStmt()
Definition: StmtCXX.h:165
SourceLocation End
Allow any unmodeled side effect.
Definition: Expr.h:609
std::string Label
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1035
SourceLocation getDefaultLoc() const
Definition: Stmt.h:1649
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
Definition: SemaStmt.cpp:3392
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition: SemaStmt.cpp:467
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6916
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
void setInit(Expr *I)
Definition: Decl.cpp:2239
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:49
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:131
std::string getAsString() const
Retrieve the human-readable string for this name.
static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef, const VarDecl *VD)
Definition: SemaStmt.cpp:2739
bool isExceptionVariable() const
Determine whether this variable is the exception variable in a C++ catch statememt or an Objective-C ...
Definition: Decl.h:1311
void setContextParam(unsigned i, ImplicitParamDecl *P)
Definition: Decl.h:4177
bool isSEHTryScope() const
Determine whether this scope is a SEH &#39;__try&#39; block.
Definition: Scope.h:440
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3552
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Defines the clang::Preprocessor interface.
ObjCLifetime getObjCLifetime() const
Definition: Type.h:327
bool isFileContext() const
Definition: DeclBase.h:1849
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Expr * getRHS()
Definition: Stmt.h:1579
void setBody(Stmt *Body)
Definition: Stmt.h:2094
The entity being initialized is an exception object that is being thrown.
Represents Objective-C&#39;s @synchronized statement.
Definition: StmtObjC.h:277
SourceLocation Begin
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2652
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1347
void removeLocalConst()
Definition: Type.h:6236
Defines the clang::TypeLoc interface and its subclasses.
static DeclContext * castToDeclContext(const CapturedDecl *D)
Definition: Decl.h:4195
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:2209
QualType getType() const
Definition: Expr.h:137
bool isFunctionOrMethod() const
Definition: DeclBase.h:1831
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:4610
static bool isEqual(const CatchHandlerType &LHS, const CatchHandlerType &RHS)
Definition: SemaStmt.cpp:3962
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1779
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2610
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition: SemaStmt.cpp:67
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:950
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2146
bool isInvalid() const
Definition: Ownership.h:166
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:2016
void setLocation(SourceLocation L)
Definition: DeclBase.h:430
static WhileStmt * Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body, SourceLocation WL)
Create a while statement.
Definition: Stmt.cpp:1016
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1082
void setHasCXXTry(SourceLocation TryLoc)
Definition: ScopeInfo.h:420
ValueDecl * getDecl()
Definition: Expr.h:1217
bool isUsable() const
Definition: Ownership.h:167
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2899
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1398
const Expr * getSubExpr() const
Definition: Expr.h:1980
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:756
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:615
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Definition: Expr.h:3342
llvm::iterator_range< semantics_iterator > semantics()
Definition: Expr.h:5744
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:708
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level)
Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) for FD based on DSA for the...
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2317
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition: Scope.h:454
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1632
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:276
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:123
static SEHFinallyStmt * Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block)
Definition: Stmt.cpp:1146
DoStmt - This represents a &#39;do/while&#39; stmt.
Definition: Stmt.h:2328
void setBody(Stmt *S)
Definition: StmtCXX.h:199
BuildForRangeKind
Definition: Sema.h:3967
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6201
RecordDecl * getDecl() const
Definition: Type.h:4448
static CatchHandlerType getEmptyKey()
Definition: SemaStmt.cpp:3948
static SwitchStmt * Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond)
Create a switch statement.
Definition: Stmt.cpp:958
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:1045
The "struct" keyword.
Definition: Type.h:5103
SelectorTable & Selectors
Definition: ASTContext.h:570
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:165
Kind
This captures a statement into a function.
Definition: Stmt.h:3350
static bool EqEnumVals(const std::pair< llvm::APSInt, EnumConstantDecl *> &lhs, const std::pair< llvm::APSInt, EnumConstantDecl *> &rhs)
EqEnumVals - Comparison preficate for uniqing enumeration values.
Definition: SemaStmt.cpp:607
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5663
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: StmtCXX.h:206
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt)
ActOnCaseStmtBody - This installs a statement as the body of a case.
Definition: SemaStmt.cpp:462
VarDecl * getVariable() const
Definition: ScopeInfo.h:604
void setHasSEHTry(SourceLocation TryLoc)
Definition: ScopeInfo.h:425
bool isOpenMPLoopScope() const
Determine whether this scope is a loop having OpenMP loop directive attached.
Definition: Scope.h:431
DeduceAutoResult
Result type of DeduceAutoType.
Definition: Sema.h:7370
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3645
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4464
Expr * getSubExpr() const
Definition: Expr.h:2046
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
Definition: SemaStmt.cpp:1223
CastKind getCastKind() const
Definition: Expr.h:3167
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:12431
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope)
Definition: SemaStmt.cpp:3504
Expr * getLHS()
Definition: Stmt.h:1567
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition: SemaStmt.cpp:480
StmtResult ActOnForEachLValueExpr(Expr *E)
In an Objective C collection iteration statement: for (x in y) x can be an arbitrary l-value expressi...
Definition: SemaStmt.cpp:1776
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:170
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1203
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:910
Represents the declaration of a label.
Definition: Decl.h:468
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
StmtResult ActOnCapturedRegionEnd(Stmt *S)
Definition: SemaStmt.cpp:4370
Expr * getCond()
Definition: Stmt.h:2077
void setAllEnumCasesCovered()
Set a flag in the SwitchStmt indicating that if the &#39;switch (X)&#39; is a switch over an enum value then ...
Definition: Stmt.h:2167
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec.auto]p6.
Definition: SemaStmt.cpp:3401
static QualType GetTypeBeforeIntegralPromotion(const Expr *&E)
GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of potentially integral-promoted expr...
Definition: SemaStmt.cpp:615
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw)
Definition: SemaStmt.cpp:3797
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef< Stmt *> Handlers)
ActOnCXXTryBlock - Takes a try compound-statement and a number of handlers and creates a try statemen...
Definition: SemaStmt.cpp:4006
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2312
bool isVLATypeCapture() const
Definition: ScopeInfo.h:586
StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
Definition: SemaStmt.cpp:4138
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1891
CanQualType VoidTy
Definition: ASTContext.h:1014
Describes the kind of initialization being performed, along with location information for tokens rela...
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:134
bool isObjCObjectPointerType() const
Definition: Type.h:6488
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:650
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body)
Definition: SemaStmt.cpp:810
bool isMSAsmLabel() const
Definition: Decl.h:502
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3245
Stmt * getCapturedStmt()
Retrieve the statement being captured.
Definition: Stmt.h:3451
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:258
sema::CompoundScopeInfo & getCurCompoundScope() const
Definition: SemaStmt.cpp:346
Requests that all candidates be shown.
Definition: Overload.h:68
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1992
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body)
Definition: SemaStmt.cpp:1279
EnumDecl * getDecl() const
Definition: Type.h:4471
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1392
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:846
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody)
Definition: SemaStmt.cpp:3879
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2320
Representation of a Microsoft __if_exists or __if_not_exists statement with a dependent name...
Definition: StmtCXX.h:252
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef, const VarDecl *VD, QualType RangeInitType)
Definition: SemaStmt.cpp:2665
Expr * getLHS() const
Definition: Expr.h:3445
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: Expr.h:3819
LabelStmt * getStmt() const
Definition: Decl.h:492
void setCapturedRecord()
Mark the record as a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:4297
bool isDeduced() const
Definition: Type.h:4806
QualType withRestrict() const
Definition: Type.h:831
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:3835
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1275
Dataflow Directional Tag Classes.
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body)
Definition: SemaStmt.cpp:3897
bool isValid() const
Return true if this is a valid SourceLocation object.
ObjCMethodDecl * lookupPrivateMethod(const Selector &Sel, bool Instance=true) const
Lookup a method in the classes implementation hierarchy.
Definition: DeclObjC.cpp:739
A single step in the initialization sequence.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:580
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:228
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:130
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:1726
void ActOnCapturedRegionError()
Definition: SemaStmt.cpp:4355
bool isRecord() const
Definition: DeclBase.h:1858
void addNRVOCandidate(VarDecl *VD)
Definition: Scope.h:472
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1075
StmtResult ActOnExprStmtError()
Definition: SemaStmt.cpp:62
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
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp)
Definition: SemaStmt.cpp:2843
Kind getKind() const
Definition: DeclBase.h:432
bool isSingleDecl() const
Definition: DeclGroup.h:80
static void DiagnoseForRangeVariableCopies(Sema &SemaRef, const CXXForRangeStmt *ForStmt)
DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
Definition: SemaStmt.cpp:2780
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5905
Represents an enum.
Definition: Decl.h:3359
const Decl * getSingleDecl() const
Definition: Stmt.h:1218
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
Expr * get() const
Definition: Sema.h:3844
ConstEvaluatedExprVisitor - This class visits &#39;const Expr *&#39;s.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl. ...
Definition: Stmt.h:1216
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:11365
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 &#39;auto&#39; typ...
Definition: Type.h:6766
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2942
bool isMacroID() const
Represents a __leave statement.
Definition: Stmt.h:3311
Represents a pointer to an Objective C object.
Definition: Type.h:5864
SwitchStmt - This represents a &#39;switch&#39; stmt.
Definition: Stmt.h:2017
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
Definition: SemaStmt.cpp:4190
unsigned getIntWidth(QualType T) const
RecordDecl * TheRecordDecl
The captured record type.
Definition: ScopeInfo.h:747
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4438
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind)
BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Definition: SemaStmt.cpp:2319
bool body_empty() const
Definition: Stmt.h:1337
Represents Objective-C&#39;s collection statement.
Definition: StmtObjC.h:23
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6677
T * getAttr() const
Definition: DeclBase.h:538
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
bool isReferenceCapture() const
Definition: ScopeInfo.h:584
CanQualType DependentTy
Definition: ASTContext.h:1043
static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S, const EnumDecl *ED, const Expr *CaseExpr, EnumValsTy::iterator &EI, EnumValsTy::iterator &EIEnd, const llvm::APSInt &Val)
Returns true if we should emit a diagnostic about this case expression not being a part of the enum u...
Definition: SemaStmt.cpp:751
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:715
Stmt * getInit()
Definition: Stmt.h:2098
void setUsesSEHTry(bool UST)
Definition: Decl.h:2142
static bool CmpEnumVals(const std::pair< llvm::APSInt, EnumConstantDecl *> &lhs, const std::pair< llvm::APSInt, EnumConstantDecl *> &rhs)
CmpEnumVals - Comparison predicate for sorting enumeration values.
Definition: SemaStmt.cpp:599
Opcode getOpcode() const
Definition: Expr.h:2041
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2296
QualType getAutoDeductType() const
C++11 deduction pattern for &#39;auto&#39; type.
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional< unsigned > DependentDeductionDepth=None)
Represents Objective-C&#39;s @finally statement.
Definition: StmtObjC.h:127
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
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1514
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
static bool DiagnoseUnusedComparison(Sema &S, const Expr *E)
Diagnose unused comparisons, both builtin and overloaded operators.
Definition: SemaStmt.cpp:128
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition: SemaStmt.cpp:338
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr *> Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:412
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2062
DeclStmt * getRangeStmt()
Definition: StmtCXX.h:161
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2280
GotoStmt - This represents a direct goto.
Definition: Stmt.h:2455
bool isLValueReferenceType() const
Definition: Type.h:6400
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:240
static bool CmpCaseVals(const std::pair< llvm::APSInt, CaseStmt *> &lhs, const std::pair< llvm::APSInt, CaseStmt *> &rhs)
CmpCaseVals - Comparison predicate for sorting case values.
Definition: SemaStmt.cpp:585
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1453
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO=true)
Perform the initialization of a potentially-movable value, which is the result of return value...
Definition: SemaStmt.cpp:3079
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2807
static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, QualType Type)
Create the initialization entity for a related result.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:263
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6222
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3307
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
ActOnCapScopeReturnStmt - Utility routine to type-check return statements for capturing scopes...
Definition: SemaStmt.cpp:3196
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
ContinueStmt - This represents a continue.
Definition: Stmt.h:2543
Expr * getTrueExpr() const
Definition: Expr.h:3741
bool isVoidType() const
Definition: Type.h:6643
static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, SourceLocation Loc, int DiagID)
Finish building a variable declaration for a for-range statement.
Definition: SemaStmt.cpp:1948
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, Stmt *tryBlock, ArrayRef< Stmt *> handlers)
Definition: StmtCXX.cpp:25
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3776
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
VarDecl * getLoopVariable()
Definition: StmtCXX.cpp:76
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr.type.conv]).
Definition: ExprCXX.h:1597
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1488
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:2200
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:1432
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:386
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
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
SourceLocation getBreakLoc() const
Definition: Stmt.h:2582
bool qual_empty() const
Definition: Type.h:5512
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:251
__DEVICE__ int min(int __a, int __b)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11687
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2516
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body)
FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
Definition: SemaStmt.cpp:2816
ExprResult ExprError()
Definition: Ownership.h:279
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand)
Definition: SemaStmt.cpp:3841
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2108
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1141
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:821
result[0]
Definition: emmintrin.h:120
Expr * getRHS() const
Definition: Expr.h:3447
bool isPointerType() const
Definition: Type.h:6384
BreakStmt - This represents a break.
Definition: Stmt.h:2573
SourceManager & SourceMgr
Definition: Sema.h:377
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:16
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK)
Definition: SemaStmt.cpp:2939
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1104
QualType getType() const
Definition: Decl.h:647
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:128
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
static bool hasDeducedReturnType(FunctionDecl *FD)
Determine whether the declared return type of the specified function contains &#39;auto&#39;.
Definition: SemaStmt.cpp:3186
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:374
This represents a decl that may have a name.
Definition: Decl.h:248
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:554
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:75
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3003
CanQualType BoolTy
Definition: ASTContext.h:1015
APSInt & getInt()
Definition: APValue.h:336
DeclStmt * getBeginStmt()
Definition: StmtCXX.h:162
Describes an entity that is being initialized.
BeginEndFunction
Definition: SemaStmt.cpp:1988
ExprResult release()
Definition: Sema.h:3840
Decl * getCalleeDecl()
Definition: Expr.h:2646
void setType(QualType newType)
Definition: Decl.h:648
Wrapper for source info for pointers.
Definition: TypeLoc.h:1237
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:526
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:107
Represents Objective-C&#39;s @autoreleasepool Statement.
Definition: StmtObjC.h:368
CopyElisionSemanticsKind
Definition: Sema.h:4017
static SEHExceptStmt * Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block)
Definition: Stmt.cpp:1138
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2904
Declaration of a template function.
static ObjCAtTryStmt * Create(const ASTContext &Context, SourceLocation atTryLoc, Stmt *atTryStmt, Stmt **CatchStmts, unsigned NumCatchStmts, Stmt *atFinallyStmt)
Definition: StmtObjC.cpp:45
void setBody(Stmt *B)
Definition: Decl.cpp:4623
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:429
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
StmtResult ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: SemaStmt.cpp:4102
static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc, const Scope &DestScope)
Definition: SemaStmt.cpp:2869
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1315
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2938
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:291