1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
41 using namespace clang;
44 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
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.
57 // Same thing in for stmt first clause (when expr) and third clause.
58 return StmtResult(FE.getAs<Stmt>());
62 StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
67 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
68 bool HasLeadingEmptyMacro) {
69 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
72 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
74 DeclGroupRef DG = dg.get();
76 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
79 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
82 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
83 DeclGroupRef DG = dg.get();
85 // If we don't have a declaration, or we have an invalid declaration,
87 if (DG.isNull() || !DG.isSingleDecl())
90 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
104 var->setInit(nullptr);
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();
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.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
123 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124 /// For '==' and '!=', suggest fixits for '=' or '|='.
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) {
131 enum { Equality, Inequality, Relational, ThreeWay } Kind;
133 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
134 if (!Op->isComparisonOp())
137 if (Op->getOpcode() == BO_EQ)
139 else if (Op->getOpcode() == BO_NE)
141 else if (Op->getOpcode() == BO_Cmp)
144 assert(Op->isRelationalOp());
147 Loc = Op->getOperatorLoc();
148 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
149 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
150 switch (Op->getOperator()) {
154 case OO_ExclaimEqual:
159 case OO_GreaterEqual:
170 Loc = Op->getOperatorLoc();
171 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
173 // Not a typo-prone comparison.
177 // Suppress warnings when the operator, suspicious as it may be, comes from
178 // a macro expansion.
179 if (S.SourceMgr.isMacroBodyExpansion(Loc))
182 S.Diag(Loc, diag::warn_unused_comparison)
183 << (unsigned)Kind << E->getSourceRange();
185 // If the LHS is a plausible entity to assign to, provide a fixit hint to
186 // correct common typos.
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, "=");
199 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
200 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
201 return DiagnoseUnusedExprResult(Label->getSubStmt());
203 const Expr *E = dyn_cast_or_null<Expr>(S);
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())
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);
222 const Expr *WarnExpr;
225 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
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
232 if (isa<StmtExpr>(E) && Loc.isMacroID())
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"))
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
247 unsigned DiagID = diag::warn_unused_expr;
248 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
249 E = Temps->getSubExpr();
250 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
251 E = TempExpr->getSubExpr();
253 if (DiagnoseUnusedComparison(*this, E))
257 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
258 if (E->getType()->isVoidType())
261 // If the callee has attribute pure, const, or warn_unused_result, warn with
262 // a more specific message to make it clear what is happening. If the call
263 // is written in a macro body, only warn if it has the warn_unused_result
265 if (const Decl *FD = CE->getCalleeDecl()) {
266 if (const Attr *A = isa<FunctionDecl>(FD)
267 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
268 : FD->getAttr<WarnUnusedResultAttr>()) {
269 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
274 if (FD->hasAttr<PureAttr>()) {
275 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
278 if (FD->hasAttr<ConstAttr>()) {
279 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
283 } else if (ShouldSuppress)
286 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
287 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
288 Diag(Loc, diag::err_arc_unused_init_message) << R1;
291 const ObjCMethodDecl *MD = ME->getMethodDecl();
293 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
294 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
298 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
299 const Expr *Source = POE->getSyntacticForm();
300 if (isa<ObjCSubscriptRefExpr>(Source))
301 DiagID = diag::warn_unused_container_subscript_expr;
303 DiagID = diag::warn_unused_property_expr;
304 } else if (const CXXFunctionalCastExpr *FC
305 = dyn_cast<CXXFunctionalCastExpr>(E)) {
306 const Expr *E = FC->getSubExpr();
307 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
308 E = TE->getSubExpr();
309 if (isa<CXXTemporaryObjectExpr>(E))
311 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
312 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
313 if (!RD->getAttr<WarnUnusedAttr>())
316 // Diagnose "(void*) blah" as a typo for "(void) blah".
317 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
318 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
319 QualType T = TI->getType();
321 // We really do want to use the non-canonical type here.
322 if (T == Context.VoidPtrTy) {
323 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
325 Diag(Loc, diag::warn_unused_voidptr)
326 << FixItHint::CreateRemoval(TL.getStarLoc());
331 if (E->isGLValue() && E->getType().isVolatileQualified()) {
332 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
336 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
339 void Sema::ActOnStartOfCompoundStmt() {
343 void Sema::ActOnFinishOfCompoundStmt() {
347 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
348 return getCurFunction()->CompoundScopes.back();
351 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
352 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
353 const unsigned NumElts = Elts.size();
355 // If we're in C89 mode, check that we don't have any decls after stmts. If
356 // so, emit an extension diagnostic.
357 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
358 // Note that __extension__ can be around a decl.
360 // Skip over all declarations.
361 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
364 // We found the end of the list or a statement. Scan for another declstmt.
365 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
369 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
370 Diag(D->getLocation(), diag::ext_mixed_decls_code);
373 // Warn about unused expressions in statements.
374 for (unsigned i = 0; i != NumElts; ++i) {
375 // Ignore statements that are last in a statement expression.
376 if (isStmtExpr && i == NumElts - 1)
379 DiagnoseUnusedExprResult(Elts[i]);
382 // Check for suspicious empty body (null statement) in `for' and `while'
383 // statements. Don't do anything for template instantiations, this just adds
385 if (NumElts != 0 && !CurrentInstantiationScope &&
386 getCurCompoundScope().HasEmptyLoopBodies) {
387 for (unsigned i = 0; i != NumElts - 1; ++i)
388 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
391 return new (Context) CompoundStmt(Context, Elts, L, R);
395 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
396 SourceLocation DotDotDotLoc, Expr *RHSVal,
397 SourceLocation ColonLoc) {
398 assert(LHSVal && "missing expression in case statement");
400 if (getCurFunction()->SwitchStack.empty()) {
401 Diag(CaseLoc, diag::err_case_not_in_switch);
406 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
407 if (!getLangOpts().CPlusPlus11)
408 return VerifyIntegerConstantExpression(E);
410 getCurFunction()->SwitchStack.back()->getCond()) {
411 QualType CondType = CondExpr->getType();
412 llvm::APSInt TempVal;
413 return CheckConvertedConstantExpression(E, CondType, TempVal,
422 if (!getLangOpts().CPlusPlus11) {
423 // C99 6.8.4.2p3: The expression shall be an integer constant.
424 // However, GCC allows any evaluatable integer expression.
425 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
426 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
431 // GCC extension: The expression shall be an integer constant.
433 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
434 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
435 // Recover from an error by just forgetting about it.
439 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
440 getLangOpts().CPlusPlus11);
444 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
445 getLangOpts().CPlusPlus11)
450 CaseStmt *CS = new (Context)
451 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
452 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
456 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
457 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
458 DiagnoseUnusedExprResult(SubStmt);
460 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
461 CS->setSubStmt(SubStmt);
465 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
466 Stmt *SubStmt, Scope *CurScope) {
467 DiagnoseUnusedExprResult(SubStmt);
469 if (getCurFunction()->SwitchStack.empty()) {
470 Diag(DefaultLoc, diag::err_default_not_in_switch);
474 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
475 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
480 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
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);
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);
503 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
504 ArrayRef<const Attr*> Attrs,
506 // Fill in the declaration and return it.
507 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
512 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
513 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
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());
520 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
526 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
527 ConditionResult Cond,
528 Stmt *thenStmt, SourceLocation ElseLoc,
530 if (Cond.isInvalid())
531 Cond = ConditionResult(
533 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
534 Context.BoolTy, VK_RValue),
538 Expr *CondExpr = Cond.get().second;
539 if (!Diags.isIgnored(diag::warn_comma_operator,
540 CondExpr->getExprLoc()))
541 CommaVisitor(*this).Visit(CondExpr);
544 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
545 diag::warn_empty_if_body);
547 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
551 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
552 Stmt *InitStmt, ConditionResult Cond,
553 Stmt *thenStmt, SourceLocation ElseLoc,
555 if (Cond.isInvalid())
558 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
559 getCurFunction()->setHasBranchProtectedScope();
561 DiagnoseUnusedExprResult(thenStmt);
562 DiagnoseUnusedExprResult(elseStmt);
565 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
566 Cond.get().second, thenStmt, ElseLoc, elseStmt);
570 struct CaseCompareFunctor {
571 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
572 const llvm::APSInt &RHS) {
573 return LHS.first < RHS;
575 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
576 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
577 return LHS.first < RHS.first;
579 bool operator()(const llvm::APSInt &LHS,
580 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
581 return LHS < RHS.first;
586 /// CmpCaseVals - Comparison predicate for sorting case values.
588 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
589 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
590 if (lhs.first < rhs.first)
593 if (lhs.first == rhs.first &&
594 lhs.second->getCaseLoc().getRawEncoding()
595 < rhs.second->getCaseLoc().getRawEncoding())
600 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
602 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
603 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
605 return lhs.first < rhs.first;
608 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
610 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
611 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
613 return lhs.first == rhs.first;
616 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
617 /// potentially integral-promoted expression @p expr.
618 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
619 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
620 E = CleanUps->getSubExpr();
621 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
622 if (ImpCast->getCastKind() != CK_IntegralCast) break;
623 E = ImpCast->getSubExpr();
628 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
629 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
633 SwitchConvertDiagnoser(Expr *Cond)
634 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
637 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
638 QualType T) override {
639 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
642 SemaDiagnosticBuilder diagnoseIncomplete(
643 Sema &S, SourceLocation Loc, QualType T) override {
644 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
645 << T << Cond->getSourceRange();
648 SemaDiagnosticBuilder diagnoseExplicitConv(
649 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
650 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
653 SemaDiagnosticBuilder noteExplicitConv(
654 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
655 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
656 << ConvTy->isEnumeralType() << ConvTy;
659 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
660 QualType T) override {
661 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
664 SemaDiagnosticBuilder noteAmbiguous(
665 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
666 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
667 << ConvTy->isEnumeralType() << ConvTy;
670 SemaDiagnosticBuilder diagnoseConversion(
671 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
672 llvm_unreachable("conversion functions are permitted");
674 } SwitchDiagnoser(Cond);
676 ExprResult CondResult =
677 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
678 if (CondResult.isInvalid())
681 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
682 return UsualUnaryConversions(CondResult.get());
685 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
686 Stmt *InitStmt, ConditionResult Cond) {
687 if (Cond.isInvalid())
690 getCurFunction()->setHasBranchIntoScope();
692 SwitchStmt *SS = new (Context)
693 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
694 getCurFunction()->SwitchStack.push_back(SS);
698 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
699 Val = Val.extOrTrunc(BitWidth);
700 Val.setIsSigned(IsSigned);
703 /// Check the specified case value is in range for the given unpromoted switch
705 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
706 unsigned UnpromotedWidth, bool UnpromotedSign) {
707 // If the case value was signed and negative and the switch expression is
708 // unsigned, don't bother to warn: this is implementation-defined behavior.
709 // FIXME: Introduce a second, default-ignored warning for this case?
710 if (UnpromotedWidth < Val.getBitWidth()) {
711 llvm::APSInt ConvVal(Val);
712 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
713 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
714 // FIXME: Use different diagnostics for overflow in conversion to promoted
715 // type versus "switch expression cannot have this value". Use proper
716 // IntRange checking rather than just looking at the unpromoted type here.
718 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
719 << ConvVal.toString(10);
723 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
725 /// Returns true if we should emit a diagnostic about this case expression not
726 /// being a part of the enum used in the switch controlling expression.
727 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
729 const Expr *CaseExpr,
730 EnumValsTy::iterator &EI,
731 EnumValsTy::iterator &EIEnd,
732 const llvm::APSInt &Val) {
736 if (const DeclRefExpr *DRE =
737 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
738 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
739 QualType VarType = VD->getType();
740 QualType EnumType = S.Context.getTypeDeclType(ED);
741 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
742 S.Context.hasSameUnqualifiedType(EnumType, VarType))
747 if (ED->hasAttr<FlagEnumAttr>())
748 return !S.IsValueInFlagEnum(ED, Val, false);
750 while (EI != EIEnd && EI->first < Val)
753 if (EI != EIEnd && EI->first == Val)
759 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
761 QualType CondType = GetTypeBeforeIntegralPromotion(Cond);
762 QualType CaseType = Case->getType();
764 const EnumType *CondEnumType = CondType->getAs<EnumType>();
765 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
766 if (!CondEnumType || !CaseEnumType)
769 // Ignore anonymous enums.
770 if (!CondEnumType->getDecl()->getIdentifier() &&
771 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
773 if (!CaseEnumType->getDecl()->getIdentifier() &&
774 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
777 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
780 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
781 << CondType << CaseType << Cond->getSourceRange()
782 << Case->getSourceRange();
786 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
788 SwitchStmt *SS = cast<SwitchStmt>(Switch);
789 assert(SS == getCurFunction()->SwitchStack.back() &&
790 "switch stack missing push/pop!");
792 getCurFunction()->SwitchStack.pop_back();
794 if (!BodyStmt) return StmtError();
795 SS->setBody(BodyStmt, SwitchLoc);
797 Expr *CondExpr = SS->getCond();
798 if (!CondExpr) return StmtError();
800 QualType CondType = CondExpr->getType();
802 const Expr *CondExprBeforePromotion = CondExpr;
803 QualType CondTypeBeforePromotion =
804 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
807 // Integral promotions are performed (on the switch condition).
809 // A case value unrepresentable by the original switch condition
810 // type (before the promotion) doesn't make sense, even when it can
811 // be represented by the promoted type. Therefore we need to find
812 // the pre-promotion type of the switch condition.
813 if (!CondExpr->isTypeDependent()) {
814 // We have already converted the expression to an integral or enumeration
815 // type, when we started the switch statement. If we don't have an
816 // appropriate type now, just return an error.
817 if (!CondType->isIntegralOrEnumerationType())
820 if (CondExpr->isKnownToHaveBooleanValue()) {
821 // switch(bool_expr) {...} is often a programmer error, e.g.
822 // switch(n && mask) { ... } // Doh - should be "n & mask".
823 // One can always use an if statement instead of switch(bool_expr).
824 Diag(SwitchLoc, diag::warn_bool_switch_condition)
825 << CondExpr->getSourceRange();
829 // Get the bitwidth of the switched-on value after promotions. We must
830 // convert the integer case values to this width before comparison.
831 bool HasDependentValue
832 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
833 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
834 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
836 // Get the width and signedness that the condition might actually have, for
838 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
840 unsigned CondWidthBeforePromotion
841 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
842 bool CondIsSignedBeforePromotion
843 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
845 // Accumulate all of the case values in a vector so that we can sort them
846 // and detect duplicates. This vector contains the APInt for the case after
847 // it has been converted to the condition type.
848 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
851 // Keep track of any GNU case ranges we see. The APSInt is the low value.
852 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
853 CaseRangesTy CaseRanges;
855 DefaultStmt *TheDefaultStmt = nullptr;
857 bool CaseListIsErroneous = false;
859 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
860 SC = SC->getNextSwitchCase()) {
862 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
863 if (TheDefaultStmt) {
864 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
865 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
867 // FIXME: Remove the default statement from the switch block so that
868 // we'll return a valid AST. This requires recursing down the AST and
869 // finding it, not something we are set up to do right now. For now,
870 // just lop the entire switch stmt out of the AST.
871 CaseListIsErroneous = true;
876 CaseStmt *CS = cast<CaseStmt>(SC);
878 Expr *Lo = CS->getLHS();
880 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
881 HasDependentValue = true;
885 checkEnumTypesInSwitchStmt(*this, CondExpr, Lo);
889 if (getLangOpts().CPlusPlus11) {
890 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
891 // constant expression of the promoted type of the switch condition.
893 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
894 if (ConvLo.isInvalid()) {
895 CaseListIsErroneous = true;
900 // We already verified that the expression has a i-c-e value (C99
901 // 6.8.4.2p3) - get that value now.
902 LoVal = Lo->EvaluateKnownConstInt(Context);
904 // If the LHS is not the same type as the condition, insert an implicit
906 Lo = DefaultLvalueConversion(Lo).get();
907 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
910 // Check the unconverted value is within the range of possible values of
911 // the switch expression.
912 checkCaseValue(*this, Lo->getLocStart(), LoVal,
913 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
915 // Convert the value to the same width/sign as the condition.
916 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
920 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
922 if (CS->getRHS()->isTypeDependent() ||
923 CS->getRHS()->isValueDependent()) {
924 HasDependentValue = true;
927 CaseRanges.push_back(std::make_pair(LoVal, CS));
929 CaseVals.push_back(std::make_pair(LoVal, CS));
933 if (!HasDependentValue) {
934 // If we don't have a default statement, check whether the
935 // condition is constant.
936 llvm::APSInt ConstantCondValue;
937 bool HasConstantCond = false;
938 if (!HasDependentValue && !TheDefaultStmt) {
939 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
940 Expr::SE_AllowSideEffects);
941 assert(!HasConstantCond ||
942 (ConstantCondValue.getBitWidth() == CondWidth &&
943 ConstantCondValue.isSigned() == CondIsSigned));
945 bool ShouldCheckConstantCond = HasConstantCond;
947 // Sort all the scalar case values so we can easily detect duplicates.
948 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
950 if (!CaseVals.empty()) {
951 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
952 if (ShouldCheckConstantCond &&
953 CaseVals[i].first == ConstantCondValue)
954 ShouldCheckConstantCond = false;
956 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
957 // If we have a duplicate, report it.
958 // First, determine if either case value has a name
959 StringRef PrevString, CurrString;
960 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
961 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
962 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
963 PrevString = DeclRef->getDecl()->getName();
965 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
966 CurrString = DeclRef->getDecl()->getName();
968 SmallString<16> CaseValStr;
969 CaseVals[i-1].first.toString(CaseValStr);
971 if (PrevString == CurrString)
972 Diag(CaseVals[i].second->getLHS()->getLocStart(),
973 diag::err_duplicate_case) <<
974 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
976 Diag(CaseVals[i].second->getLHS()->getLocStart(),
977 diag::err_duplicate_case_differing_expr) <<
978 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
979 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
982 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
983 diag::note_duplicate_case_prev);
984 // FIXME: We really want to remove the bogus case stmt from the
985 // substmt, but we have no way to do this right now.
986 CaseListIsErroneous = true;
991 // Detect duplicate case ranges, which usually don't exist at all in
993 if (!CaseRanges.empty()) {
994 // Sort all the case ranges by their low value so we can easily detect
995 // overlaps between ranges.
996 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
998 // Scan the ranges, computing the high values and removing empty ranges.
999 std::vector<llvm::APSInt> HiVals;
1000 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1001 llvm::APSInt &LoVal = CaseRanges[i].first;
1002 CaseStmt *CR = CaseRanges[i].second;
1003 Expr *Hi = CR->getRHS();
1006 if (getLangOpts().CPlusPlus11) {
1007 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
1008 // constant expression of the promoted type of the switch condition.
1010 CheckConvertedConstantExpression(Hi, CondType, HiVal,
1012 if (ConvHi.isInvalid()) {
1013 CaseListIsErroneous = true;
1018 HiVal = Hi->EvaluateKnownConstInt(Context);
1020 // If the RHS is not the same type as the condition, insert an
1022 Hi = DefaultLvalueConversion(Hi).get();
1023 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
1026 // Check the unconverted value is within the range of possible values of
1027 // the switch expression.
1028 checkCaseValue(*this, Hi->getLocStart(), HiVal,
1029 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1031 // Convert the value to the same width/sign as the condition.
1032 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1036 // If the low value is bigger than the high value, the case is empty.
1037 if (LoVal > HiVal) {
1038 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1039 << SourceRange(CR->getLHS()->getLocStart(),
1041 CaseRanges.erase(CaseRanges.begin()+i);
1047 if (ShouldCheckConstantCond &&
1048 LoVal <= ConstantCondValue &&
1049 ConstantCondValue <= HiVal)
1050 ShouldCheckConstantCond = false;
1052 HiVals.push_back(HiVal);
1055 // Rescan the ranges, looking for overlap with singleton values and other
1056 // ranges. Since the range list is sorted, we only need to compare case
1057 // ranges with their neighbors.
1058 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1059 llvm::APSInt &CRLo = CaseRanges[i].first;
1060 llvm::APSInt &CRHi = HiVals[i];
1061 CaseStmt *CR = CaseRanges[i].second;
1063 // Check to see whether the case range overlaps with any
1065 CaseStmt *OverlapStmt = nullptr;
1066 llvm::APSInt OverlapVal(32);
1068 // Find the smallest value >= the lower bound. If I is in the
1069 // case range, then we have overlap.
1070 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1071 CaseVals.end(), CRLo,
1072 CaseCompareFunctor());
1073 if (I != CaseVals.end() && I->first < CRHi) {
1074 OverlapVal = I->first; // Found overlap with scalar.
1075 OverlapStmt = I->second;
1078 // Find the smallest value bigger than the upper bound.
1079 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1080 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1081 OverlapVal = (I-1)->first; // Found overlap with scalar.
1082 OverlapStmt = (I-1)->second;
1085 // Check to see if this case stmt overlaps with the subsequent
1087 if (i && CRLo <= HiVals[i-1]) {
1088 OverlapVal = HiVals[i-1]; // Found overlap with range.
1089 OverlapStmt = CaseRanges[i-1].second;
1093 // If we have a duplicate, report it.
1094 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1095 << OverlapVal.toString(10);
1096 Diag(OverlapStmt->getLHS()->getLocStart(),
1097 diag::note_duplicate_case_prev);
1098 // FIXME: We really want to remove the bogus case stmt from the
1099 // substmt, but we have no way to do this right now.
1100 CaseListIsErroneous = true;
1105 // Complain if we have a constant condition and we didn't find a match.
1106 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1107 // TODO: it would be nice if we printed enums as enums, chars as
1109 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1110 << ConstantCondValue.toString(10)
1111 << CondExpr->getSourceRange();
1114 // Check to see if switch is over an Enum and handles all of its
1115 // values. We only issue a warning if there is not 'default:', but
1116 // we still do the analysis to preserve this information in the AST
1117 // (which can be used by flow-based analyes).
1119 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1121 // If switch has default case, then ignore it.
1122 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1123 ET->getDecl()->isCompleteDefinition()) {
1124 const EnumDecl *ED = ET->getDecl();
1125 EnumValsTy EnumVals;
1127 // Gather all enum values, set their type and sort them,
1128 // allowing easier comparison with CaseVals.
1129 for (auto *EDI : ED->enumerators()) {
1130 llvm::APSInt Val = EDI->getInitVal();
1131 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1132 EnumVals.push_back(std::make_pair(Val, EDI));
1134 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1135 auto EI = EnumVals.begin(), EIEnd =
1136 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1138 // See which case values aren't in enum.
1139 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1140 CI != CaseVals.end(); CI++) {
1141 Expr *CaseExpr = CI->second->getLHS();
1142 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1144 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1145 << CondTypeBeforePromotion;
1148 // See which of case ranges aren't in enum
1149 EI = EnumVals.begin();
1150 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1151 RI != CaseRanges.end(); RI++) {
1152 Expr *CaseExpr = RI->second->getLHS();
1153 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1155 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1156 << CondTypeBeforePromotion;
1159 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1160 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1162 CaseExpr = RI->second->getRHS();
1163 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1165 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1166 << CondTypeBeforePromotion;
1169 // Check which enum vals aren't in switch
1170 auto CI = CaseVals.begin();
1171 auto RI = CaseRanges.begin();
1172 bool hasCasesNotInSwitch = false;
1174 SmallVector<DeclarationName,8> UnhandledNames;
1176 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1177 // Drop unneeded case values
1178 while (CI != CaseVals.end() && CI->first < EI->first)
1181 if (CI != CaseVals.end() && CI->first == EI->first)
1184 // Drop unneeded case ranges
1185 for (; RI != CaseRanges.end(); RI++) {
1187 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1188 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1189 if (EI->first <= Hi)
1193 if (RI == CaseRanges.end() || EI->first < RI->first) {
1194 hasCasesNotInSwitch = true;
1195 UnhandledNames.push_back(EI->second->getDeclName());
1199 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1200 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1202 // Produce a nice diagnostic if multiple values aren't handled.
1203 if (!UnhandledNames.empty()) {
1204 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1205 TheDefaultStmt ? diag::warn_def_missing_case
1206 : diag::warn_missing_case)
1207 << (int)UnhandledNames.size();
1209 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1211 DB << UnhandledNames[I];
1214 if (!hasCasesNotInSwitch)
1215 SS->setAllEnumCasesCovered();
1220 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1221 diag::warn_empty_switch_body);
1223 // FIXME: If the case list was broken is some way, we don't have a good system
1224 // to patch it up. Instead, just return the whole substmt as broken.
1225 if (CaseListIsErroneous)
1232 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1234 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1237 if (const EnumType *ET = DstType->getAs<EnumType>())
1238 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1239 SrcType->isIntegerType()) {
1240 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1241 SrcExpr->isIntegerConstantExpr(Context)) {
1242 // Get the bitwidth of the enum value before promotions.
1243 unsigned DstWidth = Context.getIntWidth(DstType);
1244 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1246 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1247 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1248 const EnumDecl *ED = ET->getDecl();
1250 if (!ED->isClosed())
1253 if (ED->hasAttr<FlagEnumAttr>()) {
1254 if (!IsValueInFlagEnum(ED, RhsVal, true))
1255 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1256 << DstType.getUnqualifiedType();
1258 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1260 EnumValsTy EnumVals;
1262 // Gather all enum values, set their type and sort them,
1263 // allowing easier comparison with rhs constant.
1264 for (auto *EDI : ED->enumerators()) {
1265 llvm::APSInt Val = EDI->getInitVal();
1266 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1267 EnumVals.push_back(std::make_pair(Val, EDI));
1269 if (EnumVals.empty())
1271 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1272 EnumValsTy::iterator EIend =
1273 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1275 // See which values aren't in the enum.
1276 EnumValsTy::const_iterator EI = EnumVals.begin();
1277 while (EI != EIend && EI->first < RhsVal)
1279 if (EI == EIend || EI->first != RhsVal) {
1280 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1281 << DstType.getUnqualifiedType();
1288 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1290 if (Cond.isInvalid())
1293 auto CondVal = Cond.get();
1294 CheckBreakContinueBinding(CondVal.second);
1296 if (CondVal.second &&
1297 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1298 CommaVisitor(*this).Visit(CondVal.second);
1300 DiagnoseUnusedExprResult(Body);
1302 if (isa<NullStmt>(Body))
1303 getCurCompoundScope().setHasEmptyLoopBodies();
1305 return new (Context)
1306 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
1310 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1311 SourceLocation WhileLoc, SourceLocation CondLParen,
1312 Expr *Cond, SourceLocation CondRParen) {
1313 assert(Cond && "ActOnDoStmt(): missing expression");
1315 CheckBreakContinueBinding(Cond);
1316 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1317 if (CondResult.isInvalid())
1319 Cond = CondResult.get();
1321 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1322 if (CondResult.isInvalid())
1324 Cond = CondResult.get();
1326 DiagnoseUnusedExprResult(Body);
1328 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1332 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1333 using DeclSetVector =
1334 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1335 llvm::SmallPtrSet<VarDecl *, 8>>;
1337 // This visitor will traverse a conditional statement and store all
1338 // the evaluated decls into a vector. Simple is set to true if none
1339 // of the excluded constructs are used.
1340 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1341 DeclSetVector &Decls;
1342 SmallVectorImpl<SourceRange> &Ranges;
1345 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1347 DeclExtractor(Sema &S, DeclSetVector &Decls,
1348 SmallVectorImpl<SourceRange> &Ranges) :
1349 Inherited(S.Context),
1354 bool isSimple() { return Simple; }
1356 // Replaces the method in EvaluatedExprVisitor.
1357 void VisitMemberExpr(MemberExpr* E) {
1361 // Any Stmt not whitelisted will cause the condition to be marked complex.
1362 void VisitStmt(Stmt *S) {
1366 void VisitBinaryOperator(BinaryOperator *E) {
1371 void VisitCastExpr(CastExpr *E) {
1372 Visit(E->getSubExpr());
1375 void VisitUnaryOperator(UnaryOperator *E) {
1376 // Skip checking conditionals with derefernces.
1377 if (E->getOpcode() == UO_Deref)
1380 Visit(E->getSubExpr());
1383 void VisitConditionalOperator(ConditionalOperator *E) {
1384 Visit(E->getCond());
1385 Visit(E->getTrueExpr());
1386 Visit(E->getFalseExpr());
1389 void VisitParenExpr(ParenExpr *E) {
1390 Visit(E->getSubExpr());
1393 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1394 Visit(E->getOpaqueValue()->getSourceExpr());
1395 Visit(E->getFalseExpr());
1398 void VisitIntegerLiteral(IntegerLiteral *E) { }
1399 void VisitFloatingLiteral(FloatingLiteral *E) { }
1400 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1401 void VisitCharacterLiteral(CharacterLiteral *E) { }
1402 void VisitGNUNullExpr(GNUNullExpr *E) { }
1403 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1405 void VisitDeclRefExpr(DeclRefExpr *E) {
1406 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1409 Ranges.push_back(E->getSourceRange());
1414 }; // end class DeclExtractor
1416 // DeclMatcher checks to see if the decls are used in a non-evaluated
1418 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1419 DeclSetVector &Decls;
1423 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1425 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1426 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1427 if (!Statement) return;
1432 void VisitReturnStmt(ReturnStmt *S) {
1436 void VisitBreakStmt(BreakStmt *S) {
1440 void VisitGotoStmt(GotoStmt *S) {
1444 void VisitCastExpr(CastExpr *E) {
1445 if (E->getCastKind() == CK_LValueToRValue)
1446 CheckLValueToRValueCast(E->getSubExpr());
1448 Visit(E->getSubExpr());
1451 void CheckLValueToRValueCast(Expr *E) {
1452 E = E->IgnoreParenImpCasts();
1454 if (isa<DeclRefExpr>(E)) {
1458 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1459 Visit(CO->getCond());
1460 CheckLValueToRValueCast(CO->getTrueExpr());
1461 CheckLValueToRValueCast(CO->getFalseExpr());
1465 if (BinaryConditionalOperator *BCO =
1466 dyn_cast<BinaryConditionalOperator>(E)) {
1467 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1468 CheckLValueToRValueCast(BCO->getFalseExpr());
1475 void VisitDeclRefExpr(DeclRefExpr *E) {
1476 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1477 if (Decls.count(VD))
1481 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1482 // Only need to visit the semantics for POE.
1483 // SyntaticForm doesn't really use the Decal.
1484 for (auto *S : POE->semantics()) {
1485 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1486 // Look past the OVE into the expression it binds.
1487 Visit(OVE->getSourceExpr());
1493 bool FoundDeclInUse() { return FoundDecl; }
1495 }; // end class DeclMatcher
1497 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1498 Expr *Third, Stmt *Body) {
1499 // Condition is empty
1500 if (!Second) return;
1502 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1503 Second->getLocStart()))
1506 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1507 DeclSetVector Decls;
1508 SmallVector<SourceRange, 10> Ranges;
1509 DeclExtractor DE(S, Decls, Ranges);
1512 // Don't analyze complex conditionals.
1513 if (!DE.isSimple()) return;
1516 if (Decls.size() == 0) return;
1518 // Don't warn on volatile, static, or global variables.
1519 for (auto *VD : Decls)
1520 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1523 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1524 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1525 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1528 // Load decl names into diagnostic.
1529 if (Decls.size() > 4) {
1532 PDiag << (unsigned)Decls.size();
1533 for (auto *VD : Decls)
1534 PDiag << VD->getDeclName();
1537 for (auto Range : Ranges)
1540 S.Diag(Ranges.begin()->getBegin(), PDiag);
1543 // If Statement is an incemement or decrement, return true and sets the
1544 // variables Increment and DRE.
1545 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1546 DeclRefExpr *&DRE) {
1547 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1548 if (!Cleanups->cleanupsHaveSideEffects())
1549 Statement = Cleanups->getSubExpr();
1551 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1552 switch (UO->getOpcode()) {
1553 default: return false;
1563 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1567 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1568 FunctionDecl *FD = Call->getDirectCallee();
1569 if (!FD || !FD->isOverloadedOperator()) return false;
1570 switch (FD->getOverloadedOperator()) {
1571 default: return false;
1579 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1586 // A visitor to determine if a continue or break statement is a
1588 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1589 SourceLocation BreakLoc;
1590 SourceLocation ContinueLoc;
1591 bool InSwitch = false;
1594 BreakContinueFinder(Sema &S, const Stmt* Body) :
1595 Inherited(S.Context) {
1599 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1601 void VisitContinueStmt(const ContinueStmt* E) {
1602 ContinueLoc = E->getContinueLoc();
1605 void VisitBreakStmt(const BreakStmt* E) {
1607 BreakLoc = E->getBreakLoc();
1610 void VisitSwitchStmt(const SwitchStmt* S) {
1611 if (const Stmt *Init = S->getInit())
1613 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1615 if (const Stmt *Cond = S->getCond())
1618 // Don't return break statements from the body of a switch.
1620 if (const Stmt *Body = S->getBody())
1625 void VisitForStmt(const ForStmt *S) {
1626 // Only visit the init statement of a for loop; the body
1627 // has a different break/continue scope.
1628 if (const Stmt *Init = S->getInit())
1632 void VisitWhileStmt(const WhileStmt *) {
1633 // Do nothing; the children of a while loop have a different
1634 // break/continue scope.
1637 void VisitDoStmt(const DoStmt *) {
1638 // Do nothing; the children of a while loop have a different
1639 // break/continue scope.
1642 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1643 // Only visit the initialization of a for loop; the body
1644 // has a different break/continue scope.
1645 if (const Stmt *Range = S->getRangeStmt())
1647 if (const Stmt *Begin = S->getBeginStmt())
1649 if (const Stmt *End = S->getEndStmt())
1653 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1654 // Only visit the initialization of a for loop; the body
1655 // has a different break/continue scope.
1656 if (const Stmt *Element = S->getElement())
1658 if (const Stmt *Collection = S->getCollection())
1662 bool ContinueFound() { return ContinueLoc.isValid(); }
1663 bool BreakFound() { return BreakLoc.isValid(); }
1664 SourceLocation GetContinueLoc() { return ContinueLoc; }
1665 SourceLocation GetBreakLoc() { return BreakLoc; }
1667 }; // end class BreakContinueFinder
1669 // Emit a warning when a loop increment/decrement appears twice per loop
1670 // iteration. The conditions which trigger this warning are:
1671 // 1) The last statement in the loop body and the third expression in the
1672 // for loop are both increment or both decrement of the same variable
1673 // 2) No continue statements in the loop body.
1674 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1675 // Return when there is nothing to check.
1676 if (!Body || !Third) return;
1678 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1679 Third->getLocStart()))
1682 // Get the last statement from the loop body.
1683 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1684 if (!CS || CS->body_empty()) return;
1685 Stmt *LastStmt = CS->body_back();
1686 if (!LastStmt) return;
1688 bool LoopIncrement, LastIncrement;
1689 DeclRefExpr *LoopDRE, *LastDRE;
1691 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1692 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1694 // Check that the two statements are both increments or both decrements
1695 // on the same variable.
1696 if (LoopIncrement != LastIncrement ||
1697 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1699 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1701 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1702 << LastDRE->getDecl() << LastIncrement;
1703 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1710 void Sema::CheckBreakContinueBinding(Expr *E) {
1711 if (!E || getLangOpts().CPlusPlus)
1713 BreakContinueFinder BCFinder(*this, E);
1714 Scope *BreakParent = CurScope->getBreakParent();
1715 if (BCFinder.BreakFound() && BreakParent) {
1716 if (BreakParent->getFlags() & Scope::SwitchScope) {
1717 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1719 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1722 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1723 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1728 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1729 Stmt *First, ConditionResult Second,
1730 FullExprArg third, SourceLocation RParenLoc,
1732 if (Second.isInvalid())
1735 if (!getLangOpts().CPlusPlus) {
1736 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1737 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1738 // declare identifiers for objects having storage class 'auto' or
1740 for (auto *DI : DS->decls()) {
1741 VarDecl *VD = dyn_cast<VarDecl>(DI);
1742 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1745 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1746 DI->setInvalidDecl();
1752 CheckBreakContinueBinding(Second.get().second);
1753 CheckBreakContinueBinding(third.get());
1755 if (!Second.get().first)
1756 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1758 CheckForRedundantIteration(*this, third.get(), Body);
1760 if (Second.get().second &&
1761 !Diags.isIgnored(diag::warn_comma_operator,
1762 Second.get().second->getExprLoc()))
1763 CommaVisitor(*this).Visit(Second.get().second);
1765 Expr *Third = third.release().getAs<Expr>();
1767 DiagnoseUnusedExprResult(First);
1768 DiagnoseUnusedExprResult(Third);
1769 DiagnoseUnusedExprResult(Body);
1771 if (isa<NullStmt>(Body))
1772 getCurCompoundScope().setHasEmptyLoopBodies();
1774 return new (Context)
1775 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1776 Body, ForLoc, LParenLoc, RParenLoc);
1779 /// In an Objective C collection iteration statement:
1781 /// x can be an arbitrary l-value expression. Bind it up as a
1782 /// full-expression.
1783 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1784 // Reduce placeholder expressions here. Note that this rejects the
1785 // use of pseudo-object l-values in this position.
1786 ExprResult result = CheckPlaceholderExpr(E);
1787 if (result.isInvalid()) return StmtError();
1790 ExprResult FullExpr = ActOnFinishFullExpr(E);
1791 if (FullExpr.isInvalid())
1793 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1797 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1801 ExprResult result = CorrectDelayedTyposInExpr(collection);
1802 if (!result.isUsable())
1804 collection = result.get();
1806 // Bail out early if we've got a type-dependent expression.
1807 if (collection->isTypeDependent()) return collection;
1809 // Perform normal l-value conversion.
1810 result = DefaultFunctionArrayLvalueConversion(collection);
1811 if (result.isInvalid())
1813 collection = result.get();
1815 // The operand needs to have object-pointer type.
1816 // TODO: should we do a contextual conversion?
1817 const ObjCObjectPointerType *pointerType =
1818 collection->getType()->getAs<ObjCObjectPointerType>();
1820 return Diag(forLoc, diag::err_collection_expr_type)
1821 << collection->getType() << collection->getSourceRange();
1823 // Check that the operand provides
1824 // - countByEnumeratingWithState:objects:count:
1825 const ObjCObjectType *objectType = pointerType->getObjectType();
1826 ObjCInterfaceDecl *iface = objectType->getInterface();
1828 // If we have a forward-declared type, we can't do this check.
1829 // Under ARC, it is an error not to have a forward-declared class.
1831 (getLangOpts().ObjCAutoRefCount
1832 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1833 diag::err_arc_collection_forward, collection)
1834 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1835 // Otherwise, if we have any useful type information, check that
1836 // the type declares the appropriate method.
1837 } else if (iface || !objectType->qual_empty()) {
1838 IdentifierInfo *selectorIdents[] = {
1839 &Context.Idents.get("countByEnumeratingWithState"),
1840 &Context.Idents.get("objects"),
1841 &Context.Idents.get("count")
1843 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1845 ObjCMethodDecl *method = nullptr;
1847 // If there's an interface, look in both the public and private APIs.
1849 method = iface->lookupInstanceMethod(selector);
1850 if (!method) method = iface->lookupPrivateMethod(selector);
1853 // Also check protocol qualifiers.
1855 method = LookupMethodInQualifiedType(selector, pointerType,
1858 // If we didn't find it anywhere, give up.
1860 Diag(forLoc, diag::warn_collection_expr_type)
1861 << collection->getType() << selector << collection->getSourceRange();
1864 // TODO: check for an incompatible signature?
1867 // Wrap up any cleanups in the expression.
1872 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1873 Stmt *First, Expr *collection,
1874 SourceLocation RParenLoc) {
1875 getCurFunction()->setHasBranchProtectedScope();
1877 ExprResult CollectionExprResult =
1878 CheckObjCForCollectionOperand(ForLoc, collection);
1882 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1883 if (!DS->isSingleDecl())
1884 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1885 diag::err_toomany_element_decls));
1887 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1888 if (!D || D->isInvalidDecl())
1891 FirstType = D->getType();
1892 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1893 // declare identifiers for objects having storage class 'auto' or
1895 if (!D->hasLocalStorage())
1896 return StmtError(Diag(D->getLocation(),
1897 diag::err_non_local_variable_decl_in_for));
1899 // If the type contained 'auto', deduce the 'auto' to 'id'.
1900 if (FirstType->getContainedAutoType()) {
1901 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1903 Expr *DeducedInit = &OpaqueId;
1904 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1906 DiagnoseAutoDeductionFailure(D, DeducedInit);
1907 if (FirstType.isNull()) {
1908 D->setInvalidDecl();
1912 D->setType(FirstType);
1914 if (!inTemplateInstantiation()) {
1915 SourceLocation Loc =
1916 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1917 Diag(Loc, diag::warn_auto_var_is_id)
1918 << D->getDeclName();
1923 Expr *FirstE = cast<Expr>(First);
1924 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1925 return StmtError(Diag(First->getLocStart(),
1926 diag::err_selector_element_not_lvalue)
1927 << First->getSourceRange());
1929 FirstType = static_cast<Expr*>(First)->getType();
1930 if (FirstType.isConstQualified())
1931 Diag(ForLoc, diag::err_selector_element_const_type)
1932 << FirstType << First->getSourceRange();
1934 if (!FirstType->isDependentType() &&
1935 !FirstType->isObjCObjectPointerType() &&
1936 !FirstType->isBlockPointerType())
1937 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1938 << FirstType << First->getSourceRange());
1941 if (CollectionExprResult.isInvalid())
1944 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1945 if (CollectionExprResult.isInvalid())
1948 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1949 nullptr, ForLoc, RParenLoc);
1952 /// Finish building a variable declaration for a for-range statement.
1953 /// \return true if an error occurs.
1954 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1955 SourceLocation Loc, int DiagID) {
1956 if (Decl->getType()->isUndeducedType()) {
1957 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1958 if (!Res.isUsable()) {
1959 Decl->setInvalidDecl();
1965 // Deduce the type for the iterator variable now rather than leaving it to
1966 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1968 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1969 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1971 SemaRef.Diag(Loc, DiagID) << Init->getType();
1972 if (InitType.isNull()) {
1973 Decl->setInvalidDecl();
1976 Decl->setType(InitType);
1978 // In ARC, infer lifetime.
1979 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1980 // we're doing the equivalent of fast iteration.
1981 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1982 SemaRef.inferObjCARCLifetime(Decl))
1983 Decl->setInvalidDecl();
1985 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1986 SemaRef.FinalizeDeclaration(Decl);
1987 SemaRef.CurContext->addHiddenDecl(Decl);
1992 // An enum to represent whether something is dealing with a call to begin()
1993 // or a call to end() in a range-based for loop.
1994 enum BeginEndFunction {
1999 /// Produce a note indicating which begin/end function was implicitly called
2000 /// by a C++11 for-range statement. This is often not obvious from the code,
2001 /// nor from the diagnostics produced when analysing the implicit expressions
2002 /// required in a for-range statement.
2003 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2004 BeginEndFunction BEF) {
2005 CallExpr *CE = dyn_cast<CallExpr>(E);
2008 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2011 SourceLocation Loc = D->getLocation();
2013 std::string Description;
2014 bool IsTemplate = false;
2015 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2016 Description = SemaRef.getTemplateArgumentBindingsText(
2017 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2021 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2022 << BEF << IsTemplate << Description << E->getType();
2025 /// Build a variable declaration for a for-range statement.
2026 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2027 QualType Type, const char *Name) {
2028 DeclContext *DC = SemaRef.CurContext;
2029 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2030 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2031 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2033 Decl->setImplicit();
2039 static bool ObjCEnumerationCollection(Expr *Collection) {
2040 return !Collection->isTypeDependent()
2041 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2044 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2046 /// C++11 [stmt.ranged]:
2047 /// A range-based for statement is equivalent to
2050 /// auto && __range = range-init;
2051 /// for ( auto __begin = begin-expr,
2052 /// __end = end-expr;
2053 /// __begin != __end;
2055 /// for-range-declaration = *__begin;
2060 /// The body of the loop is not available yet, since it cannot be analysed until
2061 /// we have determined the type of the for-range-declaration.
2062 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2063 SourceLocation CoawaitLoc, Stmt *First,
2064 SourceLocation ColonLoc, Expr *Range,
2065 SourceLocation RParenLoc,
2066 BuildForRangeKind Kind) {
2070 if (Range && ObjCEnumerationCollection(Range))
2071 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2073 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2074 assert(DS && "first part of for range not a decl stmt");
2076 if (!DS->isSingleDecl()) {
2077 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
2081 Decl *LoopVar = DS->getSingleDecl();
2082 if (LoopVar->isInvalidDecl() || !Range ||
2083 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2084 LoopVar->setInvalidDecl();
2088 // Build the coroutine state immediately and not later during template
2090 if (!CoawaitLoc.isInvalid()) {
2091 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2095 // Build auto && __range = range-init
2096 SourceLocation RangeLoc = Range->getLocStart();
2097 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2098 Context.getAutoRRefDeductType(),
2100 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2101 diag::err_for_range_deduction_failure)) {
2102 LoopVar->setInvalidDecl();
2106 // Claim the type doesn't contain auto: we've already done the checking.
2107 DeclGroupPtrTy RangeGroup =
2108 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2109 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2110 if (RangeDecl.isInvalid()) {
2111 LoopVar->setInvalidDecl();
2115 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
2116 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2117 /*Cond=*/nullptr, /*Inc=*/nullptr,
2118 DS, RParenLoc, Kind);
2121 /// \brief Create the initialization, compare, and increment steps for
2122 /// the range-based for loop expression.
2123 /// This function does not handle array-based for loops,
2124 /// which are created in Sema::BuildCXXForRangeStmt.
2126 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2127 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2128 /// CandidateSet and BEF are set and some non-success value is returned on
2130 static Sema::ForRangeStatus
2131 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2132 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2133 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2134 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2135 ExprResult *EndExpr, BeginEndFunction *BEF) {
2136 DeclarationNameInfo BeginNameInfo(
2137 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2138 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2141 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2142 Sema::LookupMemberName);
2143 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2145 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2146 // - if _RangeT is a class type, the unqualified-ids begin and end are
2147 // looked up in the scope of class _RangeT as if by class member access
2148 // lookup (3.4.5), and if either (or both) finds at least one
2149 // declaration, begin-expr and end-expr are __range.begin() and
2150 // __range.end(), respectively;
2151 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2152 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2154 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2155 SourceLocation RangeLoc = BeginVar->getLocation();
2156 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
2158 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2159 << RangeLoc << BeginRange->getType() << *BEF;
2160 return Sema::FRS_DiagnosticIssued;
2163 // - otherwise, begin-expr and end-expr are begin(__range) and
2164 // end(__range), respectively, where begin and end are looked up with
2165 // argument-dependent lookup (3.4.2). For the purposes of this name
2166 // lookup, namespace std is an associated namespace.
2171 Sema::ForRangeStatus RangeStatus =
2172 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2173 BeginMemberLookup, CandidateSet,
2174 BeginRange, BeginExpr);
2176 if (RangeStatus != Sema::FRS_Success) {
2177 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2178 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2179 << ColonLoc << BEF_begin << BeginRange->getType();
2182 if (!CoawaitLoc.isInvalid()) {
2183 // FIXME: getCurScope() should not be used during template instantiation.
2184 // We should pick up the set of unqualified lookup results for operator
2185 // co_await during the initial parse.
2186 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2188 if (BeginExpr->isInvalid())
2189 return Sema::FRS_DiagnosticIssued;
2191 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2192 diag::err_for_range_iter_deduction_failure)) {
2193 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2194 return Sema::FRS_DiagnosticIssued;
2199 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2200 EndMemberLookup, CandidateSet,
2202 if (RangeStatus != Sema::FRS_Success) {
2203 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2204 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2205 << ColonLoc << BEF_end << EndRange->getType();
2208 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2209 diag::err_for_range_iter_deduction_failure)) {
2210 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2211 return Sema::FRS_DiagnosticIssued;
2213 return Sema::FRS_Success;
2216 /// Speculatively attempt to dereference an invalid range expression.
2217 /// If the attempt fails, this function will return a valid, null StmtResult
2218 /// and emit no diagnostics.
2219 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2220 SourceLocation ForLoc,
2221 SourceLocation CoawaitLoc,
2223 SourceLocation ColonLoc,
2225 SourceLocation RangeLoc,
2226 SourceLocation RParenLoc) {
2227 // Determine whether we can rebuild the for-range statement with a
2228 // dereferenced range expression.
2229 ExprResult AdjustedRange;
2231 Sema::SFINAETrap Trap(SemaRef);
2233 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2234 if (AdjustedRange.isInvalid())
2235 return StmtResult();
2237 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2238 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2239 RParenLoc, Sema::BFRK_Check);
2241 return StmtResult();
2244 // The attempt to dereference worked well enough that it could produce a valid
2245 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2246 // case there are any other (non-fatal) problems with it.
2247 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2248 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2249 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2250 ColonLoc, AdjustedRange.get(), RParenLoc,
2251 Sema::BFRK_Rebuild);
2255 /// RAII object to automatically invalidate a declaration if an error occurs.
2256 struct InvalidateOnErrorScope {
2257 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2258 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2259 ~InvalidateOnErrorScope() {
2260 if (Enabled && Trap.hasErrorOccurred())
2261 D->setInvalidDecl();
2264 DiagnosticErrorTrap Trap;
2270 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2272 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2273 SourceLocation ColonLoc, Stmt *RangeDecl,
2274 Stmt *Begin, Stmt *End, Expr *Cond,
2275 Expr *Inc, Stmt *LoopVarDecl,
2276 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2277 // FIXME: This should not be used during template instantiation. We should
2278 // pick up the set of unqualified lookup results for the != and + operators
2279 // in the initial parse.
2281 // Testcase (accepts-invalid):
2282 // template<typename T> void f() { for (auto x : T()) {} }
2283 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2284 // bool operator!=(N::X, N::X); void operator++(N::X);
2285 // void g() { f<N::X>(); }
2286 Scope *S = getCurScope();
2288 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2289 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2290 QualType RangeVarType = RangeVar->getType();
2292 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2293 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2295 // If we hit any errors, mark the loop variable as invalid if its type
2297 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2298 LoopVar->getType()->isUndeducedType());
2300 StmtResult BeginDeclStmt = Begin;
2301 StmtResult EndDeclStmt = End;
2302 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2304 if (RangeVarType->isDependentType()) {
2305 // The range is implicitly used as a placeholder when it is dependent.
2306 RangeVar->markUsed(Context);
2308 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2309 // them in properly when we instantiate the loop.
2310 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2311 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2312 for (auto *Binding : DD->bindings())
2313 Binding->setType(Context.DependentTy);
2314 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2316 } else if (!BeginDeclStmt.get()) {
2317 SourceLocation RangeLoc = RangeVar->getLocation();
2319 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2321 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2322 VK_LValue, ColonLoc);
2323 if (BeginRangeRef.isInvalid())
2326 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2327 VK_LValue, ColonLoc);
2328 if (EndRangeRef.isInvalid())
2331 QualType AutoType = Context.getAutoDeductType();
2332 Expr *Range = RangeVar->getInit();
2335 QualType RangeType = Range->getType();
2337 if (RequireCompleteType(RangeLoc, RangeType,
2338 diag::err_for_range_incomplete_type))
2341 // Build auto __begin = begin-expr, __end = end-expr.
2342 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2344 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2347 // Build begin-expr and end-expr and attach to __begin and __end variables.
2348 ExprResult BeginExpr, EndExpr;
2349 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2350 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2351 // __range + __bound, respectively, where __bound is the array bound. If
2352 // _RangeT is an array of unknown size or an array of incomplete type,
2353 // the program is ill-formed;
2355 // begin-expr is __range.
2356 BeginExpr = BeginRangeRef;
2357 if (!CoawaitLoc.isInvalid()) {
2358 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2359 if (BeginExpr.isInvalid())
2362 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2363 diag::err_for_range_iter_deduction_failure)) {
2364 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2368 // Find the array bound.
2369 ExprResult BoundExpr;
2370 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2371 BoundExpr = IntegerLiteral::Create(
2372 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2373 else if (const VariableArrayType *VAT =
2374 dyn_cast<VariableArrayType>(UnqAT)) {
2375 // For a variably modified type we can't just use the expression within
2376 // the array bounds, since we don't want that to be re-evaluated here.
2377 // Rather, we need to determine what it was when the array was first
2378 // created - so we resort to using sizeof(vla)/sizeof(element).
2382 // b = -1; <-- This should not affect the num of iterations below
2383 // for (int &c : vla) { .. }
2386 // FIXME: This results in codegen generating IR that recalculates the
2387 // run-time number of elements (as opposed to just using the IR Value
2388 // that corresponds to the run-time value of each bound that was
2389 // generated when the array was created.) If this proves too embarassing
2390 // even for unoptimized IR, consider passing a magic-value/cookie to
2391 // codegen that then knows to simply use that initial llvm::Value (that
2392 // corresponds to the bound at time of array creation) within
2393 // getelementptr. But be prepared to pay the price of increasing a
2394 // customized form of coupling between the two components - which could
2395 // be hard to maintain as the codebase evolves.
2397 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2398 EndVar->getLocation(), UETT_SizeOf,
2400 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2401 VAT->desugar(), RangeLoc))
2403 EndVar->getSourceRange());
2404 if (SizeOfVLAExprR.isInvalid())
2407 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2408 EndVar->getLocation(), UETT_SizeOf,
2410 CreateParsedType(VAT->desugar(),
2411 Context.getTrivialTypeSourceInfo(
2412 VAT->getElementType(), RangeLoc))
2414 EndVar->getSourceRange());
2415 if (SizeOfEachElementExprR.isInvalid())
2419 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2420 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2421 if (BoundExpr.isInvalid())
2425 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2426 // UnqAT is not incomplete and Range is not type-dependent.
2427 llvm_unreachable("Unexpected array type in for-range");
2430 // end-expr is __range + __bound.
2431 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2433 if (EndExpr.isInvalid())
2435 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2436 diag::err_for_range_iter_deduction_failure)) {
2437 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2441 OverloadCandidateSet CandidateSet(RangeLoc,
2442 OverloadCandidateSet::CSK_Normal);
2443 BeginEndFunction BEFFailure;
2444 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2445 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2446 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2449 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2450 BEFFailure == BEF_begin) {
2451 // If the range is being built from an array parameter, emit a
2452 // a diagnostic that it is being treated as a pointer.
2453 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2454 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2455 QualType ArrayTy = PVD->getOriginalType();
2456 QualType PointerTy = PVD->getType();
2457 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2458 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2459 << RangeLoc << PVD << ArrayTy << PointerTy;
2460 Diag(PVD->getLocation(), diag::note_declared_at);
2466 // If building the range failed, try dereferencing the range expression
2467 // unless a diagnostic was issued or the end function is problematic.
2468 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2470 LoopVarDecl, ColonLoc,
2473 if (SR.isInvalid() || SR.isUsable())
2477 // Otherwise, emit diagnostics if we haven't already.
2478 if (RangeStatus == FRS_NoViableFunction) {
2479 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2480 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2481 << RangeLoc << Range->getType() << BEFFailure;
2482 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2484 // Return an error if no fix was discovered.
2485 if (RangeStatus != FRS_Success)
2489 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2490 "invalid range expression in for loop");
2492 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2493 // C++1z removes this restriction.
2494 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2495 if (!Context.hasSameType(BeginType, EndType)) {
2496 Diag(RangeLoc, getLangOpts().CPlusPlus17
2497 ? diag::warn_for_range_begin_end_types_differ
2498 : diag::ext_for_range_begin_end_types_differ)
2499 << BeginType << EndType;
2500 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2501 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2505 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2507 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2509 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2510 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2511 VK_LValue, ColonLoc);
2512 if (BeginRef.isInvalid())
2515 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2516 VK_LValue, ColonLoc);
2517 if (EndRef.isInvalid())
2520 // Build and check __begin != __end expression.
2521 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2522 BeginRef.get(), EndRef.get());
2523 if (!NotEqExpr.isInvalid())
2524 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2525 if (!NotEqExpr.isInvalid())
2526 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2527 if (NotEqExpr.isInvalid()) {
2528 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2529 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2530 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2531 if (!Context.hasSameType(BeginType, EndType))
2532 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2536 // Build and check ++__begin expression.
2537 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2538 VK_LValue, ColonLoc);
2539 if (BeginRef.isInvalid())
2542 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2543 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2544 // FIXME: getCurScope() should not be used during template instantiation.
2545 // We should pick up the set of unqualified lookup results for operator
2546 // co_await during the initial parse.
2547 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2548 if (!IncrExpr.isInvalid())
2549 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2550 if (IncrExpr.isInvalid()) {
2551 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2552 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2553 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2557 // Build and check *__begin expression.
2558 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2559 VK_LValue, ColonLoc);
2560 if (BeginRef.isInvalid())
2563 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2564 if (DerefExpr.isInvalid()) {
2565 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2566 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2567 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2571 // Attach *__begin as initializer for VD. Don't touch it if we're just
2572 // trying to determine whether this would be a valid range.
2573 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2574 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2575 if (LoopVar->isInvalidDecl())
2576 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2580 // Don't bother to actually allocate the result if we're just trying to
2581 // determine whether it would be valid.
2582 if (Kind == BFRK_Check)
2583 return StmtResult();
2585 return new (Context) CXXForRangeStmt(
2586 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2587 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2588 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2589 ColonLoc, RParenLoc);
2592 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2594 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2597 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2599 ForStmt->setBody(B);
2603 // Warn when the loop variable is a const reference that creates a copy.
2604 // Suggest using the non-reference type for copies. If a copy can be prevented
2605 // suggest the const reference type that would do so.
2606 // For instance, given "for (const &Foo : Range)", suggest
2607 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2608 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2609 // the copy altogether.
2610 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2612 QualType RangeInitType) {
2613 const Expr *InitExpr = VD->getInit();
2617 QualType VariableType = VD->getType();
2619 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2620 if (!Cleanups->cleanupsHaveSideEffects())
2621 InitExpr = Cleanups->getSubExpr();
2623 const MaterializeTemporaryExpr *MTE =
2624 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2630 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2632 // Searching for either UnaryOperator for dereference of a pointer or
2633 // CXXOperatorCallExpr for handling iterators.
2634 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2635 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2637 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2638 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2641 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2642 E = MTE->GetTemporaryExpr();
2644 E = E->IgnoreImpCasts();
2647 bool ReturnsReference = false;
2648 if (isa<UnaryOperator>(E)) {
2649 ReturnsReference = true;
2651 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2652 const FunctionDecl *FD = Call->getDirectCallee();
2653 QualType ReturnType = FD->getReturnType();
2654 ReturnsReference = ReturnType->isReferenceType();
2657 if (ReturnsReference) {
2658 // Loop variable creates a temporary. Suggest either to go with
2659 // non-reference loop variable to indiciate a copy is made, or
2660 // the correct time to bind a const reference.
2661 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2662 << VD << VariableType << E->getType();
2663 QualType NonReferenceType = VariableType.getNonReferenceType();
2664 NonReferenceType.removeLocalConst();
2665 QualType NewReferenceType =
2666 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2667 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2668 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2670 // The range always returns a copy, so a temporary is always created.
2671 // Suggest removing the reference from the loop variable.
2672 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2673 << VD << RangeInitType;
2674 QualType NonReferenceType = VariableType.getNonReferenceType();
2675 NonReferenceType.removeLocalConst();
2676 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2677 << NonReferenceType << VD->getSourceRange();
2681 // Warns when the loop variable can be changed to a reference type to
2682 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2683 // "for (const Foo &x : Range)" if this form does not make a copy.
2684 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2685 const VarDecl *VD) {
2686 const Expr *InitExpr = VD->getInit();
2690 QualType VariableType = VD->getType();
2692 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2693 if (!CE->getConstructor()->isCopyConstructor())
2695 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2696 if (CE->getCastKind() != CK_LValueToRValue)
2702 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2703 // should be emitted. Also, only ignore POD types with trivial copy
2705 if (VariableType.isPODType(SemaRef.Context))
2708 // Suggest changing from a const variable to a const reference variable
2709 // if doing so will prevent a copy.
2710 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2711 << VD << VariableType << InitExpr->getType();
2712 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2713 << SemaRef.Context.getLValueReferenceType(VariableType)
2714 << VD->getSourceRange();
2717 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2718 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2719 /// using "const foo x" to show that a copy is made
2720 /// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2721 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2722 /// prevent the copy.
2723 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2724 /// Suggest "const foo &x" to prevent the copy.
2725 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2726 const CXXForRangeStmt *ForStmt) {
2727 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2728 ForStmt->getLocStart()) &&
2729 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2730 ForStmt->getLocStart()) &&
2731 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2732 ForStmt->getLocStart())) {
2736 const VarDecl *VD = ForStmt->getLoopVariable();
2740 QualType VariableType = VD->getType();
2742 if (VariableType->isIncompleteType())
2745 const Expr *InitExpr = VD->getInit();
2749 if (VariableType->isReferenceType()) {
2750 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2751 ForStmt->getRangeInit()->getType());
2752 } else if (VariableType.isConstQualified()) {
2753 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2757 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2758 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2759 /// body cannot be performed until after the type of the range variable is
2761 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2765 if (isa<ObjCForCollectionStmt>(S))
2766 return FinishObjCForCollectionStmt(S, B);
2768 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2769 ForStmt->setBody(B);
2771 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2772 diag::warn_empty_range_based_for_body);
2774 DiagnoseForRangeVariableCopies(*this, ForStmt);
2779 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2780 SourceLocation LabelLoc,
2781 LabelDecl *TheDecl) {
2782 getCurFunction()->setHasBranchIntoScope();
2783 TheDecl->markUsed(Context);
2784 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2788 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2790 // Convert operand to void*
2791 if (!E->isTypeDependent()) {
2792 QualType ETy = E->getType();
2793 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2794 ExprResult ExprRes = E;
2795 AssignConvertType ConvTy =
2796 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2797 if (ExprRes.isInvalid())
2800 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2804 ExprResult ExprRes = ActOnFinishFullExpr(E);
2805 if (ExprRes.isInvalid())
2809 getCurFunction()->setHasIndirectGoto();
2811 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2814 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2815 const Scope &DestScope) {
2816 if (!S.CurrentSEHFinally.empty() &&
2817 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2818 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2823 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2824 Scope *S = CurScope->getContinueParent();
2826 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2827 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2829 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2831 return new (Context) ContinueStmt(ContinueLoc);
2835 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2836 Scope *S = CurScope->getBreakParent();
2838 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2839 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2841 if (S->isOpenMPLoopScope())
2842 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2844 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2846 return new (Context) BreakStmt(BreakLoc);
2849 /// \brief Determine whether the given expression is a candidate for
2850 /// copy elision in either a return statement or a throw expression.
2852 /// \param ReturnType If we're determining the copy elision candidate for
2853 /// a return statement, this is the return type of the function. If we're
2854 /// determining the copy elision candidate for a throw expression, this will
2857 /// \param E The expression being returned from the function or block, or
2860 /// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2861 /// id-expressions that could be moved out of the function to be considered NRVO
2862 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2863 /// determine whether we should try to move as part of a return or throw (which
2864 /// does allow function parameters).
2866 /// \returns The NRVO candidate variable, if the return statement may use the
2867 /// NRVO, or NULL if there is no such candidate.
2868 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2869 bool AllowParamOrMoveConstructible) {
2870 if (!getLangOpts().CPlusPlus)
2873 // - in a return statement in a function [where] ...
2874 // ... the expression is the name of a non-volatile automatic object ...
2875 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2876 if (!DR || DR->refersToEnclosingVariableOrCapture())
2878 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2882 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
2887 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2888 bool AllowParamOrMoveConstructible) {
2889 QualType VDType = VD->getType();
2890 // - in a return statement in a function with ...
2891 // ... a class return type ...
2892 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2893 if (!ReturnType->isRecordType())
2895 // ... the same cv-unqualified type as the function return type ...
2896 // When considering moving this expression out, allow dissimilar types.
2897 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
2898 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2902 // ...object (other than a function or catch-clause parameter)...
2903 if (VD->getKind() != Decl::Var &&
2904 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
2906 if (VD->isExceptionVariable()) return false;
2909 if (!VD->hasLocalStorage()) return false;
2911 // Return false if VD is a __block variable. We don't want to implicitly move
2912 // out of a __block variable during a return because we cannot assume the
2913 // variable will no longer be used.
2914 if (VD->hasAttr<BlocksAttr>()) return false;
2916 if (AllowParamOrMoveConstructible)
2919 // ...non-volatile...
2920 if (VD->getType().isVolatileQualified()) return false;
2922 // Variables with higher required alignment than their type's ABI
2923 // alignment cannot use NRVO.
2924 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2925 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2931 /// \brief Perform the initialization of a potentially-movable value, which
2932 /// is the result of return value.
2934 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2935 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2936 /// then falls back to treating them as lvalues if that failed.
2938 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2939 const VarDecl *NRVOCandidate,
2940 QualType ResultType,
2943 // C++14 [class.copy]p32:
2944 // When the criteria for elision of a copy/move operation are met, but not for
2945 // an exception-declaration, and the object to be copied is designated by an
2946 // lvalue, or when the expression in a return statement is a (possibly
2947 // parenthesized) id-expression that names an object with automatic storage
2948 // duration declared in the body or parameter-declaration-clause of the
2949 // innermost enclosing function or lambda-expression, overload resolution to
2950 // select the constructor for the copy is first performed as if the object
2951 // were designated by an rvalue.
2952 ExprResult Res = ExprError();
2954 if (AllowNRVO && !NRVOCandidate)
2955 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2957 if (AllowNRVO && NRVOCandidate) {
2958 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2959 CK_NoOp, Value, VK_XValue);
2961 Expr *InitExpr = &AsRvalue;
2963 InitializationKind Kind = InitializationKind::CreateCopy(
2964 Value->getLocStart(), Value->getLocStart());
2966 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2968 for (const InitializationSequence::Step &Step : Seq.steps()) {
2970 InitializationSequence::SK_ConstructorInitialization ||
2971 (Step.Kind == InitializationSequence::SK_UserConversion &&
2972 isa<CXXConstructorDecl>(Step.Function.Function))))
2975 CXXConstructorDecl *Constructor =
2976 cast<CXXConstructorDecl>(Step.Function.Function);
2978 const RValueReferenceType *RRefType
2979 = Constructor->getParamDecl(0)->getType()
2980 ->getAs<RValueReferenceType>();
2982 // [...] If the first overload resolution fails or was not performed, or
2983 // if the type of the first parameter of the selected constructor is not
2984 // an rvalue reference to the object's type (possibly cv-qualified),
2985 // overload resolution is performed again, considering the object as an
2988 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2989 NRVOCandidate->getType()))
2992 // Promote "AsRvalue" to the heap, since we now need this
2993 // expression node to persist.
2994 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2995 Value, nullptr, VK_XValue);
2997 // Complete type-checking the initialization of the return type
2998 // using the constructor we found.
2999 Res = Seq.Perform(*this, Entity, Kind, Value);
3004 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3005 // above, or overload resolution failed. Either way, we need to try
3006 // (again) now with the return value expression as written.
3007 if (Res.isInvalid())
3008 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3013 /// \brief Determine whether the declared return type of the specified function
3014 /// contains 'auto'.
3015 static bool hasDeducedReturnType(FunctionDecl *FD) {
3016 const FunctionProtoType *FPT =
3017 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3018 return FPT->getReturnType()->isUndeducedType();
3021 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3022 /// for capturing scopes.
3025 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3026 // If this is the first return we've seen, infer the return type.
3027 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3028 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3029 QualType FnRetType = CurCap->ReturnType;
3030 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3031 bool HasDeducedReturnType =
3032 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3034 if (ExprEvalContexts.back().Context ==
3035 ExpressionEvaluationContext::DiscardedStatement &&
3036 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3038 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3041 RetValExp = ER.get();
3043 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3046 if (HasDeducedReturnType) {
3047 // In C++1y, the return type may involve 'auto'.
3048 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3049 FunctionDecl *FD = CurLambda->CallOperator;
3050 if (CurCap->ReturnType.isNull())
3051 CurCap->ReturnType = FD->getReturnType();
3053 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3054 assert(AT && "lost auto type from lambda return type");
3055 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3056 FD->setInvalidDecl();
3059 CurCap->ReturnType = FnRetType = FD->getReturnType();
3060 } else if (CurCap->HasImplicitReturnType) {
3061 // For blocks/lambdas with implicit return types, we check each return
3062 // statement individually, and deduce the common return type when the block
3063 // or lambda is completed.
3064 // FIXME: Fold this into the 'auto' codepath above.
3065 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3066 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3067 if (Result.isInvalid())
3069 RetValExp = Result.get();
3071 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3072 // when deducing a return type for a lambda-expression (or by extension
3073 // for a block). These rules differ from the stated C++11 rules only in
3074 // that they remove top-level cv-qualifiers.
3075 if (!CurContext->isDependentContext())
3076 FnRetType = RetValExp->getType().getUnqualifiedType();
3078 FnRetType = CurCap->ReturnType = Context.DependentTy;
3081 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3082 // initializer list, because it is not an expression (even
3083 // though we represent it as one). We still deduce 'void'.
3084 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3085 << RetValExp->getSourceRange();
3088 FnRetType = Context.VoidTy;
3091 // Although we'll properly infer the type of the block once it's completed,
3092 // make sure we provide a return type now for better error recovery.
3093 if (CurCap->ReturnType.isNull())
3094 CurCap->ReturnType = FnRetType;
3096 assert(!FnRetType.isNull());
3098 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3099 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3100 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3103 } else if (CapturedRegionScopeInfo *CurRegion =
3104 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3105 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3108 assert(CurLambda && "unknown kind of captured scope");
3109 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3110 ->getNoReturnAttr()) {
3111 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3116 // Otherwise, verify that this result type matches the previous one. We are
3117 // pickier with blocks than for normal functions because we don't have GCC
3118 // compatibility to worry about here.
3119 const VarDecl *NRVOCandidate = nullptr;
3120 if (FnRetType->isDependentType()) {
3121 // Delay processing for now. TODO: there are lots of dependent
3122 // types we can conclusively prove aren't void.
3123 } else if (FnRetType->isVoidType()) {
3124 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3125 !(getLangOpts().CPlusPlus &&
3126 (RetValExp->isTypeDependent() ||
3127 RetValExp->getType()->isVoidType()))) {
3128 if (!getLangOpts().CPlusPlus &&
3129 RetValExp->getType()->isVoidType())
3130 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3132 Diag(ReturnLoc, diag::err_return_block_has_expr);
3133 RetValExp = nullptr;
3136 } else if (!RetValExp) {
3137 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3138 } else if (!RetValExp->isTypeDependent()) {
3139 // we have a non-void block with an expression, continue checking
3141 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3142 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3145 // In C++ the return statement is handled via a copy initialization.
3146 // the C version of which boils down to CheckSingleAssignmentConstraints.
3147 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3148 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3150 NRVOCandidate != nullptr);
3151 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3152 FnRetType, RetValExp);
3153 if (Res.isInvalid()) {
3154 // FIXME: Cleanup temporaries here, anyway?
3157 RetValExp = Res.get();
3158 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3160 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3164 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3167 RetValExp = ER.get();
3169 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3172 // If we need to check for the named return value optimization,
3173 // or if we need to infer the return type,
3174 // save the return statement in our scope for later processing.
3175 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3176 FunctionScopes.back()->Returns.push_back(Result);
3178 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3179 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3185 /// \brief Marks all typedefs in all local classes in a type referenced.
3187 /// In a function like
3189 /// struct S { typedef int a; };
3193 /// the local type escapes and could be referenced in some TUs but not in
3194 /// others. Pretend that all local typedefs are always referenced, to not warn
3195 /// on this. This isn't necessary if f has internal linkage, or the typedef
3197 class LocalTypedefNameReferencer
3198 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3200 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3201 bool VisitRecordType(const RecordType *RT);
3205 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3206 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3207 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3208 R->isDependentType())
3210 for (auto *TmpD : R->decls())
3211 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3212 if (T->getAccess() != AS_private || R->hasFriends())
3213 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3218 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3219 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3220 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3221 TL = ATL.getModifiedLoc().IgnoreParens();
3222 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3225 /// Deduce the return type for a function from a returned expression, per
3226 /// C++1y [dcl.spec.auto]p6.
3227 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3228 SourceLocation ReturnLoc,
3231 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3234 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3235 // If the deduction is for a return statement and the initializer is
3236 // a braced-init-list, the program is ill-formed.
3237 Diag(RetExpr->getExprLoc(),
3238 getCurLambda() ? diag::err_lambda_return_init_list
3239 : diag::err_auto_fn_return_init_list)
3240 << RetExpr->getSourceRange();
3244 if (FD->isDependentContext()) {
3245 // C++1y [dcl.spec.auto]p12:
3246 // Return type deduction [...] occurs when the definition is
3247 // instantiated even if the function body contains a return
3248 // statement with a non-type-dependent operand.
3249 assert(AT->isDeduced() && "should have deduced to dependent type");
3254 // Otherwise, [...] deduce a value for U using the rules of template
3255 // argument deduction.
3256 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3258 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3259 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3260 << OrigResultType.getType() << RetExpr->getType();
3262 if (DAR != DAR_Succeeded)
3265 // If a local type is part of the returned type, mark its fields as
3267 LocalTypedefNameReferencer Referencer(*this);
3268 Referencer.TraverseType(RetExpr->getType());
3270 // In the case of a return with no operand, the initializer is considered
3273 // Deduction here can only succeed if the return type is exactly 'cv auto'
3274 // or 'decltype(auto)', so just check for that case directly.
3275 if (!OrigResultType.getType()->getAs<AutoType>()) {
3276 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3277 << OrigResultType.getType();
3280 // We always deduce U = void in this case.
3281 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3282 if (Deduced.isNull())
3286 // If a function with a declared return type that contains a placeholder type
3287 // has multiple return statements, the return type is deduced for each return
3288 // statement. [...] if the type deduced is not the same in each deduction,
3289 // the program is ill-formed.
3290 QualType DeducedT = AT->getDeducedType();
3291 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3292 AutoType *NewAT = Deduced->getContainedAutoType();
3293 // It is possible that NewAT->getDeducedType() is null. When that happens,
3294 // we should not crash, instead we ignore this deduction.
3295 if (NewAT->getDeducedType().isNull())
3298 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3300 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3301 NewAT->getDeducedType());
3302 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3303 const LambdaScopeInfo *LambdaSI = getCurLambda();
3304 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3305 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3306 << NewAT->getDeducedType() << DeducedT
3307 << true /*IsLambda*/;
3309 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3310 << (AT->isDecltypeAuto() ? 1 : 0)
3311 << NewAT->getDeducedType() << DeducedT;
3315 } else if (!FD->isInvalidDecl()) {
3316 // Update all declarations of the function to have the deduced return type.
3317 Context.adjustDeducedFunctionResultType(FD, Deduced);
3324 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3326 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3327 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3328 ExpressionEvaluationContext::DiscardedStatement)
3332 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3333 CurScope->addNRVOCandidate(VD);
3335 CurScope->setNoNRVO();
3338 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3343 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3344 // Check for unexpanded parameter packs.
3345 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3348 if (isa<CapturingScopeInfo>(getCurFunction()))
3349 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3352 QualType RelatedRetType;
3353 const AttrVec *Attrs = nullptr;
3354 bool isObjCMethod = false;
3356 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3357 FnRetType = FD->getReturnType();
3359 Attrs = &FD->getAttrs();
3360 if (FD->isNoReturn())
3361 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3362 << FD->getDeclName();
3363 if (FD->isMain() && RetValExp)
3364 if (isa<CXXBoolLiteralExpr>(RetValExp))
3365 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3366 << RetValExp->getSourceRange();
3367 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3368 FnRetType = MD->getReturnType();
3369 isObjCMethod = true;
3371 Attrs = &MD->getAttrs();
3372 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3373 // In the implementation of a method with a related return type, the
3374 // type used to type-check the validity of return statements within the
3375 // method body is a pointer to the type of the class being implemented.
3376 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3377 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3379 } else // If we don't have a function/method context, bail.
3382 // C++1z: discarded return statements are not considered when deducing a
3384 if (ExprEvalContexts.back().Context ==
3385 ExpressionEvaluationContext::DiscardedStatement &&
3386 FnRetType->getContainedAutoType()) {
3388 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3391 RetValExp = ER.get();
3393 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3396 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3398 if (getLangOpts().CPlusPlus14) {
3399 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3400 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3401 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3402 FD->setInvalidDecl();
3405 FnRetType = FD->getReturnType();
3410 bool HasDependentReturnType = FnRetType->isDependentType();
3412 ReturnStmt *Result = nullptr;
3413 if (FnRetType->isVoidType()) {
3415 if (isa<InitListExpr>(RetValExp)) {
3416 // We simply never allow init lists as the return value of void
3417 // functions. This is compatible because this was never allowed before,
3418 // so there's no legacy code to deal with.
3419 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3420 int FunctionKind = 0;
3421 if (isa<ObjCMethodDecl>(CurDecl))
3423 else if (isa<CXXConstructorDecl>(CurDecl))
3425 else if (isa<CXXDestructorDecl>(CurDecl))
3428 Diag(ReturnLoc, diag::err_return_init_list)
3429 << CurDecl->getDeclName() << FunctionKind
3430 << RetValExp->getSourceRange();
3432 // Drop the expression.
3433 RetValExp = nullptr;
3434 } else if (!RetValExp->isTypeDependent()) {
3435 // C99 6.8.6.4p1 (ext_ since GCC warns)
3436 unsigned D = diag::ext_return_has_expr;
3437 if (RetValExp->getType()->isVoidType()) {
3438 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3439 if (isa<CXXConstructorDecl>(CurDecl) ||
3440 isa<CXXDestructorDecl>(CurDecl))
3441 D = diag::err_ctor_dtor_returns_void;
3443 D = diag::ext_return_has_void_expr;
3446 ExprResult Result = RetValExp;
3447 Result = IgnoredValueConversions(Result.get());
3448 if (Result.isInvalid())
3450 RetValExp = Result.get();
3451 RetValExp = ImpCastExprToType(RetValExp,
3452 Context.VoidTy, CK_ToVoid).get();
3454 // return of void in constructor/destructor is illegal in C++.
3455 if (D == diag::err_ctor_dtor_returns_void) {
3456 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3458 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3459 << RetValExp->getSourceRange();
3461 // return (some void expression); is legal in C++.
3462 else if (D != diag::ext_return_has_void_expr ||
3463 !getLangOpts().CPlusPlus) {
3464 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3466 int FunctionKind = 0;
3467 if (isa<ObjCMethodDecl>(CurDecl))
3469 else if (isa<CXXConstructorDecl>(CurDecl))
3471 else if (isa<CXXDestructorDecl>(CurDecl))
3475 << CurDecl->getDeclName() << FunctionKind
3476 << RetValExp->getSourceRange();
3481 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3484 RetValExp = ER.get();
3488 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3489 } else if (!RetValExp && !HasDependentReturnType) {
3490 FunctionDecl *FD = getCurFunctionDecl();
3493 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3494 // C++11 [stmt.return]p2
3495 DiagID = diag::err_constexpr_return_missing_expr;
3496 FD->setInvalidDecl();
3497 } else if (getLangOpts().C99) {
3498 // C99 6.8.6.4p1 (ext_ since GCC warns)
3499 DiagID = diag::ext_return_missing_expr;
3502 DiagID = diag::warn_return_missing_expr;
3506 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3508 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3510 Result = new (Context) ReturnStmt(ReturnLoc);
3512 assert(RetValExp || HasDependentReturnType);
3513 const VarDecl *NRVOCandidate = nullptr;
3515 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3517 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3518 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3521 // In C++ the return statement is handled via a copy initialization,
3522 // the C version of which boils down to CheckSingleAssignmentConstraints.
3524 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3525 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3526 // we have a non-void function with an expression, continue checking
3527 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3529 NRVOCandidate != nullptr);
3530 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3531 RetType, RetValExp);
3532 if (Res.isInvalid()) {
3533 // FIXME: Clean up temporaries here anyway?
3536 RetValExp = Res.getAs<Expr>();
3538 // If we have a related result type, we need to implicitly
3539 // convert back to the formal result type. We can't pretend to
3540 // initialize the result again --- we might end double-retaining
3541 // --- so instead we initialize a notional temporary.
3542 if (!RelatedRetType.isNull()) {
3543 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3545 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3546 if (Res.isInvalid()) {
3547 // FIXME: Clean up temporaries here anyway?
3550 RetValExp = Res.getAs<Expr>();
3553 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3554 getCurFunctionDecl());
3558 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3561 RetValExp = ER.get();
3563 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3566 // If we need to check for the named return value optimization, save the
3567 // return statement in our scope for later processing.
3568 if (Result->getNRVOCandidate())
3569 FunctionScopes.back()->Returns.push_back(Result);
3571 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3572 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3578 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3579 SourceLocation RParen, Decl *Parm,
3581 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3582 if (Var && Var->isInvalidDecl())
3585 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3589 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3590 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3594 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3595 MultiStmtArg CatchStmts, Stmt *Finally) {
3596 if (!getLangOpts().ObjCExceptions)
3597 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3599 getCurFunction()->setHasBranchProtectedScope();
3600 unsigned NumCatchStmts = CatchStmts.size();
3601 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3602 NumCatchStmts, Finally);
3605 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3607 ExprResult Result = DefaultLvalueConversion(Throw);
3608 if (Result.isInvalid())
3611 Result = ActOnFinishFullExpr(Result.get());
3612 if (Result.isInvalid())
3614 Throw = Result.get();
3616 QualType ThrowType = Throw->getType();
3617 // Make sure the expression type is an ObjC pointer or "void *".
3618 if (!ThrowType->isDependentType() &&
3619 !ThrowType->isObjCObjectPointerType()) {
3620 const PointerType *PT = ThrowType->getAs<PointerType>();
3621 if (!PT || !PT->getPointeeType()->isVoidType())
3622 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3623 << Throw->getType() << Throw->getSourceRange());
3627 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3631 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3633 if (!getLangOpts().ObjCExceptions)
3634 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3637 // @throw without an expression designates a rethrow (which must occur
3638 // in the context of an @catch clause).
3639 Scope *AtCatchParent = CurScope;
3640 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3641 AtCatchParent = AtCatchParent->getParent();
3643 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3645 return BuildObjCAtThrowStmt(AtLoc, Throw);
3649 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3650 ExprResult result = DefaultLvalueConversion(operand);
3651 if (result.isInvalid())
3653 operand = result.get();
3655 // Make sure the expression type is an ObjC pointer or "void *".
3656 QualType type = operand->getType();
3657 if (!type->isDependentType() &&
3658 !type->isObjCObjectPointerType()) {
3659 const PointerType *pointerType = type->getAs<PointerType>();
3660 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3661 if (getLangOpts().CPlusPlus) {
3662 if (RequireCompleteType(atLoc, type,
3663 diag::err_incomplete_receiver_type))
3664 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3665 << type << operand->getSourceRange();
3667 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3668 if (result.isInvalid())
3670 if (!result.isUsable())
3671 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3672 << type << operand->getSourceRange();
3674 operand = result.get();
3676 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3677 << type << operand->getSourceRange();
3682 // The operand to @synchronized is a full-expression.
3683 return ActOnFinishFullExpr(operand);
3687 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3689 // We can't jump into or indirect-jump out of a @synchronized block.
3690 getCurFunction()->setHasBranchProtectedScope();
3691 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3694 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3695 /// and creates a proper catch handler from them.
3697 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3698 Stmt *HandlerBlock) {
3699 // There's nothing to test that ActOnExceptionDecl didn't already test.
3700 return new (Context)
3701 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3705 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3706 getCurFunction()->setHasBranchProtectedScope();
3707 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3711 class CatchHandlerType {
3713 unsigned IsPointer : 1;
3715 // This is a special constructor to be used only with DenseMapInfo's
3716 // getEmptyKey() and getTombstoneKey() functions.
3717 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3718 enum Unique { ForDenseMap };
3719 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3722 /// Used when creating a CatchHandlerType from a handler type; will determine
3723 /// whether the type is a pointer or reference and will strip off the top
3724 /// level pointer and cv-qualifiers.
3725 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3726 if (QT->isPointerType())
3729 if (IsPointer || QT->isReferenceType())
3730 QT = QT->getPointeeType();
3731 QT = QT.getUnqualifiedType();
3734 /// Used when creating a CatchHandlerType from a base class type; pretends the
3735 /// type passed in had the pointer qualifier, does not need to get an
3736 /// unqualified type.
3737 CatchHandlerType(QualType QT, bool IsPointer)
3738 : QT(QT), IsPointer(IsPointer) {}
3740 QualType underlying() const { return QT; }
3741 bool isPointer() const { return IsPointer; }
3743 friend bool operator==(const CatchHandlerType &LHS,
3744 const CatchHandlerType &RHS) {
3745 // If the pointer qualification does not match, we can return early.
3746 if (LHS.IsPointer != RHS.IsPointer)
3748 // Otherwise, check the underlying type without cv-qualifiers.
3749 return LHS.QT == RHS.QT;
3755 template <> struct DenseMapInfo<CatchHandlerType> {
3756 static CatchHandlerType getEmptyKey() {
3757 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3758 CatchHandlerType::ForDenseMap);
3761 static CatchHandlerType getTombstoneKey() {
3762 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3763 CatchHandlerType::ForDenseMap);
3766 static unsigned getHashValue(const CatchHandlerType &Base) {
3767 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3770 static bool isEqual(const CatchHandlerType &LHS,
3771 const CatchHandlerType &RHS) {
3778 class CatchTypePublicBases {
3780 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3781 const bool CheckAgainstPointer;
3783 CXXCatchStmt *FoundHandler;
3784 CanQualType FoundHandlerType;
3787 CatchTypePublicBases(
3789 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3790 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3791 FoundHandler(nullptr) {}
3793 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3794 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3796 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3797 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3798 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3799 const auto &M = TypesToCheck;
3800 auto I = M.find(Check);
3802 FoundHandler = I->second;
3803 FoundHandlerType = Ctx.getCanonicalType(S->getType());
3812 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3813 /// handlers and creates a try statement from them.
3814 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3815 ArrayRef<Stmt *> Handlers) {
3816 // Don't report an error if 'try' is used in system headers.
3817 if (!getLangOpts().CXXExceptions &&
3818 !getSourceManager().isInSystemHeader(TryLoc))
3819 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3821 // Exceptions aren't allowed in CUDA device code.
3822 if (getLangOpts().CUDA)
3823 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3824 << "try" << CurrentCUDATarget();
3826 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3827 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3829 sema::FunctionScopeInfo *FSI = getCurFunction();
3831 // C++ try is incompatible with SEH __try.
3832 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3833 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3834 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3837 const unsigned NumHandlers = Handlers.size();
3838 assert(!Handlers.empty() &&
3839 "The parser shouldn't call this if there are no handlers.");
3841 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3842 for (unsigned i = 0; i < NumHandlers; ++i) {
3843 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3845 // Diagnose when the handler is a catch-all handler, but it isn't the last
3846 // handler for the try block. [except.handle]p5. Also, skip exception
3847 // declarations that are invalid, since we can't usefully report on them.
3848 if (!H->getExceptionDecl()) {
3849 if (i < NumHandlers - 1)
3850 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3852 } else if (H->getExceptionDecl()->isInvalidDecl())
3855 // Walk the type hierarchy to diagnose when this type has already been
3856 // handled (duplication), or cannot be handled (derivation inversion). We
3857 // ignore top-level cv-qualifiers, per [except.handle]p3
3858 CatchHandlerType HandlerCHT =
3859 (QualType)Context.getCanonicalType(H->getCaughtType());
3861 // We can ignore whether the type is a reference or a pointer; we need the
3862 // underlying declaration type in order to get at the underlying record
3863 // decl, if there is one.
3864 QualType Underlying = HandlerCHT.underlying();
3865 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3866 if (!RD->hasDefinition())
3868 // Check that none of the public, unambiguous base classes are in the
3869 // map ([except.handle]p1). Give the base classes the same pointer
3870 // qualification as the original type we are basing off of. This allows
3871 // comparison against the handler type using the same top-level pointer
3872 // as the original type.
3874 Paths.setOrigin(RD);
3875 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3876 if (RD->lookupInBases(CTPB, Paths)) {
3877 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3878 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3879 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3880 diag::warn_exception_caught_by_earlier_handler)
3881 << H->getCaughtType();
3882 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3883 diag::note_previous_exception_handler)
3884 << Problem->getCaughtType();
3889 // Add the type the list of ones we have handled; diagnose if we've already
3891 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3893 const CXXCatchStmt *Problem = R.first->second;
3894 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3895 diag::warn_exception_caught_by_earlier_handler)
3896 << H->getCaughtType();
3897 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3898 diag::note_previous_exception_handler)
3899 << Problem->getCaughtType();
3903 FSI->setHasCXXTry(TryLoc);
3905 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3908 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3909 Stmt *TryBlock, Stmt *Handler) {
3910 assert(TryBlock && Handler);
3912 sema::FunctionScopeInfo *FSI = getCurFunction();
3914 // SEH __try is incompatible with C++ try. Borland appears to support this,
3916 if (!getLangOpts().Borland) {
3917 if (FSI->FirstCXXTryLoc.isValid()) {
3918 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3919 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3923 FSI->setHasSEHTry(TryLoc);
3925 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3926 // track if they use SEH.
3927 DeclContext *DC = CurContext;
3928 while (DC && !DC->isFunctionOrMethod())
3929 DC = DC->getParent();
3930 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3932 FD->setUsesSEHTry(true);
3934 Diag(TryLoc, diag::err_seh_try_outside_functions);
3936 // Reject __try on unsupported targets.
3937 if (!Context.getTargetInfo().isSEHTrySupported())
3938 Diag(TryLoc, diag::err_seh_try_unsupported);
3940 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
3944 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3947 assert(FilterExpr && Block);
3949 if(!FilterExpr->getType()->isIntegerType()) {
3950 return StmtError(Diag(FilterExpr->getExprLoc(),
3951 diag::err_filter_expression_integral)
3952 << FilterExpr->getType());
3955 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3958 void Sema::ActOnStartSEHFinallyBlock() {
3959 CurrentSEHFinally.push_back(CurScope);
3962 void Sema::ActOnAbortSEHFinallyBlock() {
3963 CurrentSEHFinally.pop_back();
3966 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
3968 CurrentSEHFinally.pop_back();
3969 return SEHFinallyStmt::Create(Context, Loc, Block);
3973 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3974 Scope *SEHTryParent = CurScope;
3975 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3976 SEHTryParent = SEHTryParent->getParent();
3978 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3979 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
3981 return new (Context) SEHLeaveStmt(Loc);
3984 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3986 NestedNameSpecifierLoc QualifierLoc,
3987 DeclarationNameInfo NameInfo,
3990 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3991 QualifierLoc, NameInfo,
3992 cast<CompoundStmt>(Nested));
3996 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3999 UnqualifiedId &Name,
4001 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4002 SS.getWithLocInContext(Context),
4003 GetNameFromUnqualifiedId(Name),
4008 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4009 unsigned NumParams) {
4010 DeclContext *DC = CurContext;
4011 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4012 DC = DC->getParent();
4014 RecordDecl *RD = nullptr;
4015 if (getLangOpts().CPlusPlus)
4016 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4019 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4021 RD->setCapturedRecord();
4024 RD->startDefinition();
4026 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4027 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4032 static void buildCapturedStmtCaptureList(
4033 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4034 SmallVectorImpl<Expr *> &CaptureInits,
4035 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
4037 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
4038 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
4040 if (Cap->isThisCapture()) {
4041 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
4042 CapturedStmt::VCK_This));
4043 CaptureInits.push_back(Cap->getInitExpr());
4045 } else if (Cap->isVLATypeCapture()) {
4047 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
4048 CaptureInits.push_back(nullptr);
4052 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
4053 Cap->isReferenceCapture()
4054 ? CapturedStmt::VCK_ByRef
4055 : CapturedStmt::VCK_ByCopy,
4056 Cap->getVariable()));
4057 CaptureInits.push_back(Cap->getInitExpr());
4061 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4062 CapturedRegionKind Kind,
4063 unsigned NumParams) {
4064 CapturedDecl *CD = nullptr;
4065 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4067 // Build the context parameter
4068 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4069 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4070 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4072 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4073 ImplicitParamDecl::CapturedContext);
4076 CD->setContextParam(0, Param);
4078 // Enter the capturing scope for this captured region.
4079 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4082 PushDeclContext(CurScope, CD);
4086 PushExpressionEvaluationContext(
4087 ExpressionEvaluationContext::PotentiallyEvaluated);
4090 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4091 CapturedRegionKind Kind,
4092 ArrayRef<CapturedParamNameType> Params) {
4093 CapturedDecl *CD = nullptr;
4094 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4096 // Build the context parameter
4097 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4098 bool ContextIsFound = false;
4099 unsigned ParamNum = 0;
4100 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4102 I != E; ++I, ++ParamNum) {
4103 if (I->second.isNull()) {
4104 assert(!ContextIsFound &&
4105 "null type has been found already for '__context' parameter");
4106 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4107 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4109 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4110 ImplicitParamDecl::CapturedContext);
4112 CD->setContextParam(ParamNum, Param);
4113 ContextIsFound = true;
4115 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4117 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4118 ImplicitParamDecl::CapturedContext);
4120 CD->setParam(ParamNum, Param);
4123 assert(ContextIsFound && "no null type for '__context' parameter");
4124 if (!ContextIsFound) {
4125 // Add __context implicitly if it is not specified.
4126 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4127 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4129 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4130 ImplicitParamDecl::CapturedContext);
4132 CD->setContextParam(ParamNum, Param);
4134 // Enter the capturing scope for this captured region.
4135 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4138 PushDeclContext(CurScope, CD);
4142 PushExpressionEvaluationContext(
4143 ExpressionEvaluationContext::PotentiallyEvaluated);
4146 void Sema::ActOnCapturedRegionError() {
4147 DiscardCleanupsInEvaluationContext();
4148 PopExpressionEvaluationContext();
4150 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4151 RecordDecl *Record = RSI->TheRecordDecl;
4152 Record->setInvalidDecl();
4154 SmallVector<Decl*, 4> Fields(Record->fields());
4155 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4156 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
4159 PopFunctionScopeInfo();
4162 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4163 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4165 SmallVector<CapturedStmt::Capture, 4> Captures;
4166 SmallVector<Expr *, 4> CaptureInits;
4167 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4169 CapturedDecl *CD = RSI->TheCapturedDecl;
4170 RecordDecl *RD = RSI->TheRecordDecl;
4172 CapturedStmt *Res = CapturedStmt::Create(
4173 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4174 Captures, CaptureInits, CD, RD);
4176 CD->setBody(Res->getCapturedStmt());
4177 RD->completeDefinition();
4179 DiscardCleanupsInEvaluationContext();
4180 PopExpressionEvaluationContext();
4183 PopFunctionScopeInfo();