1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for statements.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/Ownership.h"
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/SmallVector.h"
42 using namespace clang;
45 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
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 /// 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 static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
200 SourceLocation Loc, SourceRange R1,
201 SourceRange R2, bool IsCtor) {
204 StringRef Msg = A->getMessage();
208 return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
209 return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
213 return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
215 return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
218 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
219 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
220 return DiagnoseUnusedExprResult(Label->getSubStmt());
222 const Expr *E = dyn_cast_or_null<Expr>(S);
226 // If we are in an unevaluated expression context, then there can be no unused
227 // results because the results aren't expected to be used in the first place.
228 if (isUnevaluatedContext())
231 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
232 // In most cases, we don't want to warn if the expression is written in a
233 // macro body, or if the macro comes from a system header. If the offending
234 // expression is a call to a function with the warn_unused_result attribute,
235 // we warn no matter the location. Because of the order in which the various
236 // checks need to happen, we factor out the macro-related test here.
237 bool ShouldSuppress =
238 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
239 SourceMgr.isInSystemMacro(ExprLoc);
241 const Expr *WarnExpr;
244 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
247 // If this is a GNU statement expression expanded from a macro, it is probably
248 // unused because it is a function-like macro that can be used as either an
249 // expression or statement. Don't warn, because it is almost certainly a
251 if (isa<StmtExpr>(E) && Loc.isMacroID())
254 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
255 // That macro is frequently used to suppress "unused parameter" warnings,
256 // but its implementation makes clang's -Wunused-value fire. Prevent this.
257 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
258 SourceLocation SpellLoc = Loc;
259 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
263 // Okay, we have an unused result. Depending on what the base expression is,
264 // we might want to make a more specific diagnostic. Check for one of these
266 unsigned DiagID = diag::warn_unused_expr;
267 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
268 E = Temps->getSubExpr();
269 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
270 E = TempExpr->getSubExpr();
272 if (DiagnoseUnusedComparison(*this, E))
276 if (const auto *Cast = dyn_cast<CastExpr>(E))
277 if (Cast->getCastKind() == CK_NoOp ||
278 Cast->getCastKind() == CK_ConstructorConversion)
279 E = Cast->getSubExpr()->IgnoreImpCasts();
281 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
282 if (E->getType()->isVoidType())
285 if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
286 CE->getUnusedResultAttr(Context)),
287 Loc, R1, R2, /*isCtor=*/false))
290 // If the callee has attribute pure, const, or warn_unused_result, warn with
291 // a more specific message to make it clear what is happening. If the call
292 // is written in a macro body, only warn if it has the warn_unused_result
294 if (const Decl *FD = CE->getCalleeDecl()) {
297 if (FD->hasAttr<PureAttr>()) {
298 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
301 if (FD->hasAttr<ConstAttr>()) {
302 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
306 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
307 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
308 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
309 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
310 if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
313 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
314 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
316 if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
317 R2, /*isCtor=*/false))
320 } else if (ShouldSuppress)
324 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
325 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
326 Diag(Loc, diag::err_arc_unused_init_message) << R1;
329 const ObjCMethodDecl *MD = ME->getMethodDecl();
331 if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
332 R2, /*isCtor=*/false))
335 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
336 const Expr *Source = POE->getSyntacticForm();
337 // Handle the actually selected call of an OpenMP specialized call.
338 if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
339 POE->getNumSemanticExprs() == 1 &&
340 isa<CallExpr>(POE->getSemanticExpr(0)))
341 return DiagnoseUnusedExprResult(POE->getSemanticExpr(0));
342 if (isa<ObjCSubscriptRefExpr>(Source))
343 DiagID = diag::warn_unused_container_subscript_expr;
345 DiagID = diag::warn_unused_property_expr;
346 } else if (const CXXFunctionalCastExpr *FC
347 = dyn_cast<CXXFunctionalCastExpr>(E)) {
348 const Expr *E = FC->getSubExpr();
349 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
350 E = TE->getSubExpr();
351 if (isa<CXXTemporaryObjectExpr>(E))
353 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
354 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
355 if (!RD->getAttr<WarnUnusedAttr>())
358 // Diagnose "(void*) blah" as a typo for "(void) blah".
359 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
360 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
361 QualType T = TI->getType();
363 // We really do want to use the non-canonical type here.
364 if (T == Context.VoidPtrTy) {
365 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
367 Diag(Loc, diag::warn_unused_voidptr)
368 << FixItHint::CreateRemoval(TL.getStarLoc());
373 // Tell the user to assign it into a variable to force a volatile load if this
375 if (E->isGLValue() && E->getType().isVolatileQualified() &&
376 !E->getType()->isArrayType()) {
377 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
381 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
384 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
385 PushCompoundScope(IsStmtExpr);
388 void Sema::ActOnFinishOfCompoundStmt() {
392 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
393 return getCurFunction()->CompoundScopes.back();
396 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
397 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
398 const unsigned NumElts = Elts.size();
400 // Mark the current function as usng floating point constrained intrinsics
401 if (getCurFPFeatures().isFPConstrained())
402 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext))
403 F->setUsesFPIntrin(true);
405 // If we're in C89 mode, check that we don't have any decls after stmts. If
406 // so, emit an extension diagnostic.
407 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
408 // Note that __extension__ can be around a decl.
410 // Skip over all declarations.
411 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
414 // We found the end of the list or a statement. Scan for another declstmt.
415 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
419 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
420 Diag(D->getLocation(), diag::ext_mixed_decls_code);
424 // Check for suspicious empty body (null statement) in `for' and `while'
425 // statements. Don't do anything for template instantiations, this just adds
427 if (NumElts != 0 && !CurrentInstantiationScope &&
428 getCurCompoundScope().HasEmptyLoopBodies) {
429 for (unsigned i = 0; i != NumElts - 1; ++i)
430 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
433 return CompoundStmt::Create(Context, Elts, L, R);
437 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
441 if (DiagnoseUnexpandedParameterPack(Val.get()))
444 // If we're not inside a switch, let the 'case' statement handling diagnose
445 // this. Just clean up after the expression as best we can.
446 if (getCurFunction()->SwitchStack.empty())
447 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
448 getLangOpts().CPlusPlus11);
451 getCurFunction()->SwitchStack.back().getPointer()->getCond();
454 QualType CondType = CondExpr->getType();
456 auto CheckAndFinish = [&](Expr *E) {
457 if (CondType->isDependentType() || E->isTypeDependent())
458 return ExprResult(E);
460 if (getLangOpts().CPlusPlus11) {
461 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
462 // constant expression of the promoted type of the switch condition.
463 llvm::APSInt TempVal;
464 return CheckConvertedConstantExpression(E, CondType, TempVal,
469 if (!E->isValueDependent())
470 ER = VerifyIntegerConstantExpression(E);
472 ER = DefaultLvalueConversion(ER.get());
474 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
476 ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
480 ExprResult Converted = CorrectDelayedTyposInExpr(
481 Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
483 if (Converted.get() == Val.get())
484 Converted = CheckAndFinish(Val.get());
489 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
490 SourceLocation DotDotDotLoc, ExprResult RHSVal,
491 SourceLocation ColonLoc) {
492 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
493 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
494 : RHSVal.isInvalid() || RHSVal.get()) &&
495 "missing RHS value");
497 if (getCurFunction()->SwitchStack.empty()) {
498 Diag(CaseLoc, diag::err_case_not_in_switch);
502 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
503 getCurFunction()->SwitchStack.back().setInt(true);
507 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
508 CaseLoc, DotDotDotLoc, ColonLoc);
509 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
513 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
514 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
515 cast<CaseStmt>(S)->setSubStmt(SubStmt);
519 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
520 Stmt *SubStmt, Scope *CurScope) {
521 if (getCurFunction()->SwitchStack.empty()) {
522 Diag(DefaultLoc, diag::err_default_not_in_switch);
526 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
527 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
532 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
533 SourceLocation ColonLoc, Stmt *SubStmt) {
534 // If the label was multiply defined, reject it now.
535 if (TheDecl->getStmt()) {
536 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
537 Diag(TheDecl->getLocation(), diag::note_previous_definition);
541 // Otherwise, things are good. Fill in the declaration and return it.
542 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
543 TheDecl->setStmt(LS);
544 if (!TheDecl->isGnuLocal()) {
545 TheDecl->setLocStart(IdentLoc);
546 if (!TheDecl->isMSAsmLabel()) {
547 // Don't update the location of MS ASM labels. These will result in
548 // a diagnostic, and changing the location here will mess that up.
549 TheDecl->setLocation(IdentLoc);
555 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
556 ArrayRef<const Attr*> Attrs,
558 // Fill in the declaration and return it.
559 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
564 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
565 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
568 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
569 void VisitBinaryOperator(BinaryOperator *E) {
570 if (E->getOpcode() == BO_Comma)
571 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
572 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
578 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
579 ConditionResult Cond,
580 Stmt *thenStmt, SourceLocation ElseLoc,
582 if (Cond.isInvalid())
583 Cond = ConditionResult(
585 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
586 Context.BoolTy, VK_RValue),
590 Expr *CondExpr = Cond.get().second;
591 // Only call the CommaVisitor when not C89 due to differences in scope flags.
592 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
593 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
594 CommaVisitor(*this).Visit(CondExpr);
597 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
598 diag::warn_empty_if_body);
600 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
604 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
605 Stmt *InitStmt, ConditionResult Cond,
606 Stmt *thenStmt, SourceLocation ElseLoc,
608 if (Cond.isInvalid())
611 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
612 setFunctionHasBranchProtectedScope();
614 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
615 Cond.get().second, thenStmt, ElseLoc, elseStmt);
619 struct CaseCompareFunctor {
620 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
621 const llvm::APSInt &RHS) {
622 return LHS.first < RHS;
624 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
625 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
626 return LHS.first < RHS.first;
628 bool operator()(const llvm::APSInt &LHS,
629 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
630 return LHS < RHS.first;
635 /// CmpCaseVals - Comparison predicate for sorting case values.
637 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
638 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
639 if (lhs.first < rhs.first)
642 if (lhs.first == rhs.first &&
643 lhs.second->getCaseLoc().getRawEncoding()
644 < rhs.second->getCaseLoc().getRawEncoding())
649 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
651 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
652 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
654 return lhs.first < rhs.first;
657 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
659 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
660 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
662 return lhs.first == rhs.first;
665 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
666 /// potentially integral-promoted expression @p expr.
667 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
668 if (const auto *FE = dyn_cast<FullExpr>(E))
669 E = FE->getSubExpr();
670 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
671 if (ImpCast->getCastKind() != CK_IntegralCast) break;
672 E = ImpCast->getSubExpr();
677 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
678 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
682 SwitchConvertDiagnoser(Expr *Cond)
683 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
686 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
687 QualType T) override {
688 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
691 SemaDiagnosticBuilder diagnoseIncomplete(
692 Sema &S, SourceLocation Loc, QualType T) override {
693 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
694 << T << Cond->getSourceRange();
697 SemaDiagnosticBuilder diagnoseExplicitConv(
698 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
699 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
702 SemaDiagnosticBuilder noteExplicitConv(
703 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
704 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
705 << ConvTy->isEnumeralType() << ConvTy;
708 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
709 QualType T) override {
710 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
713 SemaDiagnosticBuilder noteAmbiguous(
714 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
715 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
716 << ConvTy->isEnumeralType() << ConvTy;
719 SemaDiagnosticBuilder diagnoseConversion(
720 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
721 llvm_unreachable("conversion functions are permitted");
723 } SwitchDiagnoser(Cond);
725 ExprResult CondResult =
726 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
727 if (CondResult.isInvalid())
730 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
731 // failed and produced a diagnostic.
732 Cond = CondResult.get();
733 if (!Cond->isTypeDependent() &&
734 !Cond->getType()->isIntegralOrEnumerationType())
737 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
738 return UsualUnaryConversions(Cond);
741 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
742 Stmt *InitStmt, ConditionResult Cond) {
743 Expr *CondExpr = Cond.get().second;
744 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
746 if (CondExpr && !CondExpr->isTypeDependent()) {
747 // We have already converted the expression to an integral or enumeration
748 // type, when we parsed the switch condition. There are cases where we don't
749 // have an appropriate type, e.g. a typo-expr Cond was corrected to an
750 // inappropriate-type expr, we just return an error.
751 if (!CondExpr->getType()->isIntegralOrEnumerationType())
753 if (CondExpr->isKnownToHaveBooleanValue()) {
754 // switch(bool_expr) {...} is often a programmer error, e.g.
755 // switch(n && mask) { ... } // Doh - should be "n & mask".
756 // One can always use an if statement instead of switch(bool_expr).
757 Diag(SwitchLoc, diag::warn_bool_switch_condition)
758 << CondExpr->getSourceRange();
762 setFunctionHasBranchIntoScope();
764 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
765 getCurFunction()->SwitchStack.push_back(
766 FunctionScopeInfo::SwitchInfo(SS, false));
770 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
771 Val = Val.extOrTrunc(BitWidth);
772 Val.setIsSigned(IsSigned);
775 /// Check the specified case value is in range for the given unpromoted switch
777 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
778 unsigned UnpromotedWidth, bool UnpromotedSign) {
779 // In C++11 onwards, this is checked by the language rules.
780 if (S.getLangOpts().CPlusPlus11)
783 // If the case value was signed and negative and the switch expression is
784 // unsigned, don't bother to warn: this is implementation-defined behavior.
785 // FIXME: Introduce a second, default-ignored warning for this case?
786 if (UnpromotedWidth < Val.getBitWidth()) {
787 llvm::APSInt ConvVal(Val);
788 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
789 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
790 // FIXME: Use different diagnostics for overflow in conversion to promoted
791 // type versus "switch expression cannot have this value". Use proper
792 // IntRange checking rather than just looking at the unpromoted type here.
794 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
795 << ConvVal.toString(10);
799 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
801 /// Returns true if we should emit a diagnostic about this case expression not
802 /// being a part of the enum used in the switch controlling expression.
803 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
805 const Expr *CaseExpr,
806 EnumValsTy::iterator &EI,
807 EnumValsTy::iterator &EIEnd,
808 const llvm::APSInt &Val) {
812 if (const DeclRefExpr *DRE =
813 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
814 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
815 QualType VarType = VD->getType();
816 QualType EnumType = S.Context.getTypeDeclType(ED);
817 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
818 S.Context.hasSameUnqualifiedType(EnumType, VarType))
823 if (ED->hasAttr<FlagEnumAttr>())
824 return !S.IsValueInFlagEnum(ED, Val, false);
826 while (EI != EIEnd && EI->first < Val)
829 if (EI != EIEnd && EI->first == Val)
835 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
837 QualType CondType = Cond->getType();
838 QualType CaseType = Case->getType();
840 const EnumType *CondEnumType = CondType->getAs<EnumType>();
841 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
842 if (!CondEnumType || !CaseEnumType)
845 // Ignore anonymous enums.
846 if (!CondEnumType->getDecl()->getIdentifier() &&
847 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
849 if (!CaseEnumType->getDecl()->getIdentifier() &&
850 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
853 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
856 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
857 << CondType << CaseType << Cond->getSourceRange()
858 << Case->getSourceRange();
862 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
864 SwitchStmt *SS = cast<SwitchStmt>(Switch);
865 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
866 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
867 "switch stack missing push/pop!");
869 getCurFunction()->SwitchStack.pop_back();
871 if (!BodyStmt) return StmtError();
872 SS->setBody(BodyStmt, SwitchLoc);
874 Expr *CondExpr = SS->getCond();
875 if (!CondExpr) return StmtError();
877 QualType CondType = CondExpr->getType();
880 // Integral promotions are performed (on the switch condition).
882 // A case value unrepresentable by the original switch condition
883 // type (before the promotion) doesn't make sense, even when it can
884 // be represented by the promoted type. Therefore we need to find
885 // the pre-promotion type of the switch condition.
886 const Expr *CondExprBeforePromotion = CondExpr;
887 QualType CondTypeBeforePromotion =
888 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
890 // Get the bitwidth of the switched-on value after promotions. We must
891 // convert the integer case values to this width before comparison.
892 bool HasDependentValue
893 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
894 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
895 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
897 // Get the width and signedness that the condition might actually have, for
899 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
901 unsigned CondWidthBeforePromotion
902 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
903 bool CondIsSignedBeforePromotion
904 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
906 // Accumulate all of the case values in a vector so that we can sort them
907 // and detect duplicates. This vector contains the APInt for the case after
908 // it has been converted to the condition type.
909 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
912 // Keep track of any GNU case ranges we see. The APSInt is the low value.
913 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
914 CaseRangesTy CaseRanges;
916 DefaultStmt *TheDefaultStmt = nullptr;
918 bool CaseListIsErroneous = false;
920 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
921 SC = SC->getNextSwitchCase()) {
923 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
924 if (TheDefaultStmt) {
925 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
926 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
928 // FIXME: Remove the default statement from the switch block so that
929 // we'll return a valid AST. This requires recursing down the AST and
930 // finding it, not something we are set up to do right now. For now,
931 // just lop the entire switch stmt out of the AST.
932 CaseListIsErroneous = true;
937 CaseStmt *CS = cast<CaseStmt>(SC);
939 Expr *Lo = CS->getLHS();
941 if (Lo->isValueDependent()) {
942 HasDependentValue = true;
946 // We already verified that the expression has a constant value;
947 // get that value (prior to conversions).
948 const Expr *LoBeforePromotion = Lo;
949 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
950 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
952 // Check the unconverted value is within the range of possible values of
953 // the switch expression.
954 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
955 CondIsSignedBeforePromotion);
957 // FIXME: This duplicates the check performed for warn_not_in_enum below.
958 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
961 // Convert the value to the same width/sign as the condition.
962 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
964 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
966 if (CS->getRHS()->isValueDependent()) {
967 HasDependentValue = true;
970 CaseRanges.push_back(std::make_pair(LoVal, CS));
972 CaseVals.push_back(std::make_pair(LoVal, CS));
976 if (!HasDependentValue) {
977 // If we don't have a default statement, check whether the
978 // condition is constant.
979 llvm::APSInt ConstantCondValue;
980 bool HasConstantCond = false;
981 if (!TheDefaultStmt) {
982 Expr::EvalResult Result;
983 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
984 Expr::SE_AllowSideEffects);
985 if (Result.Val.isInt())
986 ConstantCondValue = Result.Val.getInt();
987 assert(!HasConstantCond ||
988 (ConstantCondValue.getBitWidth() == CondWidth &&
989 ConstantCondValue.isSigned() == CondIsSigned));
991 bool ShouldCheckConstantCond = HasConstantCond;
993 // Sort all the scalar case values so we can easily detect duplicates.
994 llvm::stable_sort(CaseVals, CmpCaseVals);
996 if (!CaseVals.empty()) {
997 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
998 if (ShouldCheckConstantCond &&
999 CaseVals[i].first == ConstantCondValue)
1000 ShouldCheckConstantCond = false;
1002 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
1003 // If we have a duplicate, report it.
1004 // First, determine if either case value has a name
1005 StringRef PrevString, CurrString;
1006 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
1007 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
1008 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
1009 PrevString = DeclRef->getDecl()->getName();
1011 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
1012 CurrString = DeclRef->getDecl()->getName();
1014 SmallString<16> CaseValStr;
1015 CaseVals[i-1].first.toString(CaseValStr);
1017 if (PrevString == CurrString)
1018 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1019 diag::err_duplicate_case)
1020 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
1022 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1023 diag::err_duplicate_case_differing_expr)
1024 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
1025 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
1028 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
1029 diag::note_duplicate_case_prev);
1030 // FIXME: We really want to remove the bogus case stmt from the
1031 // substmt, but we have no way to do this right now.
1032 CaseListIsErroneous = true;
1037 // Detect duplicate case ranges, which usually don't exist at all in
1039 if (!CaseRanges.empty()) {
1040 // Sort all the case ranges by their low value so we can easily detect
1041 // overlaps between ranges.
1042 llvm::stable_sort(CaseRanges);
1044 // Scan the ranges, computing the high values and removing empty ranges.
1045 std::vector<llvm::APSInt> HiVals;
1046 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1047 llvm::APSInt &LoVal = CaseRanges[i].first;
1048 CaseStmt *CR = CaseRanges[i].second;
1049 Expr *Hi = CR->getRHS();
1051 const Expr *HiBeforePromotion = Hi;
1052 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1053 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1055 // Check the unconverted value is within the range of possible values of
1056 // the switch expression.
1057 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1058 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1060 // Convert the value to the same width/sign as the condition.
1061 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1063 // If the low value is bigger than the high value, the case is empty.
1064 if (LoVal > HiVal) {
1065 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1066 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1067 CaseRanges.erase(CaseRanges.begin()+i);
1073 if (ShouldCheckConstantCond &&
1074 LoVal <= ConstantCondValue &&
1075 ConstantCondValue <= HiVal)
1076 ShouldCheckConstantCond = false;
1078 HiVals.push_back(HiVal);
1081 // Rescan the ranges, looking for overlap with singleton values and other
1082 // ranges. Since the range list is sorted, we only need to compare case
1083 // ranges with their neighbors.
1084 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1085 llvm::APSInt &CRLo = CaseRanges[i].first;
1086 llvm::APSInt &CRHi = HiVals[i];
1087 CaseStmt *CR = CaseRanges[i].second;
1089 // Check to see whether the case range overlaps with any
1091 CaseStmt *OverlapStmt = nullptr;
1092 llvm::APSInt OverlapVal(32);
1094 // Find the smallest value >= the lower bound. If I is in the
1095 // case range, then we have overlap.
1096 CaseValsTy::iterator I =
1097 llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1098 if (I != CaseVals.end() && I->first < CRHi) {
1099 OverlapVal = I->first; // Found overlap with scalar.
1100 OverlapStmt = I->second;
1103 // Find the smallest value bigger than the upper bound.
1104 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1105 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1106 OverlapVal = (I-1)->first; // Found overlap with scalar.
1107 OverlapStmt = (I-1)->second;
1110 // Check to see if this case stmt overlaps with the subsequent
1112 if (i && CRLo <= HiVals[i-1]) {
1113 OverlapVal = HiVals[i-1]; // Found overlap with range.
1114 OverlapStmt = CaseRanges[i-1].second;
1118 // If we have a duplicate, report it.
1119 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1120 << OverlapVal.toString(10);
1121 Diag(OverlapStmt->getLHS()->getBeginLoc(),
1122 diag::note_duplicate_case_prev);
1123 // FIXME: We really want to remove the bogus case stmt from the
1124 // substmt, but we have no way to do this right now.
1125 CaseListIsErroneous = true;
1130 // Complain if we have a constant condition and we didn't find a match.
1131 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1132 ShouldCheckConstantCond) {
1133 // TODO: it would be nice if we printed enums as enums, chars as
1135 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1136 << ConstantCondValue.toString(10)
1137 << CondExpr->getSourceRange();
1140 // Check to see if switch is over an Enum and handles all of its
1141 // values. We only issue a warning if there is not 'default:', but
1142 // we still do the analysis to preserve this information in the AST
1143 // (which can be used by flow-based analyes).
1145 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1147 // If switch has default case, then ignore it.
1148 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1149 ET && ET->getDecl()->isCompleteDefinition()) {
1150 const EnumDecl *ED = ET->getDecl();
1151 EnumValsTy EnumVals;
1153 // Gather all enum values, set their type and sort them,
1154 // allowing easier comparison with CaseVals.
1155 for (auto *EDI : ED->enumerators()) {
1156 llvm::APSInt Val = EDI->getInitVal();
1157 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1158 EnumVals.push_back(std::make_pair(Val, EDI));
1160 llvm::stable_sort(EnumVals, CmpEnumVals);
1161 auto EI = EnumVals.begin(), EIEnd =
1162 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1164 // See which case values aren't in enum.
1165 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1166 CI != CaseVals.end(); CI++) {
1167 Expr *CaseExpr = CI->second->getLHS();
1168 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1170 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1171 << CondTypeBeforePromotion;
1174 // See which of case ranges aren't in enum
1175 EI = EnumVals.begin();
1176 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1177 RI != CaseRanges.end(); RI++) {
1178 Expr *CaseExpr = RI->second->getLHS();
1179 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1181 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1182 << CondTypeBeforePromotion;
1185 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1186 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1188 CaseExpr = RI->second->getRHS();
1189 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1191 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1192 << CondTypeBeforePromotion;
1195 // Check which enum vals aren't in switch
1196 auto CI = CaseVals.begin();
1197 auto RI = CaseRanges.begin();
1198 bool hasCasesNotInSwitch = false;
1200 SmallVector<DeclarationName,8> UnhandledNames;
1202 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1203 // Don't warn about omitted unavailable EnumConstantDecls.
1204 switch (EI->second->getAvailability()) {
1206 // Omitting a deprecated constant is ok; it should never materialize.
1207 case AR_Unavailable:
1210 case AR_NotYetIntroduced:
1211 // Partially available enum constants should be present. Note that we
1212 // suppress -Wunguarded-availability diagnostics for such uses.
1217 if (EI->second->hasAttr<UnusedAttr>())
1220 // Drop unneeded case values
1221 while (CI != CaseVals.end() && CI->first < EI->first)
1224 if (CI != CaseVals.end() && CI->first == EI->first)
1227 // Drop unneeded case ranges
1228 for (; RI != CaseRanges.end(); RI++) {
1230 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1231 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1232 if (EI->first <= Hi)
1236 if (RI == CaseRanges.end() || EI->first < RI->first) {
1237 hasCasesNotInSwitch = true;
1238 UnhandledNames.push_back(EI->second->getDeclName());
1242 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1243 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1245 // Produce a nice diagnostic if multiple values aren't handled.
1246 if (!UnhandledNames.empty()) {
1247 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1248 TheDefaultStmt ? diag::warn_def_missing_case
1249 : diag::warn_missing_case)
1250 << (int)UnhandledNames.size();
1252 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1254 DB << UnhandledNames[I];
1257 if (!hasCasesNotInSwitch)
1258 SS->setAllEnumCasesCovered();
1263 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1264 diag::warn_empty_switch_body);
1266 // FIXME: If the case list was broken is some way, we don't have a good system
1267 // to patch it up. Instead, just return the whole substmt as broken.
1268 if (CaseListIsErroneous)
1275 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1277 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1280 if (const EnumType *ET = DstType->getAs<EnumType>())
1281 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1282 SrcType->isIntegerType()) {
1283 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1284 SrcExpr->isIntegerConstantExpr(Context)) {
1285 // Get the bitwidth of the enum value before promotions.
1286 unsigned DstWidth = Context.getIntWidth(DstType);
1287 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1289 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1290 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1291 const EnumDecl *ED = ET->getDecl();
1293 if (!ED->isClosed())
1296 if (ED->hasAttr<FlagEnumAttr>()) {
1297 if (!IsValueInFlagEnum(ED, RhsVal, true))
1298 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1299 << DstType.getUnqualifiedType();
1301 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1303 EnumValsTy EnumVals;
1305 // Gather all enum values, set their type and sort them,
1306 // allowing easier comparison with rhs constant.
1307 for (auto *EDI : ED->enumerators()) {
1308 llvm::APSInt Val = EDI->getInitVal();
1309 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1310 EnumVals.push_back(std::make_pair(Val, EDI));
1312 if (EnumVals.empty())
1314 llvm::stable_sort(EnumVals, CmpEnumVals);
1315 EnumValsTy::iterator EIend =
1316 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1318 // See which values aren't in the enum.
1319 EnumValsTy::const_iterator EI = EnumVals.begin();
1320 while (EI != EIend && EI->first < RhsVal)
1322 if (EI == EIend || EI->first != RhsVal) {
1323 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1324 << DstType.getUnqualifiedType();
1331 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
1332 SourceLocation LParenLoc, ConditionResult Cond,
1333 SourceLocation RParenLoc, Stmt *Body) {
1334 if (Cond.isInvalid())
1337 auto CondVal = Cond.get();
1338 CheckBreakContinueBinding(CondVal.second);
1340 if (CondVal.second &&
1341 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1342 CommaVisitor(*this).Visit(CondVal.second);
1344 if (isa<NullStmt>(Body))
1345 getCurCompoundScope().setHasEmptyLoopBodies();
1347 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1348 WhileLoc, LParenLoc, RParenLoc);
1352 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1353 SourceLocation WhileLoc, SourceLocation CondLParen,
1354 Expr *Cond, SourceLocation CondRParen) {
1355 assert(Cond && "ActOnDoStmt(): missing expression");
1357 CheckBreakContinueBinding(Cond);
1358 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1359 if (CondResult.isInvalid())
1361 Cond = CondResult.get();
1363 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1364 if (CondResult.isInvalid())
1366 Cond = CondResult.get();
1368 // Only call the CommaVisitor for C89 due to differences in scope flags.
1369 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1370 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1371 CommaVisitor(*this).Visit(Cond);
1373 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1377 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1378 using DeclSetVector =
1379 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1380 llvm::SmallPtrSet<VarDecl *, 8>>;
1382 // This visitor will traverse a conditional statement and store all
1383 // the evaluated decls into a vector. Simple is set to true if none
1384 // of the excluded constructs are used.
1385 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1386 DeclSetVector &Decls;
1387 SmallVectorImpl<SourceRange> &Ranges;
1390 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1392 DeclExtractor(Sema &S, DeclSetVector &Decls,
1393 SmallVectorImpl<SourceRange> &Ranges) :
1394 Inherited(S.Context),
1399 bool isSimple() { return Simple; }
1401 // Replaces the method in EvaluatedExprVisitor.
1402 void VisitMemberExpr(MemberExpr* E) {
1406 // Any Stmt not explicitly listed will cause the condition to be marked
1408 void VisitStmt(Stmt *S) { Simple = false; }
1410 void VisitBinaryOperator(BinaryOperator *E) {
1415 void VisitCastExpr(CastExpr *E) {
1416 Visit(E->getSubExpr());
1419 void VisitUnaryOperator(UnaryOperator *E) {
1420 // Skip checking conditionals with derefernces.
1421 if (E->getOpcode() == UO_Deref)
1424 Visit(E->getSubExpr());
1427 void VisitConditionalOperator(ConditionalOperator *E) {
1428 Visit(E->getCond());
1429 Visit(E->getTrueExpr());
1430 Visit(E->getFalseExpr());
1433 void VisitParenExpr(ParenExpr *E) {
1434 Visit(E->getSubExpr());
1437 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1438 Visit(E->getOpaqueValue()->getSourceExpr());
1439 Visit(E->getFalseExpr());
1442 void VisitIntegerLiteral(IntegerLiteral *E) { }
1443 void VisitFloatingLiteral(FloatingLiteral *E) { }
1444 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1445 void VisitCharacterLiteral(CharacterLiteral *E) { }
1446 void VisitGNUNullExpr(GNUNullExpr *E) { }
1447 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1449 void VisitDeclRefExpr(DeclRefExpr *E) {
1450 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1452 // Don't allow unhandled Decl types.
1457 Ranges.push_back(E->getSourceRange());
1462 }; // end class DeclExtractor
1464 // DeclMatcher checks to see if the decls are used in a non-evaluated
1466 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1467 DeclSetVector &Decls;
1471 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1473 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1474 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1475 if (!Statement) return;
1480 void VisitReturnStmt(ReturnStmt *S) {
1484 void VisitBreakStmt(BreakStmt *S) {
1488 void VisitGotoStmt(GotoStmt *S) {
1492 void VisitCastExpr(CastExpr *E) {
1493 if (E->getCastKind() == CK_LValueToRValue)
1494 CheckLValueToRValueCast(E->getSubExpr());
1496 Visit(E->getSubExpr());
1499 void CheckLValueToRValueCast(Expr *E) {
1500 E = E->IgnoreParenImpCasts();
1502 if (isa<DeclRefExpr>(E)) {
1506 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1507 Visit(CO->getCond());
1508 CheckLValueToRValueCast(CO->getTrueExpr());
1509 CheckLValueToRValueCast(CO->getFalseExpr());
1513 if (BinaryConditionalOperator *BCO =
1514 dyn_cast<BinaryConditionalOperator>(E)) {
1515 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1516 CheckLValueToRValueCast(BCO->getFalseExpr());
1523 void VisitDeclRefExpr(DeclRefExpr *E) {
1524 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1525 if (Decls.count(VD))
1529 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1530 // Only need to visit the semantics for POE.
1531 // SyntaticForm doesn't really use the Decal.
1532 for (auto *S : POE->semantics()) {
1533 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1534 // Look past the OVE into the expression it binds.
1535 Visit(OVE->getSourceExpr());
1541 bool FoundDeclInUse() { return FoundDecl; }
1543 }; // end class DeclMatcher
1545 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1546 Expr *Third, Stmt *Body) {
1547 // Condition is empty
1548 if (!Second) return;
1550 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1551 Second->getBeginLoc()))
1554 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1555 DeclSetVector Decls;
1556 SmallVector<SourceRange, 10> Ranges;
1557 DeclExtractor DE(S, Decls, Ranges);
1560 // Don't analyze complex conditionals.
1561 if (!DE.isSimple()) return;
1564 if (Decls.size() == 0) return;
1566 // Don't warn on volatile, static, or global variables.
1567 for (auto *VD : Decls)
1568 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1571 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1572 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1573 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1576 // Load decl names into diagnostic.
1577 if (Decls.size() > 4) {
1580 PDiag << (unsigned)Decls.size();
1581 for (auto *VD : Decls)
1582 PDiag << VD->getDeclName();
1585 for (auto Range : Ranges)
1588 S.Diag(Ranges.begin()->getBegin(), PDiag);
1591 // If Statement is an incemement or decrement, return true and sets the
1592 // variables Increment and DRE.
1593 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1594 DeclRefExpr *&DRE) {
1595 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1596 if (!Cleanups->cleanupsHaveSideEffects())
1597 Statement = Cleanups->getSubExpr();
1599 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1600 switch (UO->getOpcode()) {
1601 default: return false;
1611 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1615 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1616 FunctionDecl *FD = Call->getDirectCallee();
1617 if (!FD || !FD->isOverloadedOperator()) return false;
1618 switch (FD->getOverloadedOperator()) {
1619 default: return false;
1627 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1634 // A visitor to determine if a continue or break statement is a
1636 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1637 SourceLocation BreakLoc;
1638 SourceLocation ContinueLoc;
1639 bool InSwitch = false;
1642 BreakContinueFinder(Sema &S, const Stmt* Body) :
1643 Inherited(S.Context) {
1647 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1649 void VisitContinueStmt(const ContinueStmt* E) {
1650 ContinueLoc = E->getContinueLoc();
1653 void VisitBreakStmt(const BreakStmt* E) {
1655 BreakLoc = E->getBreakLoc();
1658 void VisitSwitchStmt(const SwitchStmt* S) {
1659 if (const Stmt *Init = S->getInit())
1661 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1663 if (const Stmt *Cond = S->getCond())
1666 // Don't return break statements from the body of a switch.
1668 if (const Stmt *Body = S->getBody())
1673 void VisitForStmt(const ForStmt *S) {
1674 // Only visit the init statement of a for loop; the body
1675 // has a different break/continue scope.
1676 if (const Stmt *Init = S->getInit())
1680 void VisitWhileStmt(const WhileStmt *) {
1681 // Do nothing; the children of a while loop have a different
1682 // break/continue scope.
1685 void VisitDoStmt(const DoStmt *) {
1686 // Do nothing; the children of a while loop have a different
1687 // break/continue scope.
1690 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1691 // Only visit the initialization of a for loop; the body
1692 // has a different break/continue scope.
1693 if (const Stmt *Init = S->getInit())
1695 if (const Stmt *Range = S->getRangeStmt())
1697 if (const Stmt *Begin = S->getBeginStmt())
1699 if (const Stmt *End = S->getEndStmt())
1703 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1704 // Only visit the initialization of a for loop; the body
1705 // has a different break/continue scope.
1706 if (const Stmt *Element = S->getElement())
1708 if (const Stmt *Collection = S->getCollection())
1712 bool ContinueFound() { return ContinueLoc.isValid(); }
1713 bool BreakFound() { return BreakLoc.isValid(); }
1714 SourceLocation GetContinueLoc() { return ContinueLoc; }
1715 SourceLocation GetBreakLoc() { return BreakLoc; }
1717 }; // end class BreakContinueFinder
1719 // Emit a warning when a loop increment/decrement appears twice per loop
1720 // iteration. The conditions which trigger this warning are:
1721 // 1) The last statement in the loop body and the third expression in the
1722 // for loop are both increment or both decrement of the same variable
1723 // 2) No continue statements in the loop body.
1724 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1725 // Return when there is nothing to check.
1726 if (!Body || !Third) return;
1728 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1729 Third->getBeginLoc()))
1732 // Get the last statement from the loop body.
1733 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1734 if (!CS || CS->body_empty()) return;
1735 Stmt *LastStmt = CS->body_back();
1736 if (!LastStmt) return;
1738 bool LoopIncrement, LastIncrement;
1739 DeclRefExpr *LoopDRE, *LastDRE;
1741 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1742 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1744 // Check that the two statements are both increments or both decrements
1745 // on the same variable.
1746 if (LoopIncrement != LastIncrement ||
1747 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1749 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1751 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1752 << LastDRE->getDecl() << LastIncrement;
1753 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1760 void Sema::CheckBreakContinueBinding(Expr *E) {
1761 if (!E || getLangOpts().CPlusPlus)
1763 BreakContinueFinder BCFinder(*this, E);
1764 Scope *BreakParent = CurScope->getBreakParent();
1765 if (BCFinder.BreakFound() && BreakParent) {
1766 if (BreakParent->getFlags() & Scope::SwitchScope) {
1767 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1769 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1772 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1773 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1778 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1779 Stmt *First, ConditionResult Second,
1780 FullExprArg third, SourceLocation RParenLoc,
1782 if (Second.isInvalid())
1785 if (!getLangOpts().CPlusPlus) {
1786 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1787 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1788 // declare identifiers for objects having storage class 'auto' or
1790 for (auto *DI : DS->decls()) {
1791 VarDecl *VD = dyn_cast<VarDecl>(DI);
1792 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1795 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1796 DI->setInvalidDecl();
1802 CheckBreakContinueBinding(Second.get().second);
1803 CheckBreakContinueBinding(third.get());
1805 if (!Second.get().first)
1806 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1808 CheckForRedundantIteration(*this, third.get(), Body);
1810 if (Second.get().second &&
1811 !Diags.isIgnored(diag::warn_comma_operator,
1812 Second.get().second->getExprLoc()))
1813 CommaVisitor(*this).Visit(Second.get().second);
1815 Expr *Third = third.release().getAs<Expr>();
1816 if (isa<NullStmt>(Body))
1817 getCurCompoundScope().setHasEmptyLoopBodies();
1819 return new (Context)
1820 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1821 Body, ForLoc, LParenLoc, RParenLoc);
1824 /// In an Objective C collection iteration statement:
1826 /// x can be an arbitrary l-value expression. Bind it up as a
1827 /// full-expression.
1828 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1829 // Reduce placeholder expressions here. Note that this rejects the
1830 // use of pseudo-object l-values in this position.
1831 ExprResult result = CheckPlaceholderExpr(E);
1832 if (result.isInvalid()) return StmtError();
1835 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
1836 if (FullExpr.isInvalid())
1838 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1842 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1846 ExprResult result = CorrectDelayedTyposInExpr(collection);
1847 if (!result.isUsable())
1849 collection = result.get();
1851 // Bail out early if we've got a type-dependent expression.
1852 if (collection->isTypeDependent()) return collection;
1854 // Perform normal l-value conversion.
1855 result = DefaultFunctionArrayLvalueConversion(collection);
1856 if (result.isInvalid())
1858 collection = result.get();
1860 // The operand needs to have object-pointer type.
1861 // TODO: should we do a contextual conversion?
1862 const ObjCObjectPointerType *pointerType =
1863 collection->getType()->getAs<ObjCObjectPointerType>();
1865 return Diag(forLoc, diag::err_collection_expr_type)
1866 << collection->getType() << collection->getSourceRange();
1868 // Check that the operand provides
1869 // - countByEnumeratingWithState:objects:count:
1870 const ObjCObjectType *objectType = pointerType->getObjectType();
1871 ObjCInterfaceDecl *iface = objectType->getInterface();
1873 // If we have a forward-declared type, we can't do this check.
1874 // Under ARC, it is an error not to have a forward-declared class.
1876 (getLangOpts().ObjCAutoRefCount
1877 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1878 diag::err_arc_collection_forward, collection)
1879 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1880 // Otherwise, if we have any useful type information, check that
1881 // the type declares the appropriate method.
1882 } else if (iface || !objectType->qual_empty()) {
1883 IdentifierInfo *selectorIdents[] = {
1884 &Context.Idents.get("countByEnumeratingWithState"),
1885 &Context.Idents.get("objects"),
1886 &Context.Idents.get("count")
1888 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1890 ObjCMethodDecl *method = nullptr;
1892 // If there's an interface, look in both the public and private APIs.
1894 method = iface->lookupInstanceMethod(selector);
1895 if (!method) method = iface->lookupPrivateMethod(selector);
1898 // Also check protocol qualifiers.
1900 method = LookupMethodInQualifiedType(selector, pointerType,
1903 // If we didn't find it anywhere, give up.
1905 Diag(forLoc, diag::warn_collection_expr_type)
1906 << collection->getType() << selector << collection->getSourceRange();
1909 // TODO: check for an incompatible signature?
1912 // Wrap up any cleanups in the expression.
1917 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1918 Stmt *First, Expr *collection,
1919 SourceLocation RParenLoc) {
1920 setFunctionHasBranchProtectedScope();
1922 ExprResult CollectionExprResult =
1923 CheckObjCForCollectionOperand(ForLoc, collection);
1927 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1928 if (!DS->isSingleDecl())
1929 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1930 diag::err_toomany_element_decls));
1932 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1933 if (!D || D->isInvalidDecl())
1936 FirstType = D->getType();
1937 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1938 // declare identifiers for objects having storage class 'auto' or
1940 if (!D->hasLocalStorage())
1941 return StmtError(Diag(D->getLocation(),
1942 diag::err_non_local_variable_decl_in_for));
1944 // If the type contained 'auto', deduce the 'auto' to 'id'.
1945 if (FirstType->getContainedAutoType()) {
1946 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1948 Expr *DeducedInit = &OpaqueId;
1949 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1951 DiagnoseAutoDeductionFailure(D, DeducedInit);
1952 if (FirstType.isNull()) {
1953 D->setInvalidDecl();
1957 D->setType(FirstType);
1959 if (!inTemplateInstantiation()) {
1960 SourceLocation Loc =
1961 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1962 Diag(Loc, diag::warn_auto_var_is_id)
1963 << D->getDeclName();
1968 Expr *FirstE = cast<Expr>(First);
1969 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1971 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1972 << First->getSourceRange());
1974 FirstType = static_cast<Expr*>(First)->getType();
1975 if (FirstType.isConstQualified())
1976 Diag(ForLoc, diag::err_selector_element_const_type)
1977 << FirstType << First->getSourceRange();
1979 if (!FirstType->isDependentType() &&
1980 !FirstType->isObjCObjectPointerType() &&
1981 !FirstType->isBlockPointerType())
1982 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1983 << FirstType << First->getSourceRange());
1986 if (CollectionExprResult.isInvalid())
1989 CollectionExprResult =
1990 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
1991 if (CollectionExprResult.isInvalid())
1994 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1995 nullptr, ForLoc, RParenLoc);
1998 /// Finish building a variable declaration for a for-range statement.
1999 /// \return true if an error occurs.
2000 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
2001 SourceLocation Loc, int DiagID) {
2002 if (Decl->getType()->isUndeducedType()) {
2003 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
2004 if (!Res.isUsable()) {
2005 Decl->setInvalidDecl();
2011 // Deduce the type for the iterator variable now rather than leaving it to
2012 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2014 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
2015 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
2017 SemaRef.Diag(Loc, DiagID) << Init->getType();
2018 if (InitType.isNull()) {
2019 Decl->setInvalidDecl();
2022 Decl->setType(InitType);
2024 // In ARC, infer lifetime.
2025 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2026 // we're doing the equivalent of fast iteration.
2027 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2028 SemaRef.inferObjCARCLifetime(Decl))
2029 Decl->setInvalidDecl();
2031 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2032 SemaRef.FinalizeDeclaration(Decl);
2033 SemaRef.CurContext->addHiddenDecl(Decl);
2038 // An enum to represent whether something is dealing with a call to begin()
2039 // or a call to end() in a range-based for loop.
2040 enum BeginEndFunction {
2045 /// Produce a note indicating which begin/end function was implicitly called
2046 /// by a C++11 for-range statement. This is often not obvious from the code,
2047 /// nor from the diagnostics produced when analysing the implicit expressions
2048 /// required in a for-range statement.
2049 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2050 BeginEndFunction BEF) {
2051 CallExpr *CE = dyn_cast<CallExpr>(E);
2054 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2057 SourceLocation Loc = D->getLocation();
2059 std::string Description;
2060 bool IsTemplate = false;
2061 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2062 Description = SemaRef.getTemplateArgumentBindingsText(
2063 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2067 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2068 << BEF << IsTemplate << Description << E->getType();
2071 /// Build a variable declaration for a for-range statement.
2072 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2073 QualType Type, StringRef Name) {
2074 DeclContext *DC = SemaRef.CurContext;
2075 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2076 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2077 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2079 Decl->setImplicit();
2085 static bool ObjCEnumerationCollection(Expr *Collection) {
2086 return !Collection->isTypeDependent()
2087 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2090 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2092 /// C++11 [stmt.ranged]:
2093 /// A range-based for statement is equivalent to
2096 /// auto && __range = range-init;
2097 /// for ( auto __begin = begin-expr,
2098 /// __end = end-expr;
2099 /// __begin != __end;
2101 /// for-range-declaration = *__begin;
2106 /// The body of the loop is not available yet, since it cannot be analysed until
2107 /// we have determined the type of the for-range-declaration.
2108 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2109 SourceLocation CoawaitLoc, Stmt *InitStmt,
2110 Stmt *First, SourceLocation ColonLoc,
2111 Expr *Range, SourceLocation RParenLoc,
2112 BuildForRangeKind Kind) {
2116 if (Range && ObjCEnumerationCollection(Range)) {
2117 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2119 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2120 << InitStmt->getSourceRange();
2121 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2124 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2125 assert(DS && "first part of for range not a decl stmt");
2127 if (!DS->isSingleDecl()) {
2128 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2132 // This function is responsible for attaching an initializer to LoopVar. We
2133 // must call ActOnInitializerError if we fail to do so.
2134 Decl *LoopVar = DS->getSingleDecl();
2135 if (LoopVar->isInvalidDecl() || !Range ||
2136 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2137 ActOnInitializerError(LoopVar);
2141 // Build the coroutine state immediately and not later during template
2143 if (!CoawaitLoc.isInvalid()) {
2144 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
2145 ActOnInitializerError(LoopVar);
2150 // Build auto && __range = range-init
2151 // Divide by 2, since the variables are in the inner scope (loop body).
2152 const auto DepthStr = std::to_string(S->getDepth() / 2);
2153 SourceLocation RangeLoc = Range->getBeginLoc();
2154 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2155 Context.getAutoRRefDeductType(),
2156 std::string("__range") + DepthStr);
2157 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2158 diag::err_for_range_deduction_failure)) {
2159 ActOnInitializerError(LoopVar);
2163 // Claim the type doesn't contain auto: we've already done the checking.
2164 DeclGroupPtrTy RangeGroup =
2165 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2166 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2167 if (RangeDecl.isInvalid()) {
2168 ActOnInitializerError(LoopVar);
2172 StmtResult R = BuildCXXForRangeStmt(
2173 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2174 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2175 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2176 if (R.isInvalid()) {
2177 ActOnInitializerError(LoopVar);
2184 /// Create the initialization, compare, and increment steps for
2185 /// the range-based for loop expression.
2186 /// This function does not handle array-based for loops,
2187 /// which are created in Sema::BuildCXXForRangeStmt.
2189 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2190 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2191 /// CandidateSet and BEF are set and some non-success value is returned on
2193 static Sema::ForRangeStatus
2194 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2195 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2196 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2197 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2198 ExprResult *EndExpr, BeginEndFunction *BEF) {
2199 DeclarationNameInfo BeginNameInfo(
2200 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2201 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2204 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2205 Sema::LookupMemberName);
2206 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2208 auto BuildBegin = [&] {
2210 Sema::ForRangeStatus RangeStatus =
2211 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2212 BeginMemberLookup, CandidateSet,
2213 BeginRange, BeginExpr);
2215 if (RangeStatus != Sema::FRS_Success) {
2216 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2217 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2218 << ColonLoc << BEF_begin << BeginRange->getType();
2221 if (!CoawaitLoc.isInvalid()) {
2222 // FIXME: getCurScope() should not be used during template instantiation.
2223 // We should pick up the set of unqualified lookup results for operator
2224 // co_await during the initial parse.
2225 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2227 if (BeginExpr->isInvalid())
2228 return Sema::FRS_DiagnosticIssued;
2230 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2231 diag::err_for_range_iter_deduction_failure)) {
2232 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2233 return Sema::FRS_DiagnosticIssued;
2235 return Sema::FRS_Success;
2238 auto BuildEnd = [&] {
2240 Sema::ForRangeStatus RangeStatus =
2241 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2242 EndMemberLookup, CandidateSet,
2244 if (RangeStatus != Sema::FRS_Success) {
2245 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2246 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2247 << ColonLoc << BEF_end << EndRange->getType();
2250 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2251 diag::err_for_range_iter_deduction_failure)) {
2252 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2253 return Sema::FRS_DiagnosticIssued;
2255 return Sema::FRS_Success;
2258 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2259 // - if _RangeT is a class type, the unqualified-ids begin and end are
2260 // looked up in the scope of class _RangeT as if by class member access
2261 // lookup (3.4.5), and if either (or both) finds at least one
2262 // declaration, begin-expr and end-expr are __range.begin() and
2263 // __range.end(), respectively;
2264 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2265 if (BeginMemberLookup.isAmbiguous())
2266 return Sema::FRS_DiagnosticIssued;
2268 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2269 if (EndMemberLookup.isAmbiguous())
2270 return Sema::FRS_DiagnosticIssued;
2272 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2273 // Look up the non-member form of the member we didn't find, first.
2274 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2275 // a 'begin' but ignored it because there was no member 'end'"
2277 auto BuildNonmember = [&](
2278 BeginEndFunction BEFFound, LookupResult &Found,
2279 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2280 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2281 LookupResult OldFound = std::move(Found);
2284 if (Sema::ForRangeStatus Result = BuildNotFound())
2287 switch (BuildFound()) {
2288 case Sema::FRS_Success:
2289 return Sema::FRS_Success;
2291 case Sema::FRS_NoViableFunction:
2292 CandidateSet->NoteCandidates(
2293 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2294 SemaRef.PDiag(diag::err_for_range_invalid)
2295 << BeginRange->getType() << BEFFound),
2296 SemaRef, OCD_AllCandidates, BeginRange);
2299 case Sema::FRS_DiagnosticIssued:
2300 for (NamedDecl *D : OldFound) {
2301 SemaRef.Diag(D->getLocation(),
2302 diag::note_for_range_member_begin_end_ignored)
2303 << BeginRange->getType() << BEFFound;
2305 return Sema::FRS_DiagnosticIssued;
2307 llvm_unreachable("unexpected ForRangeStatus");
2309 if (BeginMemberLookup.empty())
2310 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2311 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2314 // - otherwise, begin-expr and end-expr are begin(__range) and
2315 // end(__range), respectively, where begin and end are looked up with
2316 // argument-dependent lookup (3.4.2). For the purposes of this name
2317 // lookup, namespace std is an associated namespace.
2320 if (Sema::ForRangeStatus Result = BuildBegin())
2325 /// Speculatively attempt to dereference an invalid range expression.
2326 /// If the attempt fails, this function will return a valid, null StmtResult
2327 /// and emit no diagnostics.
2328 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2329 SourceLocation ForLoc,
2330 SourceLocation CoawaitLoc,
2333 SourceLocation ColonLoc,
2335 SourceLocation RangeLoc,
2336 SourceLocation RParenLoc) {
2337 // Determine whether we can rebuild the for-range statement with a
2338 // dereferenced range expression.
2339 ExprResult AdjustedRange;
2341 Sema::SFINAETrap Trap(SemaRef);
2343 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2344 if (AdjustedRange.isInvalid())
2345 return StmtResult();
2347 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2348 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2349 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2351 return StmtResult();
2354 // The attempt to dereference worked well enough that it could produce a valid
2355 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2356 // case there are any other (non-fatal) problems with it.
2357 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2358 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2359 return SemaRef.ActOnCXXForRangeStmt(
2360 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2361 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2364 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2365 StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2366 SourceLocation CoawaitLoc, Stmt *InitStmt,
2367 SourceLocation ColonLoc, Stmt *RangeDecl,
2368 Stmt *Begin, Stmt *End, Expr *Cond,
2369 Expr *Inc, Stmt *LoopVarDecl,
2370 SourceLocation RParenLoc,
2371 BuildForRangeKind Kind) {
2372 // FIXME: This should not be used during template instantiation. We should
2373 // pick up the set of unqualified lookup results for the != and + operators
2374 // in the initial parse.
2376 // Testcase (accepts-invalid):
2377 // template<typename T> void f() { for (auto x : T()) {} }
2378 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2379 // bool operator!=(N::X, N::X); void operator++(N::X);
2380 // void g() { f<N::X>(); }
2381 Scope *S = getCurScope();
2383 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2384 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2385 QualType RangeVarType = RangeVar->getType();
2387 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2388 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2390 StmtResult BeginDeclStmt = Begin;
2391 StmtResult EndDeclStmt = End;
2392 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2394 if (RangeVarType->isDependentType()) {
2395 // The range is implicitly used as a placeholder when it is dependent.
2396 RangeVar->markUsed(Context);
2398 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2399 // them in properly when we instantiate the loop.
2400 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2401 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2402 for (auto *Binding : DD->bindings())
2403 Binding->setType(Context.DependentTy);
2404 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2406 } else if (!BeginDeclStmt.get()) {
2407 SourceLocation RangeLoc = RangeVar->getLocation();
2409 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2411 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2412 VK_LValue, ColonLoc);
2413 if (BeginRangeRef.isInvalid())
2416 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2417 VK_LValue, ColonLoc);
2418 if (EndRangeRef.isInvalid())
2421 QualType AutoType = Context.getAutoDeductType();
2422 Expr *Range = RangeVar->getInit();
2425 QualType RangeType = Range->getType();
2427 if (RequireCompleteType(RangeLoc, RangeType,
2428 diag::err_for_range_incomplete_type))
2431 // Build auto __begin = begin-expr, __end = end-expr.
2432 // Divide by 2, since the variables are in the inner scope (loop body).
2433 const auto DepthStr = std::to_string(S->getDepth() / 2);
2434 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2435 std::string("__begin") + DepthStr);
2436 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2437 std::string("__end") + DepthStr);
2439 // Build begin-expr and end-expr and attach to __begin and __end variables.
2440 ExprResult BeginExpr, EndExpr;
2441 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2442 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2443 // __range + __bound, respectively, where __bound is the array bound. If
2444 // _RangeT is an array of unknown size or an array of incomplete type,
2445 // the program is ill-formed;
2447 // begin-expr is __range.
2448 BeginExpr = BeginRangeRef;
2449 if (!CoawaitLoc.isInvalid()) {
2450 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2451 if (BeginExpr.isInvalid())
2454 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2455 diag::err_for_range_iter_deduction_failure)) {
2456 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2460 // Find the array bound.
2461 ExprResult BoundExpr;
2462 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2463 BoundExpr = IntegerLiteral::Create(
2464 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2465 else if (const VariableArrayType *VAT =
2466 dyn_cast<VariableArrayType>(UnqAT)) {
2467 // For a variably modified type we can't just use the expression within
2468 // the array bounds, since we don't want that to be re-evaluated here.
2469 // Rather, we need to determine what it was when the array was first
2470 // created - so we resort to using sizeof(vla)/sizeof(element).
2474 // b = -1; <-- This should not affect the num of iterations below
2475 // for (int &c : vla) { .. }
2478 // FIXME: This results in codegen generating IR that recalculates the
2479 // run-time number of elements (as opposed to just using the IR Value
2480 // that corresponds to the run-time value of each bound that was
2481 // generated when the array was created.) If this proves too embarrassing
2482 // even for unoptimized IR, consider passing a magic-value/cookie to
2483 // codegen that then knows to simply use that initial llvm::Value (that
2484 // corresponds to the bound at time of array creation) within
2485 // getelementptr. But be prepared to pay the price of increasing a
2486 // customized form of coupling between the two components - which could
2487 // be hard to maintain as the codebase evolves.
2489 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2490 EndVar->getLocation(), UETT_SizeOf,
2492 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2493 VAT->desugar(), RangeLoc))
2495 EndVar->getSourceRange());
2496 if (SizeOfVLAExprR.isInvalid())
2499 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2500 EndVar->getLocation(), UETT_SizeOf,
2502 CreateParsedType(VAT->desugar(),
2503 Context.getTrivialTypeSourceInfo(
2504 VAT->getElementType(), RangeLoc))
2506 EndVar->getSourceRange());
2507 if (SizeOfEachElementExprR.isInvalid())
2511 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2512 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2513 if (BoundExpr.isInvalid())
2517 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2518 // UnqAT is not incomplete and Range is not type-dependent.
2519 llvm_unreachable("Unexpected array type in for-range");
2522 // end-expr is __range + __bound.
2523 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2525 if (EndExpr.isInvalid())
2527 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2528 diag::err_for_range_iter_deduction_failure)) {
2529 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2533 OverloadCandidateSet CandidateSet(RangeLoc,
2534 OverloadCandidateSet::CSK_Normal);
2535 BeginEndFunction BEFFailure;
2536 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2537 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2538 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2541 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2542 BEFFailure == BEF_begin) {
2543 // If the range is being built from an array parameter, emit a
2544 // a diagnostic that it is being treated as a pointer.
2545 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2546 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2547 QualType ArrayTy = PVD->getOriginalType();
2548 QualType PointerTy = PVD->getType();
2549 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2550 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2551 << RangeLoc << PVD << ArrayTy << PointerTy;
2552 Diag(PVD->getLocation(), diag::note_declared_at);
2558 // If building the range failed, try dereferencing the range expression
2559 // unless a diagnostic was issued or the end function is problematic.
2560 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2561 CoawaitLoc, InitStmt,
2562 LoopVarDecl, ColonLoc,
2565 if (SR.isInvalid() || SR.isUsable())
2569 // Otherwise, emit diagnostics if we haven't already.
2570 if (RangeStatus == FRS_NoViableFunction) {
2571 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2572 CandidateSet.NoteCandidates(
2573 PartialDiagnosticAt(Range->getBeginLoc(),
2574 PDiag(diag::err_for_range_invalid)
2575 << RangeLoc << Range->getType()
2577 *this, OCD_AllCandidates, Range);
2579 // Return an error if no fix was discovered.
2580 if (RangeStatus != FRS_Success)
2584 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2585 "invalid range expression in for loop");
2587 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2588 // C++1z removes this restriction.
2589 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2590 if (!Context.hasSameType(BeginType, EndType)) {
2591 Diag(RangeLoc, getLangOpts().CPlusPlus17
2592 ? diag::warn_for_range_begin_end_types_differ
2593 : diag::ext_for_range_begin_end_types_differ)
2594 << BeginType << EndType;
2595 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2596 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2600 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2602 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2604 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2605 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2606 VK_LValue, ColonLoc);
2607 if (BeginRef.isInvalid())
2610 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2611 VK_LValue, ColonLoc);
2612 if (EndRef.isInvalid())
2615 // Build and check __begin != __end expression.
2616 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2617 BeginRef.get(), EndRef.get());
2618 if (!NotEqExpr.isInvalid())
2619 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2620 if (!NotEqExpr.isInvalid())
2622 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2623 if (NotEqExpr.isInvalid()) {
2624 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2625 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2626 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2627 if (!Context.hasSameType(BeginType, EndType))
2628 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2632 // Build and check ++__begin expression.
2633 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2634 VK_LValue, ColonLoc);
2635 if (BeginRef.isInvalid())
2638 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2639 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2640 // FIXME: getCurScope() should not be used during template instantiation.
2641 // We should pick up the set of unqualified lookup results for operator
2642 // co_await during the initial parse.
2643 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2644 if (!IncrExpr.isInvalid())
2645 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2646 if (IncrExpr.isInvalid()) {
2647 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2648 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2649 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2653 // Build and check *__begin expression.
2654 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2655 VK_LValue, ColonLoc);
2656 if (BeginRef.isInvalid())
2659 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2660 if (DerefExpr.isInvalid()) {
2661 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2662 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2663 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2667 // Attach *__begin as initializer for VD. Don't touch it if we're just
2668 // trying to determine whether this would be a valid range.
2669 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2670 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2671 if (LoopVar->isInvalidDecl() ||
2672 (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
2673 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2677 // Don't bother to actually allocate the result if we're just trying to
2678 // determine whether it would be valid.
2679 if (Kind == BFRK_Check)
2680 return StmtResult();
2682 // In OpenMP loop region loop control variable must be private. Perform
2683 // analysis of first part (if any).
2684 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
2685 ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
2687 return new (Context) CXXForRangeStmt(
2688 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2689 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2690 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2691 ColonLoc, RParenLoc);
2694 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2696 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2699 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2701 ForStmt->setBody(B);
2705 // Warn when the loop variable is a const reference that creates a copy.
2706 // Suggest using the non-reference type for copies. If a copy can be prevented
2707 // suggest the const reference type that would do so.
2708 // For instance, given "for (const &Foo : Range)", suggest
2709 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2710 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2711 // the copy altogether.
2712 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2714 QualType RangeInitType) {
2715 const Expr *InitExpr = VD->getInit();
2719 QualType VariableType = VD->getType();
2721 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2722 if (!Cleanups->cleanupsHaveSideEffects())
2723 InitExpr = Cleanups->getSubExpr();
2725 const MaterializeTemporaryExpr *MTE =
2726 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2732 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
2734 // Searching for either UnaryOperator for dereference of a pointer or
2735 // CXXOperatorCallExpr for handling iterators.
2736 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2737 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2739 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2740 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2743 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2744 E = MTE->getSubExpr();
2746 E = E->IgnoreImpCasts();
2749 QualType ReferenceReturnType;
2750 if (isa<UnaryOperator>(E)) {
2751 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
2753 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2754 const FunctionDecl *FD = Call->getDirectCallee();
2755 QualType ReturnType = FD->getReturnType();
2756 if (ReturnType->isReferenceType())
2757 ReferenceReturnType = ReturnType;
2760 if (!ReferenceReturnType.isNull()) {
2761 // Loop variable creates a temporary. Suggest either to go with
2762 // non-reference loop variable to indicate a copy is made, or
2763 // the correct type to bind a const reference.
2764 SemaRef.Diag(VD->getLocation(),
2765 diag::warn_for_range_const_ref_binds_temp_built_from_ref)
2766 << VD << VariableType << ReferenceReturnType;
2767 QualType NonReferenceType = VariableType.getNonReferenceType();
2768 NonReferenceType.removeLocalConst();
2769 QualType NewReferenceType =
2770 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2771 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2772 << NonReferenceType << NewReferenceType << VD->getSourceRange()
2773 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
2774 } else if (!VariableType->isRValueReferenceType()) {
2775 // The range always returns a copy, so a temporary is always created.
2776 // Suggest removing the reference from the loop variable.
2777 // If the type is a rvalue reference do not warn since that changes the
2778 // semantic of the code.
2779 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
2780 << VD << RangeInitType;
2781 QualType NonReferenceType = VariableType.getNonReferenceType();
2782 NonReferenceType.removeLocalConst();
2783 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2784 << NonReferenceType << VD->getSourceRange()
2785 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
2789 /// Determines whether the @p VariableType's declaration is a record with the
2790 /// clang::trivial_abi attribute.
2791 static bool hasTrivialABIAttr(QualType VariableType) {
2792 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
2793 return RD->hasAttr<TrivialABIAttr>();
2798 // Warns when the loop variable can be changed to a reference type to
2799 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2800 // "for (const Foo &x : Range)" if this form does not make a copy.
2801 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2802 const VarDecl *VD) {
2803 const Expr *InitExpr = VD->getInit();
2807 QualType VariableType = VD->getType();
2809 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2810 if (!CE->getConstructor()->isCopyConstructor())
2812 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2813 if (CE->getCastKind() != CK_LValueToRValue)
2819 // Small trivially copyable types are cheap to copy. Do not emit the
2820 // diagnostic for these instances. 64 bytes is a common size of a cache line.
2821 // (The function `getTypeSize` returns the size in bits.)
2822 ASTContext &Ctx = SemaRef.Context;
2823 if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
2824 (VariableType.isTriviallyCopyableType(Ctx) ||
2825 hasTrivialABIAttr(VariableType)))
2828 // Suggest changing from a const variable to a const reference variable
2829 // if doing so will prevent a copy.
2830 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2831 << VD << VariableType;
2832 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
2833 << SemaRef.Context.getLValueReferenceType(VariableType)
2834 << VD->getSourceRange()
2835 << FixItHint::CreateInsertion(VD->getLocation(), "&");
2838 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2839 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2840 /// using "const foo x" to show that a copy is made
2841 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2842 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2843 /// prevent the copy.
2844 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2845 /// Suggest "const foo &x" to prevent the copy.
2846 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2847 const CXXForRangeStmt *ForStmt) {
2848 if (SemaRef.inTemplateInstantiation())
2851 if (SemaRef.Diags.isIgnored(
2852 diag::warn_for_range_const_ref_binds_temp_built_from_ref,
2853 ForStmt->getBeginLoc()) &&
2854 SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
2855 ForStmt->getBeginLoc()) &&
2856 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2857 ForStmt->getBeginLoc())) {
2861 const VarDecl *VD = ForStmt->getLoopVariable();
2865 QualType VariableType = VD->getType();
2867 if (VariableType->isIncompleteType())
2870 const Expr *InitExpr = VD->getInit();
2874 if (InitExpr->getExprLoc().isMacroID())
2877 if (VariableType->isReferenceType()) {
2878 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2879 ForStmt->getRangeInit()->getType());
2880 } else if (VariableType.isConstQualified()) {
2881 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2885 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2886 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2887 /// body cannot be performed until after the type of the range variable is
2889 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2893 if (isa<ObjCForCollectionStmt>(S))
2894 return FinishObjCForCollectionStmt(S, B);
2896 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2897 ForStmt->setBody(B);
2899 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2900 diag::warn_empty_range_based_for_body);
2902 DiagnoseForRangeVariableCopies(*this, ForStmt);
2907 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2908 SourceLocation LabelLoc,
2909 LabelDecl *TheDecl) {
2910 setFunctionHasBranchIntoScope();
2911 TheDecl->markUsed(Context);
2912 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2916 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2918 // Convert operand to void*
2919 if (!E->isTypeDependent()) {
2920 QualType ETy = E->getType();
2921 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2922 ExprResult ExprRes = E;
2923 AssignConvertType ConvTy =
2924 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2925 if (ExprRes.isInvalid())
2928 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2932 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2933 if (ExprRes.isInvalid())
2937 setFunctionHasIndirectGoto();
2939 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2942 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2943 const Scope &DestScope) {
2944 if (!S.CurrentSEHFinally.empty() &&
2945 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2946 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2951 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2952 Scope *S = CurScope->getContinueParent();
2954 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2955 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2957 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2959 return new (Context) ContinueStmt(ContinueLoc);
2963 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2964 Scope *S = CurScope->getBreakParent();
2966 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2967 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2969 if (S->isOpenMPLoopScope())
2970 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2972 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2974 return new (Context) BreakStmt(BreakLoc);
2977 /// Determine whether the given expression is a candidate for
2978 /// copy elision in either a return statement or a throw expression.
2980 /// \param ReturnType If we're determining the copy elision candidate for
2981 /// a return statement, this is the return type of the function. If we're
2982 /// determining the copy elision candidate for a throw expression, this will
2985 /// \param E The expression being returned from the function or block, or
2988 /// \param CESK Whether we allow function parameters or
2989 /// id-expressions that could be moved out of the function to be considered NRVO
2990 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2991 /// determine whether we should try to move as part of a return or throw (which
2992 /// does allow function parameters).
2994 /// \returns The NRVO candidate variable, if the return statement may use the
2995 /// NRVO, or NULL if there is no such candidate.
2996 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2997 CopyElisionSemanticsKind CESK) {
2998 // - in a return statement in a function [where] ...
2999 // ... the expression is the name of a non-volatile automatic object ...
3000 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
3001 if (!DR || DR->refersToEnclosingVariableOrCapture())
3003 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
3007 if (isCopyElisionCandidate(ReturnType, VD, CESK))
3012 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3013 CopyElisionSemanticsKind CESK) {
3014 QualType VDType = VD->getType();
3015 // - in a return statement in a function with ...
3016 // ... a class return type ...
3017 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
3018 if (!ReturnType->isRecordType())
3020 // ... the same cv-unqualified type as the function return type ...
3021 // When considering moving this expression out, allow dissimilar types.
3022 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
3023 !Context.hasSameUnqualifiedType(ReturnType, VDType))
3027 // ...object (other than a function or catch-clause parameter)...
3028 if (VD->getKind() != Decl::Var &&
3029 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
3031 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
3035 if (!VD->hasLocalStorage()) return false;
3037 // Return false if VD is a __block variable. We don't want to implicitly move
3038 // out of a __block variable during a return because we cannot assume the
3039 // variable will no longer be used.
3040 if (VD->hasAttr<BlocksAttr>()) return false;
3042 if (CESK & CES_AllowDifferentTypes)
3045 // ...non-volatile...
3046 if (VD->getType().isVolatileQualified()) return false;
3048 // Variables with higher required alignment than their type's ABI
3049 // alignment cannot use NRVO.
3050 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
3051 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
3057 /// Try to perform the initialization of a potentially-movable value,
3058 /// which is the operand to a return or throw statement.
3060 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3061 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3062 /// then falls back to treating them as lvalues if that failed.
3064 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
3065 /// resolutions that find non-constructors, such as derived-to-base conversions
3066 /// or `operator T()&&` member functions. If false, do consider such
3067 /// conversion sequences.
3069 /// \param Res We will fill this in if move-initialization was possible.
3070 /// If move-initialization is not possible, such that we must fall back to
3071 /// treating the operand as an lvalue, we will leave Res in its original
3073 static void TryMoveInitialization(Sema& S,
3074 const InitializedEntity &Entity,
3075 const VarDecl *NRVOCandidate,
3076 QualType ResultType,
3078 bool ConvertingConstructorsOnly,
3080 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3081 CK_NoOp, Value, VK_XValue);
3083 Expr *InitExpr = &AsRvalue;
3085 InitializationKind Kind = InitializationKind::CreateCopy(
3086 Value->getBeginLoc(), Value->getBeginLoc());
3088 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3093 for (const InitializationSequence::Step &Step : Seq.steps()) {
3094 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3095 Step.Kind != InitializationSequence::SK_UserConversion)
3098 FunctionDecl *FD = Step.Function.Function;
3099 if (ConvertingConstructorsOnly) {
3100 if (isa<CXXConstructorDecl>(FD)) {
3101 // C++14 [class.copy]p32:
3102 // [...] If the first overload resolution fails or was not performed,
3103 // or if the type of the first parameter of the selected constructor
3104 // is not an rvalue reference to the object's type (possibly
3105 // cv-qualified), overload resolution is performed again, considering
3106 // the object as an lvalue.
3107 const RValueReferenceType *RRefType =
3108 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3111 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3112 NRVOCandidate->getType()))
3118 if (isa<CXXConstructorDecl>(FD)) {
3119 // Check that overload resolution selected a constructor taking an
3120 // rvalue reference. If it selected an lvalue reference, then we
3121 // didn't need to cast this thing to an rvalue in the first place.
3122 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3124 } else if (isa<CXXMethodDecl>(FD)) {
3125 // Check that overload resolution selected a conversion operator
3126 // taking an rvalue reference.
3127 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3134 // Promote "AsRvalue" to the heap, since we now need this
3135 // expression node to persist.
3136 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3137 Value, nullptr, VK_XValue);
3139 // Complete type-checking the initialization of the return type
3140 // using the constructor we found.
3141 Res = Seq.Perform(S, Entity, Kind, Value);
3145 /// Perform the initialization of a potentially-movable value, which
3146 /// is the result of return value.
3148 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3149 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3150 /// then falls back to treating them as lvalues if that failed.
3152 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3153 const VarDecl *NRVOCandidate,
3154 QualType ResultType,
3157 // C++14 [class.copy]p32:
3158 // When the criteria for elision of a copy/move operation are met, but not for
3159 // an exception-declaration, and the object to be copied is designated by an
3160 // lvalue, or when the expression in a return statement is a (possibly
3161 // parenthesized) id-expression that names an object with automatic storage
3162 // duration declared in the body or parameter-declaration-clause of the
3163 // innermost enclosing function or lambda-expression, overload resolution to
3164 // select the constructor for the copy is first performed as if the object
3165 // were designated by an rvalue.
3166 ExprResult Res = ExprError();
3169 bool AffectedByCWG1579 = false;
3171 if (!NRVOCandidate) {
3172 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3173 if (NRVOCandidate &&
3174 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3175 Value->getExprLoc())) {
3176 const VarDecl *NRVOCandidateInCXX11 =
3177 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3178 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3182 if (NRVOCandidate) {
3183 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3187 if (!Res.isInvalid() && AffectedByCWG1579) {
3188 QualType QT = NRVOCandidate->getType();
3189 if (QT.getNonReferenceType()
3190 .getUnqualifiedType()
3191 .isTriviallyCopyableType(Context)) {
3192 // Adding 'std::move' around a trivially copyable variable is probably
3193 // pointless. Don't suggest it.
3195 // Common cases for this are returning unique_ptr<Derived> from a
3196 // function of return type unique_ptr<Base>, or returning T from a
3197 // function of return type Expected<T>. This is totally fine in a
3198 // post-CWG1579 world, but was not fine before.
3199 assert(!ResultType.isNull());
3200 SmallString<32> Str;
3201 Str += "std::move(";
3202 Str += NRVOCandidate->getDeclName().getAsString();
3204 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3205 << Value->getSourceRange()
3206 << NRVOCandidate->getDeclName() << ResultType << QT;
3207 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3208 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3210 } else if (Res.isInvalid() &&
3211 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3212 Value->getExprLoc())) {
3213 const VarDecl *FakeNRVOCandidate =
3214 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3215 if (FakeNRVOCandidate) {
3216 QualType QT = FakeNRVOCandidate->getType();
3217 if (QT->isLValueReferenceType()) {
3218 // Adding 'std::move' around an lvalue reference variable's name is
3219 // dangerous. Don't suggest it.
3220 } else if (QT.getNonReferenceType()
3221 .getUnqualifiedType()
3222 .isTriviallyCopyableType(Context)) {
3223 // Adding 'std::move' around a trivially copyable variable is probably
3224 // pointless. Don't suggest it.
3226 ExprResult FakeRes = ExprError();
3227 Expr *FakeValue = Value;
3228 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3229 FakeValue, false, FakeRes);
3230 if (!FakeRes.isInvalid()) {
3232 (Entity.getKind() == InitializedEntity::EK_Exception);
3233 SmallString<32> Str;
3234 Str += "std::move(";
3235 Str += FakeNRVOCandidate->getDeclName().getAsString();
3237 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3238 << Value->getSourceRange()
3239 << FakeNRVOCandidate->getDeclName() << IsThrow;
3240 Diag(Value->getExprLoc(), diag::note_add_std_move)
3241 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3248 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3249 // above, or overload resolution failed. Either way, we need to try
3250 // (again) now with the return value expression as written.
3251 if (Res.isInvalid())
3252 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3257 /// Determine whether the declared return type of the specified function
3258 /// contains 'auto'.
3259 static bool hasDeducedReturnType(FunctionDecl *FD) {
3260 const FunctionProtoType *FPT =
3261 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3262 return FPT->getReturnType()->isUndeducedType();
3265 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3266 /// for capturing scopes.
3269 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3270 // If this is the first return we've seen, infer the return type.
3271 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3272 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3273 QualType FnRetType = CurCap->ReturnType;
3274 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3275 bool HasDeducedReturnType =
3276 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3278 if (ExprEvalContexts.back().Context ==
3279 ExpressionEvaluationContext::DiscardedStatement &&
3280 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3283 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3286 RetValExp = ER.get();
3288 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3289 /* NRVOCandidate=*/nullptr);
3292 if (HasDeducedReturnType) {
3293 // In C++1y, the return type may involve 'auto'.
3294 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3295 FunctionDecl *FD = CurLambda->CallOperator;
3296 if (CurCap->ReturnType.isNull())
3297 CurCap->ReturnType = FD->getReturnType();
3299 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3300 assert(AT && "lost auto type from lambda return type");
3301 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3302 FD->setInvalidDecl();
3303 // FIXME: preserve the ill-formed return expression.
3306 CurCap->ReturnType = FnRetType = FD->getReturnType();
3307 } else if (CurCap->HasImplicitReturnType) {
3308 // For blocks/lambdas with implicit return types, we check each return
3309 // statement individually, and deduce the common return type when the block
3310 // or lambda is completed.
3311 // FIXME: Fold this into the 'auto' codepath above.
3312 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3313 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3314 if (Result.isInvalid())
3316 RetValExp = Result.get();
3318 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3319 // when deducing a return type for a lambda-expression (or by extension
3320 // for a block). These rules differ from the stated C++11 rules only in
3321 // that they remove top-level cv-qualifiers.
3322 if (!CurContext->isDependentContext())
3323 FnRetType = RetValExp->getType().getUnqualifiedType();
3325 FnRetType = CurCap->ReturnType = Context.DependentTy;
3328 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3329 // initializer list, because it is not an expression (even
3330 // though we represent it as one). We still deduce 'void'.
3331 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3332 << RetValExp->getSourceRange();
3335 FnRetType = Context.VoidTy;
3338 // Although we'll properly infer the type of the block once it's completed,
3339 // make sure we provide a return type now for better error recovery.
3340 if (CurCap->ReturnType.isNull())
3341 CurCap->ReturnType = FnRetType;
3343 assert(!FnRetType.isNull());
3345 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3346 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3347 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3350 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3351 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3354 assert(CurLambda && "unknown kind of captured scope");
3355 if (CurLambda->CallOperator->getType()
3356 ->castAs<FunctionType>()
3357 ->getNoReturnAttr()) {
3358 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3363 // Otherwise, verify that this result type matches the previous one. We are
3364 // pickier with blocks than for normal functions because we don't have GCC
3365 // compatibility to worry about here.
3366 const VarDecl *NRVOCandidate = nullptr;
3367 if (FnRetType->isDependentType()) {
3368 // Delay processing for now. TODO: there are lots of dependent
3369 // types we can conclusively prove aren't void.
3370 } else if (FnRetType->isVoidType()) {
3371 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3372 !(getLangOpts().CPlusPlus &&
3373 (RetValExp->isTypeDependent() ||
3374 RetValExp->getType()->isVoidType()))) {
3375 if (!getLangOpts().CPlusPlus &&
3376 RetValExp->getType()->isVoidType())
3377 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3379 Diag(ReturnLoc, diag::err_return_block_has_expr);
3380 RetValExp = nullptr;
3383 } else if (!RetValExp) {
3384 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3385 } else if (!RetValExp->isTypeDependent()) {
3386 // we have a non-void block with an expression, continue checking
3388 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3389 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3392 // In C++ the return statement is handled via a copy initialization.
3393 // the C version of which boils down to CheckSingleAssignmentConstraints.
3394 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3395 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3397 NRVOCandidate != nullptr);
3398 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3399 FnRetType, RetValExp);
3400 if (Res.isInvalid()) {
3401 // FIXME: Cleanup temporaries here, anyway?
3404 RetValExp = Res.get();
3405 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3407 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3412 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3415 RetValExp = ER.get();
3418 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3420 // If we need to check for the named return value optimization,
3421 // or if we need to infer the return type,
3422 // save the return statement in our scope for later processing.
3423 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3424 FunctionScopes.back()->Returns.push_back(Result);
3426 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3427 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3433 /// Marks all typedefs in all local classes in a type referenced.
3435 /// In a function like
3437 /// struct S { typedef int a; };
3441 /// the local type escapes and could be referenced in some TUs but not in
3442 /// others. Pretend that all local typedefs are always referenced, to not warn
3443 /// on this. This isn't necessary if f has internal linkage, or the typedef
3445 class LocalTypedefNameReferencer
3446 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3448 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3449 bool VisitRecordType(const RecordType *RT);
3453 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3454 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3455 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3456 R->isDependentType())
3458 for (auto *TmpD : R->decls())
3459 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3460 if (T->getAccess() != AS_private || R->hasFriends())
3461 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3466 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3467 return FD->getTypeSourceInfo()
3469 .getAsAdjusted<FunctionProtoTypeLoc>()
3473 /// Deduce the return type for a function from a returned expression, per
3474 /// C++1y [dcl.spec.auto]p6.
3475 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3476 SourceLocation ReturnLoc,
3479 // If this is the conversion function for a lambda, we choose to deduce it
3480 // type from the corresponding call operator, not from the synthesized return
3481 // statement within it. See Sema::DeduceReturnType.
3482 if (isLambdaConversionOperator(FD))
3485 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3488 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3489 // If the deduction is for a return statement and the initializer is
3490 // a braced-init-list, the program is ill-formed.
3491 Diag(RetExpr->getExprLoc(),
3492 getCurLambda() ? diag::err_lambda_return_init_list
3493 : diag::err_auto_fn_return_init_list)
3494 << RetExpr->getSourceRange();
3498 if (FD->isDependentContext()) {
3499 // C++1y [dcl.spec.auto]p12:
3500 // Return type deduction [...] occurs when the definition is
3501 // instantiated even if the function body contains a return
3502 // statement with a non-type-dependent operand.
3503 assert(AT->isDeduced() && "should have deduced to dependent type");
3508 // Otherwise, [...] deduce a value for U using the rules of template
3509 // argument deduction.
3510 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3512 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3513 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3514 << OrigResultType.getType() << RetExpr->getType();
3516 if (DAR != DAR_Succeeded)
3519 // If a local type is part of the returned type, mark its fields as
3521 LocalTypedefNameReferencer Referencer(*this);
3522 Referencer.TraverseType(RetExpr->getType());
3524 // In the case of a return with no operand, the initializer is considered
3527 // Deduction here can only succeed if the return type is exactly 'cv auto'
3528 // or 'decltype(auto)', so just check for that case directly.
3529 if (!OrigResultType.getType()->getAs<AutoType>()) {
3530 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3531 << OrigResultType.getType();
3534 // We always deduce U = void in this case.
3535 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3536 if (Deduced.isNull())
3540 // CUDA: Kernel function must have 'void' return type.
3541 if (getLangOpts().CUDA)
3542 if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) {
3543 Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3544 << FD->getType() << FD->getSourceRange();
3548 // If a function with a declared return type that contains a placeholder type
3549 // has multiple return statements, the return type is deduced for each return
3550 // statement. [...] if the type deduced is not the same in each deduction,
3551 // the program is ill-formed.
3552 QualType DeducedT = AT->getDeducedType();
3553 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3554 AutoType *NewAT = Deduced->getContainedAutoType();
3555 // It is possible that NewAT->getDeducedType() is null. When that happens,
3556 // we should not crash, instead we ignore this deduction.
3557 if (NewAT->getDeducedType().isNull())
3560 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3562 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3563 NewAT->getDeducedType());
3564 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3565 const LambdaScopeInfo *LambdaSI = getCurLambda();
3566 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3567 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3568 << NewAT->getDeducedType() << DeducedT
3569 << true /*IsLambda*/;
3571 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3572 << (AT->isDecltypeAuto() ? 1 : 0)
3573 << NewAT->getDeducedType() << DeducedT;
3577 } else if (!FD->isInvalidDecl()) {
3578 // Update all declarations of the function to have the deduced return type.
3579 Context.adjustDeducedFunctionResultType(FD, Deduced);
3586 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3588 // Correct typos, in case the containing function returns 'auto' and
3589 // RetValExp should determine the deduced type.
3590 ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
3591 if (RetVal.isInvalid())
3593 StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
3594 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3595 ExpressionEvaluationContext::DiscardedStatement)
3599 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3600 CurScope->addNRVOCandidate(VD);
3602 CurScope->setNoNRVO();
3605 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3610 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3611 // Check for unexpanded parameter packs.
3612 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3615 if (isa<CapturingScopeInfo>(getCurFunction()))
3616 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3619 QualType RelatedRetType;
3620 const AttrVec *Attrs = nullptr;
3621 bool isObjCMethod = false;
3623 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3624 FnRetType = FD->getReturnType();
3626 Attrs = &FD->getAttrs();
3627 if (FD->isNoReturn())
3628 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3629 << FD->getDeclName();
3630 if (FD->isMain() && RetValExp)
3631 if (isa<CXXBoolLiteralExpr>(RetValExp))
3632 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3633 << RetValExp->getSourceRange();
3634 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3635 if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
3636 if (RT->getDecl()->isOrContainsUnion())
3637 Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3640 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3641 FnRetType = MD->getReturnType();
3642 isObjCMethod = true;
3644 Attrs = &MD->getAttrs();
3645 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3646 // In the implementation of a method with a related return type, the
3647 // type used to type-check the validity of return statements within the
3648 // method body is a pointer to the type of the class being implemented.
3649 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3650 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3652 } else // If we don't have a function/method context, bail.
3655 // C++1z: discarded return statements are not considered when deducing a
3657 if (ExprEvalContexts.back().Context ==
3658 ExpressionEvaluationContext::DiscardedStatement &&
3659 FnRetType->getContainedAutoType()) {
3662 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3665 RetValExp = ER.get();
3667 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3668 /* NRVOCandidate=*/nullptr);
3671 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3673 if (getLangOpts().CPlusPlus14) {
3674 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3675 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3676 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3677 FD->setInvalidDecl();
3680 FnRetType = FD->getReturnType();
3685 bool HasDependentReturnType = FnRetType->isDependentType();
3687 ReturnStmt *Result = nullptr;
3688 if (FnRetType->isVoidType()) {
3690 if (isa<InitListExpr>(RetValExp)) {
3691 // We simply never allow init lists as the return value of void
3692 // functions. This is compatible because this was never allowed before,
3693 // so there's no legacy code to deal with.
3694 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3695 int FunctionKind = 0;
3696 if (isa<ObjCMethodDecl>(CurDecl))
3698 else if (isa<CXXConstructorDecl>(CurDecl))
3700 else if (isa<CXXDestructorDecl>(CurDecl))
3703 Diag(ReturnLoc, diag::err_return_init_list)
3704 << CurDecl->getDeclName() << FunctionKind
3705 << RetValExp->getSourceRange();
3707 // Drop the expression.
3708 RetValExp = nullptr;
3709 } else if (!RetValExp->isTypeDependent()) {
3710 // C99 6.8.6.4p1 (ext_ since GCC warns)
3711 unsigned D = diag::ext_return_has_expr;
3712 if (RetValExp->getType()->isVoidType()) {
3713 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3714 if (isa<CXXConstructorDecl>(CurDecl) ||
3715 isa<CXXDestructorDecl>(CurDecl))
3716 D = diag::err_ctor_dtor_returns_void;
3718 D = diag::ext_return_has_void_expr;
3721 ExprResult Result = RetValExp;
3722 Result = IgnoredValueConversions(Result.get());
3723 if (Result.isInvalid())
3725 RetValExp = Result.get();
3726 RetValExp = ImpCastExprToType(RetValExp,
3727 Context.VoidTy, CK_ToVoid).get();
3729 // return of void in constructor/destructor is illegal in C++.
3730 if (D == diag::err_ctor_dtor_returns_void) {
3731 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3733 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3734 << RetValExp->getSourceRange();
3736 // return (some void expression); is legal in C++.
3737 else if (D != diag::ext_return_has_void_expr ||
3738 !getLangOpts().CPlusPlus) {
3739 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3741 int FunctionKind = 0;
3742 if (isa<ObjCMethodDecl>(CurDecl))
3744 else if (isa<CXXConstructorDecl>(CurDecl))
3746 else if (isa<CXXDestructorDecl>(CurDecl))
3750 << CurDecl->getDeclName() << FunctionKind
3751 << RetValExp->getSourceRange();
3757 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3760 RetValExp = ER.get();
3764 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3765 /* NRVOCandidate=*/nullptr);
3766 } else if (!RetValExp && !HasDependentReturnType) {
3767 FunctionDecl *FD = getCurFunctionDecl();
3770 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3771 // C++11 [stmt.return]p2
3772 DiagID = diag::err_constexpr_return_missing_expr;
3773 FD->setInvalidDecl();
3774 } else if (getLangOpts().C99) {
3775 // C99 6.8.6.4p1 (ext_ since GCC warns)
3776 DiagID = diag::ext_return_missing_expr;
3779 DiagID = diag::warn_return_missing_expr;
3783 Diag(ReturnLoc, DiagID)
3784 << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
3786 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3788 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3789 /* NRVOCandidate=*/nullptr);
3791 assert(RetValExp || HasDependentReturnType);
3792 const VarDecl *NRVOCandidate = nullptr;
3794 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3796 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3797 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3800 // In C++ the return statement is handled via a copy initialization,
3801 // the C version of which boils down to CheckSingleAssignmentConstraints.
3803 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3804 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3805 // we have a non-void function with an expression, continue checking
3806 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3808 NRVOCandidate != nullptr);
3809 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3810 RetType, RetValExp);
3811 if (Res.isInvalid()) {
3812 // FIXME: Clean up temporaries here anyway?
3815 RetValExp = Res.getAs<Expr>();
3817 // If we have a related result type, we need to implicitly
3818 // convert back to the formal result type. We can't pretend to
3819 // initialize the result again --- we might end double-retaining
3820 // --- so instead we initialize a notional temporary.
3821 if (!RelatedRetType.isNull()) {
3822 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3824 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3825 if (Res.isInvalid()) {
3826 // FIXME: Clean up temporaries here anyway?
3829 RetValExp = Res.getAs<Expr>();
3832 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3833 getCurFunctionDecl());
3838 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3841 RetValExp = ER.get();
3843 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3846 // If we need to check for the named return value optimization, save the
3847 // return statement in our scope for later processing.
3848 if (Result->getNRVOCandidate())
3849 FunctionScopes.back()->Returns.push_back(Result);
3851 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3852 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3858 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3859 SourceLocation RParen, Decl *Parm,
3861 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3862 if (Var && Var->isInvalidDecl())
3865 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3869 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3870 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3874 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3875 MultiStmtArg CatchStmts, Stmt *Finally) {
3876 if (!getLangOpts().ObjCExceptions)
3877 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3879 setFunctionHasBranchProtectedScope();
3880 unsigned NumCatchStmts = CatchStmts.size();
3881 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3882 NumCatchStmts, Finally);
3885 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3887 ExprResult Result = DefaultLvalueConversion(Throw);
3888 if (Result.isInvalid())
3891 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
3892 if (Result.isInvalid())
3894 Throw = Result.get();
3896 QualType ThrowType = Throw->getType();
3897 // Make sure the expression type is an ObjC pointer or "void *".
3898 if (!ThrowType->isDependentType() &&
3899 !ThrowType->isObjCObjectPointerType()) {
3900 const PointerType *PT = ThrowType->getAs<PointerType>();
3901 if (!PT || !PT->getPointeeType()->isVoidType())
3902 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3903 << Throw->getType() << Throw->getSourceRange());
3907 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3911 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3913 if (!getLangOpts().ObjCExceptions)
3914 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3917 // @throw without an expression designates a rethrow (which must occur
3918 // in the context of an @catch clause).
3919 Scope *AtCatchParent = CurScope;
3920 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3921 AtCatchParent = AtCatchParent->getParent();
3923 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3925 return BuildObjCAtThrowStmt(AtLoc, Throw);
3929 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3930 ExprResult result = DefaultLvalueConversion(operand);
3931 if (result.isInvalid())
3933 operand = result.get();
3935 // Make sure the expression type is an ObjC pointer or "void *".
3936 QualType type = operand->getType();
3937 if (!type->isDependentType() &&
3938 !type->isObjCObjectPointerType()) {
3939 const PointerType *pointerType = type->getAs<PointerType>();
3940 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3941 if (getLangOpts().CPlusPlus) {
3942 if (RequireCompleteType(atLoc, type,
3943 diag::err_incomplete_receiver_type))
3944 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3945 << type << operand->getSourceRange();
3947 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3948 if (result.isInvalid())
3950 if (!result.isUsable())
3951 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3952 << type << operand->getSourceRange();
3954 operand = result.get();
3956 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3957 << type << operand->getSourceRange();
3962 // The operand to @synchronized is a full-expression.
3963 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
3967 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3969 // We can't jump into or indirect-jump out of a @synchronized block.
3970 setFunctionHasBranchProtectedScope();
3971 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3974 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3975 /// and creates a proper catch handler from them.
3977 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3978 Stmt *HandlerBlock) {
3979 // There's nothing to test that ActOnExceptionDecl didn't already test.
3980 return new (Context)
3981 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3985 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3986 setFunctionHasBranchProtectedScope();
3987 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3991 class CatchHandlerType {
3993 unsigned IsPointer : 1;
3995 // This is a special constructor to be used only with DenseMapInfo's
3996 // getEmptyKey() and getTombstoneKey() functions.
3997 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3998 enum Unique { ForDenseMap };
3999 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
4002 /// Used when creating a CatchHandlerType from a handler type; will determine
4003 /// whether the type is a pointer or reference and will strip off the top
4004 /// level pointer and cv-qualifiers.
4005 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4006 if (QT->isPointerType())
4009 if (IsPointer || QT->isReferenceType())
4010 QT = QT->getPointeeType();
4011 QT = QT.getUnqualifiedType();
4014 /// Used when creating a CatchHandlerType from a base class type; pretends the
4015 /// type passed in had the pointer qualifier, does not need to get an
4016 /// unqualified type.
4017 CatchHandlerType(QualType QT, bool IsPointer)
4018 : QT(QT), IsPointer(IsPointer) {}
4020 QualType underlying() const { return QT; }
4021 bool isPointer() const { return IsPointer; }
4023 friend bool operator==(const CatchHandlerType &LHS,
4024 const CatchHandlerType &RHS) {
4025 // If the pointer qualification does not match, we can return early.
4026 if (LHS.IsPointer != RHS.IsPointer)
4028 // Otherwise, check the underlying type without cv-qualifiers.
4029 return LHS.QT == RHS.QT;
4035 template <> struct DenseMapInfo<CatchHandlerType> {
4036 static CatchHandlerType getEmptyKey() {
4037 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4038 CatchHandlerType::ForDenseMap);
4041 static CatchHandlerType getTombstoneKey() {
4042 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4043 CatchHandlerType::ForDenseMap);
4046 static unsigned getHashValue(const CatchHandlerType &Base) {
4047 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
4050 static bool isEqual(const CatchHandlerType &LHS,
4051 const CatchHandlerType &RHS) {
4058 class CatchTypePublicBases {
4060 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
4061 const bool CheckAgainstPointer;
4063 CXXCatchStmt *FoundHandler;
4064 CanQualType FoundHandlerType;
4067 CatchTypePublicBases(
4069 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
4070 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
4071 FoundHandler(nullptr) {}
4073 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
4074 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
4076 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4077 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4078 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
4079 const auto &M = TypesToCheck;
4080 auto I = M.find(Check);
4082 FoundHandler = I->second;
4083 FoundHandlerType = Ctx.getCanonicalType(S->getType());
4092 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4093 /// handlers and creates a try statement from them.
4094 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4095 ArrayRef<Stmt *> Handlers) {
4096 // Don't report an error if 'try' is used in system headers.
4097 if (!getLangOpts().CXXExceptions &&
4098 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
4099 // Delay error emission for the OpenMP device code.
4100 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4103 // Exceptions aren't allowed in CUDA device code.
4104 if (getLangOpts().CUDA)
4105 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4106 << "try" << CurrentCUDATarget();
4108 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4109 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4111 sema::FunctionScopeInfo *FSI = getCurFunction();
4113 // C++ try is incompatible with SEH __try.
4114 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4115 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4116 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4119 const unsigned NumHandlers = Handlers.size();
4120 assert(!Handlers.empty() &&
4121 "The parser shouldn't call this if there are no handlers.");
4123 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4124 for (unsigned i = 0; i < NumHandlers; ++i) {
4125 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4127 // Diagnose when the handler is a catch-all handler, but it isn't the last
4128 // handler for the try block. [except.handle]p5. Also, skip exception
4129 // declarations that are invalid, since we can't usefully report on them.
4130 if (!H->getExceptionDecl()) {
4131 if (i < NumHandlers - 1)
4132 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4134 } else if (H->getExceptionDecl()->isInvalidDecl())
4137 // Walk the type hierarchy to diagnose when this type has already been
4138 // handled (duplication), or cannot be handled (derivation inversion). We
4139 // ignore top-level cv-qualifiers, per [except.handle]p3
4140 CatchHandlerType HandlerCHT =
4141 (QualType)Context.getCanonicalType(H->getCaughtType());
4143 // We can ignore whether the type is a reference or a pointer; we need the
4144 // underlying declaration type in order to get at the underlying record
4145 // decl, if there is one.
4146 QualType Underlying = HandlerCHT.underlying();
4147 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4148 if (!RD->hasDefinition())
4150 // Check that none of the public, unambiguous base classes are in the
4151 // map ([except.handle]p1). Give the base classes the same pointer
4152 // qualification as the original type we are basing off of. This allows
4153 // comparison against the handler type using the same top-level pointer
4154 // as the original type.
4156 Paths.setOrigin(RD);
4157 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4158 if (RD->lookupInBases(CTPB, Paths)) {
4159 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4160 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4161 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4162 diag::warn_exception_caught_by_earlier_handler)
4163 << H->getCaughtType();
4164 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4165 diag::note_previous_exception_handler)
4166 << Problem->getCaughtType();
4171 // Add the type the list of ones we have handled; diagnose if we've already
4173 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4175 const CXXCatchStmt *Problem = R.first->second;
4176 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4177 diag::warn_exception_caught_by_earlier_handler)
4178 << H->getCaughtType();
4179 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4180 diag::note_previous_exception_handler)
4181 << Problem->getCaughtType();
4185 FSI->setHasCXXTry(TryLoc);
4187 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4190 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4191 Stmt *TryBlock, Stmt *Handler) {
4192 assert(TryBlock && Handler);
4194 sema::FunctionScopeInfo *FSI = getCurFunction();
4196 // SEH __try is incompatible with C++ try. Borland appears to support this,
4198 if (!getLangOpts().Borland) {
4199 if (FSI->FirstCXXTryLoc.isValid()) {
4200 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4201 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4205 FSI->setHasSEHTry(TryLoc);
4207 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4208 // track if they use SEH.
4209 DeclContext *DC = CurContext;
4210 while (DC && !DC->isFunctionOrMethod())
4211 DC = DC->getParent();
4212 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4214 FD->setUsesSEHTry(true);
4216 Diag(TryLoc, diag::err_seh_try_outside_functions);
4218 // Reject __try on unsupported targets.
4219 if (!Context.getTargetInfo().isSEHTrySupported())
4220 Diag(TryLoc, diag::err_seh_try_unsupported);
4222 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4225 StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4227 assert(FilterExpr && Block);
4228 QualType FTy = FilterExpr->getType();
4229 if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4231 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4234 return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
4237 void Sema::ActOnStartSEHFinallyBlock() {
4238 CurrentSEHFinally.push_back(CurScope);
4241 void Sema::ActOnAbortSEHFinallyBlock() {
4242 CurrentSEHFinally.pop_back();
4245 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4247 CurrentSEHFinally.pop_back();
4248 return SEHFinallyStmt::Create(Context, Loc, Block);
4252 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4253 Scope *SEHTryParent = CurScope;
4254 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4255 SEHTryParent = SEHTryParent->getParent();
4257 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4258 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4260 return new (Context) SEHLeaveStmt(Loc);
4263 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4265 NestedNameSpecifierLoc QualifierLoc,
4266 DeclarationNameInfo NameInfo,
4269 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4270 QualifierLoc, NameInfo,
4271 cast<CompoundStmt>(Nested));
4275 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4278 UnqualifiedId &Name,
4280 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4281 SS.getWithLocInContext(Context),
4282 GetNameFromUnqualifiedId(Name),
4287 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4288 unsigned NumParams) {
4289 DeclContext *DC = CurContext;
4290 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4291 DC = DC->getParent();
4293 RecordDecl *RD = nullptr;
4294 if (getLangOpts().CPlusPlus)
4295 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4298 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4300 RD->setCapturedRecord();
4303 RD->startDefinition();
4305 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4306 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4312 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4313 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4314 SmallVectorImpl<Expr *> &CaptureInits) {
4315 for (const sema::Capture &Cap : RSI->Captures) {
4316 if (Cap.isInvalid())
4319 // Form the initializer for the capture.
4320 ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4321 RSI->CapRegionKind == CR_OpenMP);
4323 // FIXME: Bail out now if the capture is not used and the initializer has
4326 // Create a field for this capture.
4327 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4329 // Add the capture to our list of captures.
4330 if (Cap.isThisCapture()) {
4331 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4332 CapturedStmt::VCK_This));
4333 } else if (Cap.isVLATypeCapture()) {
4335 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4337 assert(Cap.isVariableCapture() && "unknown kind of capture");
4339 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4340 S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
4342 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4343 Cap.isReferenceCapture()
4344 ? CapturedStmt::VCK_ByRef
4345 : CapturedStmt::VCK_ByCopy,
4346 Cap.getVariable()));
4348 CaptureInits.push_back(Init.get());
4353 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4354 CapturedRegionKind Kind,
4355 unsigned NumParams) {
4356 CapturedDecl *CD = nullptr;
4357 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4359 // Build the context parameter
4360 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4361 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4362 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4364 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4365 ImplicitParamDecl::CapturedContext);
4368 CD->setContextParam(0, Param);
4370 // Enter the capturing scope for this captured region.
4371 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4374 PushDeclContext(CurScope, CD);
4378 PushExpressionEvaluationContext(
4379 ExpressionEvaluationContext::PotentiallyEvaluated);
4382 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4383 CapturedRegionKind Kind,
4384 ArrayRef<CapturedParamNameType> Params,
4385 unsigned OpenMPCaptureLevel) {
4386 CapturedDecl *CD = nullptr;
4387 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4389 // Build the context parameter
4390 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4391 bool ContextIsFound = false;
4392 unsigned ParamNum = 0;
4393 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4395 I != E; ++I, ++ParamNum) {
4396 if (I->second.isNull()) {
4397 assert(!ContextIsFound &&
4398 "null type has been found already for '__context' parameter");
4399 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4400 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4404 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4405 ImplicitParamDecl::CapturedContext);
4407 CD->setContextParam(ParamNum, Param);
4408 ContextIsFound = true;
4410 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4412 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4413 ImplicitParamDecl::CapturedContext);
4415 CD->setParam(ParamNum, Param);
4418 assert(ContextIsFound && "no null type for '__context' parameter");
4419 if (!ContextIsFound) {
4420 // Add __context implicitly if it is not specified.
4421 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4422 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4424 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4425 ImplicitParamDecl::CapturedContext);
4427 CD->setContextParam(ParamNum, Param);
4429 // Enter the capturing scope for this captured region.
4430 PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
4433 PushDeclContext(CurScope, CD);
4437 PushExpressionEvaluationContext(
4438 ExpressionEvaluationContext::PotentiallyEvaluated);
4441 void Sema::ActOnCapturedRegionError() {
4442 DiscardCleanupsInEvaluationContext();
4443 PopExpressionEvaluationContext();
4445 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4446 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4448 RecordDecl *Record = RSI->TheRecordDecl;
4449 Record->setInvalidDecl();
4451 SmallVector<Decl*, 4> Fields(Record->fields());
4452 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4453 SourceLocation(), SourceLocation(), ParsedAttributesView());
4456 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4457 // Leave the captured scope before we start creating captures in the
4459 DiscardCleanupsInEvaluationContext();
4460 PopExpressionEvaluationContext();
4462 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4463 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4465 SmallVector<CapturedStmt::Capture, 4> Captures;
4466 SmallVector<Expr *, 4> CaptureInits;
4467 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4470 CapturedDecl *CD = RSI->TheCapturedDecl;
4471 RecordDecl *RD = RSI->TheRecordDecl;
4473 CapturedStmt *Res = CapturedStmt::Create(
4474 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4475 Captures, CaptureInits, CD, RD);
4477 CD->setBody(Res->getCapturedStmt());
4478 RD->completeDefinition();