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/AST/ASTContext.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/IgnoreExpr.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Ownership.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/StringExtras.h"
44 using namespace clang
;
47 StmtResult
Sema::ActOnExprStmt(ExprResult FE
, bool DiscardedValue
) {
51 FE
= ActOnFinishFullExpr(FE
.get(), FE
.get()->getExprLoc(), DiscardedValue
);
55 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
56 // void expression for its side effects. Conversion to void allows any
57 // operand, even incomplete types.
59 // Same thing in for stmt first clause (when expr) and third clause.
60 return StmtResult(FE
.getAs
<Stmt
>());
64 StmtResult
Sema::ActOnExprStmtError() {
65 DiscardCleanupsInEvaluationContext();
69 StmtResult
Sema::ActOnNullStmt(SourceLocation SemiLoc
,
70 bool HasLeadingEmptyMacro
) {
71 return new (Context
) NullStmt(SemiLoc
, HasLeadingEmptyMacro
);
74 StmtResult
Sema::ActOnDeclStmt(DeclGroupPtrTy dg
, SourceLocation StartLoc
,
75 SourceLocation EndLoc
) {
76 DeclGroupRef DG
= dg
.get();
78 // If we have an invalid decl, just return an error.
79 if (DG
.isNull()) return StmtError();
81 return new (Context
) DeclStmt(DG
, StartLoc
, EndLoc
);
84 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg
) {
85 DeclGroupRef DG
= dg
.get();
87 // If we don't have a declaration, or we have an invalid declaration,
89 if (DG
.isNull() || !DG
.isSingleDecl())
92 Decl
*decl
= DG
.getSingleDecl();
93 if (!decl
|| decl
->isInvalidDecl())
96 // Only variable declarations are permitted.
97 VarDecl
*var
= dyn_cast
<VarDecl
>(decl
);
99 Diag(decl
->getLocation(), diag::err_non_variable_decl_in_for
);
100 decl
->setInvalidDecl();
104 // foreach variables are never actually initialized in the way that
105 // the parser came up with.
106 var
->setInit(nullptr);
108 // In ARC, we don't need to retain the iteration variable of a fast
109 // enumeration loop. Rather than actually trying to catch that
110 // during declaration processing, we remove the consequences here.
111 if (getLangOpts().ObjCAutoRefCount
) {
112 QualType type
= var
->getType();
114 // Only do this if we inferred the lifetime. Inferred lifetime
115 // will show up as a local qualifier because explicit lifetime
116 // should have shown up as an AttributedType instead.
117 if (type
.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong
) {
118 // Add 'const' and mark the variable as pseudo-strong.
119 var
->setType(type
.withConst());
120 var
->setARCPseudoStrong(true);
125 /// Diagnose unused comparisons, both builtin and overloaded operators.
126 /// For '==' and '!=', suggest fixits for '=' or '|='.
128 /// Adding a cast to void (or other expression wrappers) will prevent the
129 /// warning from firing.
130 static bool DiagnoseUnusedComparison(Sema
&S
, const Expr
*E
) {
133 enum { Equality
, Inequality
, Relational
, ThreeWay
} Kind
;
135 if (const BinaryOperator
*Op
= dyn_cast
<BinaryOperator
>(E
)) {
136 if (!Op
->isComparisonOp())
139 if (Op
->getOpcode() == BO_EQ
)
141 else if (Op
->getOpcode() == BO_NE
)
143 else if (Op
->getOpcode() == BO_Cmp
)
146 assert(Op
->isRelationalOp());
149 Loc
= Op
->getOperatorLoc();
150 CanAssign
= Op
->getLHS()->IgnoreParenImpCasts()->isLValue();
151 } else if (const CXXOperatorCallExpr
*Op
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
152 switch (Op
->getOperator()) {
156 case OO_ExclaimEqual
:
161 case OO_GreaterEqual
:
172 Loc
= Op
->getOperatorLoc();
173 CanAssign
= Op
->getArg(0)->IgnoreParenImpCasts()->isLValue();
175 // Not a typo-prone comparison.
179 // Suppress warnings when the operator, suspicious as it may be, comes from
180 // a macro expansion.
181 if (S
.SourceMgr
.isMacroBodyExpansion(Loc
))
184 S
.Diag(Loc
, diag::warn_unused_comparison
)
185 << (unsigned)Kind
<< E
->getSourceRange();
187 // If the LHS is a plausible entity to assign to, provide a fixit hint to
188 // correct common typos.
190 if (Kind
== Inequality
)
191 S
.Diag(Loc
, diag::note_inequality_comparison_to_or_assign
)
192 << FixItHint::CreateReplacement(Loc
, "|=");
193 else if (Kind
== Equality
)
194 S
.Diag(Loc
, diag::note_equality_comparison_to_assign
)
195 << FixItHint::CreateReplacement(Loc
, "=");
201 static bool DiagnoseNoDiscard(Sema
&S
, const WarnUnusedResultAttr
*A
,
202 SourceLocation Loc
, SourceRange R1
,
203 SourceRange R2
, bool IsCtor
) {
206 StringRef Msg
= A
->getMessage();
210 return S
.Diag(Loc
, diag::warn_unused_constructor
) << A
<< R1
<< R2
;
211 return S
.Diag(Loc
, diag::warn_unused_result
) << A
<< R1
<< R2
;
215 return S
.Diag(Loc
, diag::warn_unused_constructor_msg
) << A
<< Msg
<< R1
217 return S
.Diag(Loc
, diag::warn_unused_result_msg
) << A
<< Msg
<< R1
<< R2
;
220 void Sema::DiagnoseUnusedExprResult(const Stmt
*S
, unsigned DiagID
) {
221 if (const LabelStmt
*Label
= dyn_cast_or_null
<LabelStmt
>(S
))
222 return DiagnoseUnusedExprResult(Label
->getSubStmt(), DiagID
);
224 const Expr
*E
= dyn_cast_or_null
<Expr
>(S
);
228 // If we are in an unevaluated expression context, then there can be no unused
229 // results because the results aren't expected to be used in the first place.
230 if (isUnevaluatedContext())
233 SourceLocation ExprLoc
= E
->IgnoreParenImpCasts()->getExprLoc();
234 // In most cases, we don't want to warn if the expression is written in a
235 // macro body, or if the macro comes from a system header. If the offending
236 // expression is a call to a function with the warn_unused_result attribute,
237 // we warn no matter the location. Because of the order in which the various
238 // checks need to happen, we factor out the macro-related test here.
239 bool ShouldSuppress
=
240 SourceMgr
.isMacroBodyExpansion(ExprLoc
) ||
241 SourceMgr
.isInSystemMacro(ExprLoc
);
243 const Expr
*WarnExpr
;
246 if (!E
->isUnusedResultAWarning(WarnExpr
, Loc
, R1
, R2
, Context
))
249 // If this is a GNU statement expression expanded from a macro, it is probably
250 // unused because it is a function-like macro that can be used as either an
251 // expression or statement. Don't warn, because it is almost certainly a
253 if (isa
<StmtExpr
>(E
) && Loc
.isMacroID())
256 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
257 // That macro is frequently used to suppress "unused parameter" warnings,
258 // but its implementation makes clang's -Wunused-value fire. Prevent this.
259 if (isa
<ParenExpr
>(E
->IgnoreImpCasts()) && Loc
.isMacroID()) {
260 SourceLocation SpellLoc
= Loc
;
261 if (findMacroSpelling(SpellLoc
, "UNREFERENCED_PARAMETER"))
265 // Okay, we have an unused result. Depending on what the base expression is,
266 // we might want to make a more specific diagnostic. Check for one of these
268 if (const FullExpr
*Temps
= dyn_cast
<FullExpr
>(E
))
269 E
= Temps
->getSubExpr();
270 if (const CXXBindTemporaryExpr
*TempExpr
= dyn_cast
<CXXBindTemporaryExpr
>(E
))
271 E
= TempExpr
->getSubExpr();
273 if (DiagnoseUnusedComparison(*this, E
))
277 if (const auto *Cast
= dyn_cast
<CastExpr
>(E
))
278 if (Cast
->getCastKind() == CK_NoOp
||
279 Cast
->getCastKind() == CK_ConstructorConversion
)
280 E
= Cast
->getSubExpr()->IgnoreImpCasts();
282 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
283 if (E
->getType()->isVoidType())
286 if (DiagnoseNoDiscard(*this, cast_or_null
<WarnUnusedResultAttr
>(
287 CE
->getUnusedResultAttr(Context
)),
288 Loc
, R1
, R2
, /*isCtor=*/false))
291 // If the callee has attribute pure, const, or warn_unused_result, warn with
292 // a more specific message to make it clear what is happening. If the call
293 // is written in a macro body, only warn if it has the warn_unused_result
295 if (const Decl
*FD
= CE
->getCalleeDecl()) {
298 if (FD
->hasAttr
<PureAttr
>()) {
299 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "pure";
302 if (FD
->hasAttr
<ConstAttr
>()) {
303 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "const";
307 } else if (const auto *CE
= dyn_cast
<CXXConstructExpr
>(E
)) {
308 if (const CXXConstructorDecl
*Ctor
= CE
->getConstructor()) {
309 const auto *A
= Ctor
->getAttr
<WarnUnusedResultAttr
>();
310 A
= A
? A
: Ctor
->getParent()->getAttr
<WarnUnusedResultAttr
>();
311 if (DiagnoseNoDiscard(*this, A
, Loc
, R1
, R2
, /*isCtor=*/true))
314 } else if (const auto *ILE
= dyn_cast
<InitListExpr
>(E
)) {
315 if (const TagDecl
*TD
= ILE
->getType()->getAsTagDecl()) {
317 if (DiagnoseNoDiscard(*this, TD
->getAttr
<WarnUnusedResultAttr
>(), Loc
, R1
,
318 R2
, /*isCtor=*/false))
321 } else if (ShouldSuppress
)
325 if (const ObjCMessageExpr
*ME
= dyn_cast
<ObjCMessageExpr
>(E
)) {
326 if (getLangOpts().ObjCAutoRefCount
&& ME
->isDelegateInitCall()) {
327 Diag(Loc
, diag::err_arc_unused_init_message
) << R1
;
330 const ObjCMethodDecl
*MD
= ME
->getMethodDecl();
332 if (DiagnoseNoDiscard(*this, MD
->getAttr
<WarnUnusedResultAttr
>(), Loc
, R1
,
333 R2
, /*isCtor=*/false))
336 } else if (const PseudoObjectExpr
*POE
= dyn_cast
<PseudoObjectExpr
>(E
)) {
337 const Expr
*Source
= POE
->getSyntacticForm();
338 // Handle the actually selected call of an OpenMP specialized call.
339 if (LangOpts
.OpenMP
&& isa
<CallExpr
>(Source
) &&
340 POE
->getNumSemanticExprs() == 1 &&
341 isa
<CallExpr
>(POE
->getSemanticExpr(0)))
342 return DiagnoseUnusedExprResult(POE
->getSemanticExpr(0), DiagID
);
343 if (isa
<ObjCSubscriptRefExpr
>(Source
))
344 DiagID
= diag::warn_unused_container_subscript_expr
;
345 else if (isa
<ObjCPropertyRefExpr
>(Source
))
346 DiagID
= diag::warn_unused_property_expr
;
347 } else if (const CXXFunctionalCastExpr
*FC
348 = dyn_cast
<CXXFunctionalCastExpr
>(E
)) {
349 const Expr
*E
= FC
->getSubExpr();
350 if (const CXXBindTemporaryExpr
*TE
= dyn_cast
<CXXBindTemporaryExpr
>(E
))
351 E
= TE
->getSubExpr();
352 if (isa
<CXXTemporaryObjectExpr
>(E
))
354 if (const CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(E
))
355 if (const CXXRecordDecl
*RD
= CE
->getType()->getAsCXXRecordDecl())
356 if (!RD
->getAttr
<WarnUnusedAttr
>())
359 // Diagnose "(void*) blah" as a typo for "(void) blah".
360 else if (const CStyleCastExpr
*CE
= dyn_cast
<CStyleCastExpr
>(E
)) {
361 TypeSourceInfo
*TI
= CE
->getTypeInfoAsWritten();
362 QualType T
= TI
->getType();
364 // We really do want to use the non-canonical type here.
365 if (T
== Context
.VoidPtrTy
) {
366 PointerTypeLoc TL
= TI
->getTypeLoc().castAs
<PointerTypeLoc
>();
368 Diag(Loc
, diag::warn_unused_voidptr
)
369 << FixItHint::CreateRemoval(TL
.getStarLoc());
374 // Tell the user to assign it into a variable to force a volatile load if this
376 if (E
->isGLValue() && E
->getType().isVolatileQualified() &&
377 !E
->getType()->isArrayType()) {
378 Diag(Loc
, diag::warn_unused_volatile
) << R1
<< R2
;
382 // Do not diagnose use of a comma operator in a SFINAE context because the
383 // type of the left operand could be used for SFINAE, so technically it is
385 if (DiagID
!= diag::warn_unused_comma_left_operand
|| !isSFINAEContext())
386 DiagIfReachable(Loc
, S
? llvm::ArrayRef(S
) : std::nullopt
,
387 PDiag(DiagID
) << R1
<< R2
);
390 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr
) {
391 PushCompoundScope(IsStmtExpr
);
394 void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
395 if (getCurFPFeatures().isFPConstrained()) {
396 FunctionScopeInfo
*FSI
= getCurFunction();
398 FSI
->setUsesFPIntrin();
402 void Sema::ActOnFinishOfCompoundStmt() {
406 sema::CompoundScopeInfo
&Sema::getCurCompoundScope() const {
407 return getCurFunction()->CompoundScopes
.back();
410 StmtResult
Sema::ActOnCompoundStmt(SourceLocation L
, SourceLocation R
,
411 ArrayRef
<Stmt
*> Elts
, bool isStmtExpr
) {
412 const unsigned NumElts
= Elts
.size();
414 // If we're in C mode, check that we don't have any decls after stmts. If
415 // so, emit an extension diagnostic in C89 and potentially a warning in later
417 const unsigned MixedDeclsCodeID
= getLangOpts().C99
418 ? diag::warn_mixed_decls_code
419 : diag::ext_mixed_decls_code
;
420 if (!getLangOpts().CPlusPlus
&& !Diags
.isIgnored(MixedDeclsCodeID
, L
)) {
421 // Note that __extension__ can be around a decl.
423 // Skip over all declarations.
424 for (; i
!= NumElts
&& isa
<DeclStmt
>(Elts
[i
]); ++i
)
427 // We found the end of the list or a statement. Scan for another declstmt.
428 for (; i
!= NumElts
&& !isa
<DeclStmt
>(Elts
[i
]); ++i
)
432 Decl
*D
= *cast
<DeclStmt
>(Elts
[i
])->decl_begin();
433 Diag(D
->getLocation(), MixedDeclsCodeID
);
437 // Check for suspicious empty body (null statement) in `for' and `while'
438 // statements. Don't do anything for template instantiations, this just adds
440 if (NumElts
!= 0 && !CurrentInstantiationScope
&&
441 getCurCompoundScope().HasEmptyLoopBodies
) {
442 for (unsigned i
= 0; i
!= NumElts
- 1; ++i
)
443 DiagnoseEmptyLoopBody(Elts
[i
], Elts
[i
+ 1]);
446 // Calculate difference between FP options in this compound statement and in
447 // the enclosing one. If this is a function body, take the difference against
448 // default options. In this case the difference will indicate options that are
449 // changed upon entry to the statement.
450 FPOptions FPO
= (getCurFunction()->CompoundScopes
.size() == 1)
451 ? FPOptions(getLangOpts())
452 : getCurCompoundScope().InitialFPFeatures
;
453 FPOptionsOverride FPDiff
= getCurFPFeatures().getChangesFrom(FPO
);
455 return CompoundStmt::Create(Context
, Elts
, FPDiff
, L
, R
);
459 Sema::ActOnCaseExpr(SourceLocation CaseLoc
, ExprResult Val
) {
463 if (DiagnoseUnexpandedParameterPack(Val
.get()))
466 // If we're not inside a switch, let the 'case' statement handling diagnose
467 // this. Just clean up after the expression as best we can.
468 if (getCurFunction()->SwitchStack
.empty())
469 return ActOnFinishFullExpr(Val
.get(), Val
.get()->getExprLoc(), false,
470 getLangOpts().CPlusPlus11
);
473 getCurFunction()->SwitchStack
.back().getPointer()->getCond();
476 QualType CondType
= CondExpr
->getType();
478 auto CheckAndFinish
= [&](Expr
*E
) {
479 if (CondType
->isDependentType() || E
->isTypeDependent())
480 return ExprResult(E
);
482 if (getLangOpts().CPlusPlus11
) {
483 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
484 // constant expression of the promoted type of the switch condition.
485 llvm::APSInt TempVal
;
486 return CheckConvertedConstantExpression(E
, CondType
, TempVal
,
491 if (!E
->isValueDependent())
492 ER
= VerifyIntegerConstantExpression(E
, AllowFold
);
494 ER
= DefaultLvalueConversion(ER
.get());
496 ER
= ImpCastExprToType(ER
.get(), CondType
, CK_IntegralCast
);
498 ER
= ActOnFinishFullExpr(ER
.get(), ER
.get()->getExprLoc(), false);
502 ExprResult Converted
= CorrectDelayedTyposInExpr(
503 Val
, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
505 if (Converted
.get() == Val
.get())
506 Converted
= CheckAndFinish(Val
.get());
511 Sema::ActOnCaseStmt(SourceLocation CaseLoc
, ExprResult LHSVal
,
512 SourceLocation DotDotDotLoc
, ExprResult RHSVal
,
513 SourceLocation ColonLoc
) {
514 assert((LHSVal
.isInvalid() || LHSVal
.get()) && "missing LHS value");
515 assert((DotDotDotLoc
.isInvalid() ? RHSVal
.isUnset()
516 : RHSVal
.isInvalid() || RHSVal
.get()) &&
517 "missing RHS value");
519 if (getCurFunction()->SwitchStack
.empty()) {
520 Diag(CaseLoc
, diag::err_case_not_in_switch
);
524 if (LHSVal
.isInvalid() || RHSVal
.isInvalid()) {
525 getCurFunction()->SwitchStack
.back().setInt(true);
529 auto *CS
= CaseStmt::Create(Context
, LHSVal
.get(), RHSVal
.get(),
530 CaseLoc
, DotDotDotLoc
, ColonLoc
);
531 getCurFunction()->SwitchStack
.back().getPointer()->addSwitchCase(CS
);
535 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
536 void Sema::ActOnCaseStmtBody(Stmt
*S
, Stmt
*SubStmt
) {
537 cast
<CaseStmt
>(S
)->setSubStmt(SubStmt
);
541 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc
, SourceLocation ColonLoc
,
542 Stmt
*SubStmt
, Scope
*CurScope
) {
543 if (getCurFunction()->SwitchStack
.empty()) {
544 Diag(DefaultLoc
, diag::err_default_not_in_switch
);
548 DefaultStmt
*DS
= new (Context
) DefaultStmt(DefaultLoc
, ColonLoc
, SubStmt
);
549 getCurFunction()->SwitchStack
.back().getPointer()->addSwitchCase(DS
);
554 Sema::ActOnLabelStmt(SourceLocation IdentLoc
, LabelDecl
*TheDecl
,
555 SourceLocation ColonLoc
, Stmt
*SubStmt
) {
556 // If the label was multiply defined, reject it now.
557 if (TheDecl
->getStmt()) {
558 Diag(IdentLoc
, diag::err_redefinition_of_label
) << TheDecl
->getDeclName();
559 Diag(TheDecl
->getLocation(), diag::note_previous_definition
);
563 ReservedIdentifierStatus Status
= TheDecl
->isReserved(getLangOpts());
564 if (isReservedInAllContexts(Status
) &&
565 !Context
.getSourceManager().isInSystemHeader(IdentLoc
))
566 Diag(IdentLoc
, diag::warn_reserved_extern_symbol
)
567 << TheDecl
<< static_cast<int>(Status
);
569 // Otherwise, things are good. Fill in the declaration and return it.
570 LabelStmt
*LS
= new (Context
) LabelStmt(IdentLoc
, TheDecl
, SubStmt
);
571 TheDecl
->setStmt(LS
);
572 if (!TheDecl
->isGnuLocal()) {
573 TheDecl
->setLocStart(IdentLoc
);
574 if (!TheDecl
->isMSAsmLabel()) {
575 // Don't update the location of MS ASM labels. These will result in
576 // a diagnostic, and changing the location here will mess that up.
577 TheDecl
->setLocation(IdentLoc
);
583 StmtResult
Sema::BuildAttributedStmt(SourceLocation AttrsLoc
,
584 ArrayRef
<const Attr
*> Attrs
,
586 // FIXME: this code should move when a planned refactoring around statement
588 for (const auto *A
: Attrs
) {
589 if (A
->getKind() == attr::MustTail
) {
590 if (!checkAndRewriteMustTailAttr(SubStmt
, *A
)) {
593 setFunctionHasMustTail();
597 return AttributedStmt::Create(Context
, AttrsLoc
, Attrs
, SubStmt
);
600 StmtResult
Sema::ActOnAttributedStmt(const ParsedAttributes
&Attrs
,
602 SmallVector
<const Attr
*, 1> SemanticAttrs
;
603 ProcessStmtAttributes(SubStmt
, Attrs
, SemanticAttrs
);
604 if (!SemanticAttrs
.empty())
605 return BuildAttributedStmt(Attrs
.Range
.getBegin(), SemanticAttrs
, SubStmt
);
606 // If none of the attributes applied, that's fine, we can recover by
607 // returning the substatement directly instead of making an AttributedStmt
608 // with no attributes on it.
612 bool Sema::checkAndRewriteMustTailAttr(Stmt
*St
, const Attr
&MTA
) {
613 ReturnStmt
*R
= cast
<ReturnStmt
>(St
);
614 Expr
*E
= R
->getRetValue();
616 if (CurContext
->isDependentContext() || (E
&& E
->isInstantiationDependent()))
617 // We have to suspend our check until template instantiation time.
620 if (!checkMustTailAttr(St
, MTA
))
623 // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
624 // Currently it does not skip implicit constructors in an initialization
626 auto IgnoreImplicitAsWritten
= [](Expr
*E
) -> Expr
* {
627 return IgnoreExprNodes(E
, IgnoreImplicitAsWrittenSingleStep
,
628 IgnoreElidableImplicitConstructorSingleStep
);
631 // Now that we have verified that 'musttail' is valid here, rewrite the
632 // return value to remove all implicit nodes, but retain parentheses.
633 R
->setRetValue(IgnoreImplicitAsWritten(E
));
637 bool Sema::checkMustTailAttr(const Stmt
*St
, const Attr
&MTA
) {
638 assert(!CurContext
->isDependentContext() &&
639 "musttail cannot be checked from a dependent context");
641 // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
642 auto IgnoreParenImplicitAsWritten
= [](const Expr
*E
) -> const Expr
* {
643 return IgnoreExprNodes(const_cast<Expr
*>(E
), IgnoreParensSingleStep
,
644 IgnoreImplicitAsWrittenSingleStep
,
645 IgnoreElidableImplicitConstructorSingleStep
);
648 const Expr
*E
= cast
<ReturnStmt
>(St
)->getRetValue();
649 const auto *CE
= dyn_cast_or_null
<CallExpr
>(IgnoreParenImplicitAsWritten(E
));
652 Diag(St
->getBeginLoc(), diag::err_musttail_needs_call
) << &MTA
;
656 if (const auto *EWC
= dyn_cast
<ExprWithCleanups
>(E
)) {
657 if (EWC
->cleanupsHaveSideEffects()) {
658 Diag(St
->getBeginLoc(), diag::err_musttail_needs_trivial_args
) << &MTA
;
663 // We need to determine the full function type (including "this" type, if any)
664 // for both caller and callee.
669 ft_non_static_member
,
670 ft_pointer_to_member
,
671 } MemberType
= ft_non_member
;
674 const FunctionProtoType
*Func
;
675 const CXXMethodDecl
*Method
= nullptr;
676 } CallerType
, CalleeType
;
678 auto GetMethodType
= [this, St
, MTA
](const CXXMethodDecl
*CMD
, FuncType
&Type
,
679 bool IsCallee
) -> bool {
680 if (isa
<CXXConstructorDecl
, CXXDestructorDecl
>(CMD
)) {
681 Diag(St
->getBeginLoc(), diag::err_musttail_structors_forbidden
)
682 << IsCallee
<< isa
<CXXDestructorDecl
>(CMD
);
684 Diag(CMD
->getBeginLoc(), diag::note_musttail_structors_forbidden
)
685 << isa
<CXXDestructorDecl
>(CMD
);
686 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
690 Type
.MemberType
= FuncType::ft_static_member
;
692 Type
.This
= CMD
->getFunctionObjectParameterType();
693 Type
.MemberType
= FuncType::ft_non_static_member
;
695 Type
.Func
= CMD
->getType()->castAs
<FunctionProtoType
>();
699 const auto *CallerDecl
= dyn_cast
<FunctionDecl
>(CurContext
);
701 // Find caller function signature.
704 if (isa
<BlockDecl
>(CurContext
))
706 else if (isa
<ObjCMethodDecl
>(CurContext
))
710 Diag(St
->getBeginLoc(), diag::err_musttail_forbidden_from_this_context
)
711 << &MTA
<< ContextType
;
713 } else if (const auto *CMD
= dyn_cast
<CXXMethodDecl
>(CurContext
)) {
714 // Caller is a class/struct method.
715 if (!GetMethodType(CMD
, CallerType
, false))
718 // Caller is a non-method function.
719 CallerType
.Func
= CallerDecl
->getType()->getAs
<FunctionProtoType
>();
722 const Expr
*CalleeExpr
= CE
->getCallee()->IgnoreParens();
723 const auto *CalleeBinOp
= dyn_cast
<BinaryOperator
>(CalleeExpr
);
724 SourceLocation CalleeLoc
= CE
->getCalleeDecl()
725 ? CE
->getCalleeDecl()->getBeginLoc()
728 // Find callee function signature.
729 if (const CXXMethodDecl
*CMD
=
730 dyn_cast_or_null
<CXXMethodDecl
>(CE
->getCalleeDecl())) {
731 // Call is: obj.method(), obj->method(), functor(), etc.
732 if (!GetMethodType(CMD
, CalleeType
, true))
734 } else if (CalleeBinOp
&& CalleeBinOp
->isPtrMemOp()) {
735 // Call is: obj->*method_ptr or obj.*method_ptr
737 CalleeBinOp
->getRHS()->getType()->castAs
<MemberPointerType
>();
738 CalleeType
.This
= QualType(MPT
->getClass(), 0);
739 CalleeType
.Func
= MPT
->getPointeeType()->castAs
<FunctionProtoType
>();
740 CalleeType
.MemberType
= FuncType::ft_pointer_to_member
;
741 } else if (isa
<CXXPseudoDestructorExpr
>(CalleeExpr
)) {
742 Diag(St
->getBeginLoc(), diag::err_musttail_structors_forbidden
)
743 << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
744 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
747 // Non-method function.
749 CalleeExpr
->getType()->getPointeeType()->getAs
<FunctionProtoType
>();
752 // Both caller and callee must have a prototype (no K&R declarations).
753 if (!CalleeType
.Func
|| !CallerType
.Func
) {
754 Diag(St
->getBeginLoc(), diag::err_musttail_needs_prototype
) << &MTA
;
755 if (!CalleeType
.Func
&& CE
->getDirectCallee()) {
756 Diag(CE
->getDirectCallee()->getBeginLoc(),
757 diag::note_musttail_fix_non_prototype
);
759 if (!CallerType
.Func
)
760 Diag(CallerDecl
->getBeginLoc(), diag::note_musttail_fix_non_prototype
);
764 // Caller and callee must have matching calling conventions.
766 // Some calling conventions are physically capable of supporting tail calls
767 // even if the function types don't perfectly match. LLVM is currently too
768 // strict to allow this, but if LLVM added support for this in the future, we
769 // could exit early here and skip the remaining checks if the functions are
770 // using such a calling convention.
771 if (CallerType
.Func
->getCallConv() != CalleeType
.Func
->getCallConv()) {
772 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(CE
->getCalleeDecl()))
773 Diag(St
->getBeginLoc(), diag::err_musttail_callconv_mismatch
)
774 << true << ND
->getDeclName();
776 Diag(St
->getBeginLoc(), diag::err_musttail_callconv_mismatch
) << false;
777 Diag(CalleeLoc
, diag::note_musttail_callconv_mismatch
)
778 << FunctionType::getNameForCallConv(CallerType
.Func
->getCallConv())
779 << FunctionType::getNameForCallConv(CalleeType
.Func
->getCallConv());
780 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
784 if (CalleeType
.Func
->isVariadic() || CallerType
.Func
->isVariadic()) {
785 Diag(St
->getBeginLoc(), diag::err_musttail_no_variadic
) << &MTA
;
789 // Caller and callee must match in whether they have a "this" parameter.
790 if (CallerType
.This
.isNull() != CalleeType
.This
.isNull()) {
791 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(CE
->getCalleeDecl())) {
792 Diag(St
->getBeginLoc(), diag::err_musttail_member_mismatch
)
793 << CallerType
.MemberType
<< CalleeType
.MemberType
<< true
794 << ND
->getDeclName();
795 Diag(CalleeLoc
, diag::note_musttail_callee_defined_here
)
796 << ND
->getDeclName();
798 Diag(St
->getBeginLoc(), diag::err_musttail_member_mismatch
)
799 << CallerType
.MemberType
<< CalleeType
.MemberType
<< false;
800 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
804 auto CheckTypesMatch
= [this](FuncType CallerType
, FuncType CalleeType
,
805 PartialDiagnostic
&PD
) -> bool {
809 ft_parameter_mismatch
,
813 auto DoTypesMatch
= [this, &PD
](QualType A
, QualType B
,
814 unsigned Select
) -> bool {
815 if (!Context
.hasSimilarType(A
, B
)) {
816 PD
<< Select
<< A
.getUnqualifiedType() << B
.getUnqualifiedType();
822 if (!CallerType
.This
.isNull() &&
823 !DoTypesMatch(CallerType
.This
, CalleeType
.This
, ft_different_class
))
826 if (!DoTypesMatch(CallerType
.Func
->getReturnType(),
827 CalleeType
.Func
->getReturnType(), ft_return_type
))
830 if (CallerType
.Func
->getNumParams() != CalleeType
.Func
->getNumParams()) {
831 PD
<< ft_parameter_arity
<< CallerType
.Func
->getNumParams()
832 << CalleeType
.Func
->getNumParams();
836 ArrayRef
<QualType
> CalleeParams
= CalleeType
.Func
->getParamTypes();
837 ArrayRef
<QualType
> CallerParams
= CallerType
.Func
->getParamTypes();
838 size_t N
= CallerType
.Func
->getNumParams();
839 for (size_t I
= 0; I
< N
; I
++) {
840 if (!DoTypesMatch(CalleeParams
[I
], CallerParams
[I
],
841 ft_parameter_mismatch
)) {
842 PD
<< static_cast<int>(I
) + 1;
850 PartialDiagnostic PD
= PDiag(diag::note_musttail_mismatch
);
851 if (!CheckTypesMatch(CallerType
, CalleeType
, PD
)) {
852 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(CE
->getCalleeDecl()))
853 Diag(St
->getBeginLoc(), diag::err_musttail_mismatch
)
854 << true << ND
->getDeclName();
856 Diag(St
->getBeginLoc(), diag::err_musttail_mismatch
) << false;
858 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
866 class CommaVisitor
: public EvaluatedExprVisitor
<CommaVisitor
> {
867 typedef EvaluatedExprVisitor
<CommaVisitor
> Inherited
;
870 CommaVisitor(Sema
&SemaRef
) : Inherited(SemaRef
.Context
), SemaRef(SemaRef
) {}
871 void VisitBinaryOperator(BinaryOperator
*E
) {
872 if (E
->getOpcode() == BO_Comma
)
873 SemaRef
.DiagnoseCommaOperator(E
->getLHS(), E
->getExprLoc());
874 EvaluatedExprVisitor
<CommaVisitor
>::VisitBinaryOperator(E
);
879 StmtResult
Sema::ActOnIfStmt(SourceLocation IfLoc
,
880 IfStatementKind StatementKind
,
881 SourceLocation LParenLoc
, Stmt
*InitStmt
,
882 ConditionResult Cond
, SourceLocation RParenLoc
,
883 Stmt
*thenStmt
, SourceLocation ElseLoc
,
885 if (Cond
.isInvalid())
888 bool ConstevalOrNegatedConsteval
=
889 StatementKind
== IfStatementKind::ConstevalNonNegated
||
890 StatementKind
== IfStatementKind::ConstevalNegated
;
892 Expr
*CondExpr
= Cond
.get().second
;
893 assert((CondExpr
|| ConstevalOrNegatedConsteval
) &&
894 "If statement: missing condition");
895 // Only call the CommaVisitor when not C89 due to differences in scope flags.
896 if (CondExpr
&& (getLangOpts().C99
|| getLangOpts().CPlusPlus
) &&
897 !Diags
.isIgnored(diag::warn_comma_operator
, CondExpr
->getExprLoc()))
898 CommaVisitor(*this).Visit(CondExpr
);
900 if (!ConstevalOrNegatedConsteval
&& !elseStmt
)
901 DiagnoseEmptyStmtBody(RParenLoc
, thenStmt
, diag::warn_empty_if_body
);
903 if (ConstevalOrNegatedConsteval
||
904 StatementKind
== IfStatementKind::Constexpr
) {
905 auto DiagnoseLikelihood
= [&](const Stmt
*S
) {
906 if (const Attr
*A
= Stmt::getLikelihoodAttr(S
)) {
907 Diags
.Report(A
->getLocation(),
908 diag::warn_attribute_has_no_effect_on_compile_time_if
)
909 << A
<< ConstevalOrNegatedConsteval
<< A
->getRange();
911 diag::note_attribute_has_no_effect_on_compile_time_if_here
)
912 << ConstevalOrNegatedConsteval
913 << SourceRange(IfLoc
, (ConstevalOrNegatedConsteval
914 ? thenStmt
->getBeginLoc()
916 .getLocWithOffset(-1));
919 DiagnoseLikelihood(thenStmt
);
920 DiagnoseLikelihood(elseStmt
);
922 std::tuple
<bool, const Attr
*, const Attr
*> LHC
=
923 Stmt::determineLikelihoodConflict(thenStmt
, elseStmt
);
924 if (std::get
<0>(LHC
)) {
925 const Attr
*ThenAttr
= std::get
<1>(LHC
);
926 const Attr
*ElseAttr
= std::get
<2>(LHC
);
927 Diags
.Report(ThenAttr
->getLocation(),
928 diag::warn_attributes_likelihood_ifstmt_conflict
)
929 << ThenAttr
<< ThenAttr
->getRange();
930 Diags
.Report(ElseAttr
->getLocation(), diag::note_conflicting_attribute
)
931 << ElseAttr
<< ElseAttr
->getRange();
935 if (ConstevalOrNegatedConsteval
) {
936 bool Immediate
= ExprEvalContexts
.back().Context
==
937 ExpressionEvaluationContext::ImmediateFunctionContext
;
938 if (CurContext
->isFunctionOrMethod()) {
940 dyn_cast
<FunctionDecl
>(Decl::castFromDeclContext(CurContext
));
941 if (FD
&& FD
->isImmediateFunction())
944 if (isUnevaluatedContext() || Immediate
)
945 Diags
.Report(IfLoc
, diag::warn_consteval_if_always_true
) << Immediate
;
948 return BuildIfStmt(IfLoc
, StatementKind
, LParenLoc
, InitStmt
, Cond
, RParenLoc
,
949 thenStmt
, ElseLoc
, elseStmt
);
952 StmtResult
Sema::BuildIfStmt(SourceLocation IfLoc
,
953 IfStatementKind StatementKind
,
954 SourceLocation LParenLoc
, Stmt
*InitStmt
,
955 ConditionResult Cond
, SourceLocation RParenLoc
,
956 Stmt
*thenStmt
, SourceLocation ElseLoc
,
958 if (Cond
.isInvalid())
961 if (StatementKind
!= IfStatementKind::Ordinary
||
962 isa
<ObjCAvailabilityCheckExpr
>(Cond
.get().second
))
963 setFunctionHasBranchProtectedScope();
965 return IfStmt::Create(Context
, IfLoc
, StatementKind
, InitStmt
,
966 Cond
.get().first
, Cond
.get().second
, LParenLoc
,
967 RParenLoc
, thenStmt
, ElseLoc
, elseStmt
);
971 struct CaseCompareFunctor
{
972 bool operator()(const std::pair
<llvm::APSInt
, CaseStmt
*> &LHS
,
973 const llvm::APSInt
&RHS
) {
974 return LHS
.first
< RHS
;
976 bool operator()(const std::pair
<llvm::APSInt
, CaseStmt
*> &LHS
,
977 const std::pair
<llvm::APSInt
, CaseStmt
*> &RHS
) {
978 return LHS
.first
< RHS
.first
;
980 bool operator()(const llvm::APSInt
&LHS
,
981 const std::pair
<llvm::APSInt
, CaseStmt
*> &RHS
) {
982 return LHS
< RHS
.first
;
987 /// CmpCaseVals - Comparison predicate for sorting case values.
989 static bool CmpCaseVals(const std::pair
<llvm::APSInt
, CaseStmt
*>& lhs
,
990 const std::pair
<llvm::APSInt
, CaseStmt
*>& rhs
) {
991 if (lhs
.first
< rhs
.first
)
994 if (lhs
.first
== rhs
.first
&&
995 lhs
.second
->getCaseLoc() < rhs
.second
->getCaseLoc())
1000 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
1002 static bool CmpEnumVals(const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& lhs
,
1003 const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& rhs
)
1005 return lhs
.first
< rhs
.first
;
1008 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
1010 static bool EqEnumVals(const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& lhs
,
1011 const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& rhs
)
1013 return lhs
.first
== rhs
.first
;
1016 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
1017 /// potentially integral-promoted expression @p expr.
1018 static QualType
GetTypeBeforeIntegralPromotion(const Expr
*&E
) {
1019 if (const auto *FE
= dyn_cast
<FullExpr
>(E
))
1020 E
= FE
->getSubExpr();
1021 while (const auto *ImpCast
= dyn_cast
<ImplicitCastExpr
>(E
)) {
1022 if (ImpCast
->getCastKind() != CK_IntegralCast
) break;
1023 E
= ImpCast
->getSubExpr();
1025 return E
->getType();
1028 ExprResult
Sema::CheckSwitchCondition(SourceLocation SwitchLoc
, Expr
*Cond
) {
1029 class SwitchConvertDiagnoser
: public ICEConvertDiagnoser
{
1033 SwitchConvertDiagnoser(Expr
*Cond
)
1034 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
1037 SemaDiagnosticBuilder
diagnoseNotInt(Sema
&S
, SourceLocation Loc
,
1038 QualType T
) override
{
1039 return S
.Diag(Loc
, diag::err_typecheck_statement_requires_integer
) << T
;
1042 SemaDiagnosticBuilder
diagnoseIncomplete(
1043 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
1044 return S
.Diag(Loc
, diag::err_switch_incomplete_class_type
)
1045 << T
<< Cond
->getSourceRange();
1048 SemaDiagnosticBuilder
diagnoseExplicitConv(
1049 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
1050 return S
.Diag(Loc
, diag::err_switch_explicit_conversion
) << T
<< ConvTy
;
1053 SemaDiagnosticBuilder
noteExplicitConv(
1054 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
1055 return S
.Diag(Conv
->getLocation(), diag::note_switch_conversion
)
1056 << ConvTy
->isEnumeralType() << ConvTy
;
1059 SemaDiagnosticBuilder
diagnoseAmbiguous(Sema
&S
, SourceLocation Loc
,
1060 QualType T
) override
{
1061 return S
.Diag(Loc
, diag::err_switch_multiple_conversions
) << T
;
1064 SemaDiagnosticBuilder
noteAmbiguous(
1065 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
1066 return S
.Diag(Conv
->getLocation(), diag::note_switch_conversion
)
1067 << ConvTy
->isEnumeralType() << ConvTy
;
1070 SemaDiagnosticBuilder
diagnoseConversion(
1071 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
1072 llvm_unreachable("conversion functions are permitted");
1074 } SwitchDiagnoser(Cond
);
1076 ExprResult CondResult
=
1077 PerformContextualImplicitConversion(SwitchLoc
, Cond
, SwitchDiagnoser
);
1078 if (CondResult
.isInvalid())
1081 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
1082 // failed and produced a diagnostic.
1083 Cond
= CondResult
.get();
1084 if (!Cond
->isTypeDependent() &&
1085 !Cond
->getType()->isIntegralOrEnumerationType())
1088 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
1089 return UsualUnaryConversions(Cond
);
1092 StmtResult
Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc
,
1093 SourceLocation LParenLoc
,
1094 Stmt
*InitStmt
, ConditionResult Cond
,
1095 SourceLocation RParenLoc
) {
1096 Expr
*CondExpr
= Cond
.get().second
;
1097 assert((Cond
.isInvalid() || CondExpr
) && "switch with no condition");
1099 if (CondExpr
&& !CondExpr
->isTypeDependent()) {
1100 // We have already converted the expression to an integral or enumeration
1101 // type, when we parsed the switch condition. There are cases where we don't
1102 // have an appropriate type, e.g. a typo-expr Cond was corrected to an
1103 // inappropriate-type expr, we just return an error.
1104 if (!CondExpr
->getType()->isIntegralOrEnumerationType())
1106 if (CondExpr
->isKnownToHaveBooleanValue()) {
1107 // switch(bool_expr) {...} is often a programmer error, e.g.
1108 // switch(n && mask) { ... } // Doh - should be "n & mask".
1109 // One can always use an if statement instead of switch(bool_expr).
1110 Diag(SwitchLoc
, diag::warn_bool_switch_condition
)
1111 << CondExpr
->getSourceRange();
1115 setFunctionHasBranchIntoScope();
1117 auto *SS
= SwitchStmt::Create(Context
, InitStmt
, Cond
.get().first
, CondExpr
,
1118 LParenLoc
, RParenLoc
);
1119 getCurFunction()->SwitchStack
.push_back(
1120 FunctionScopeInfo::SwitchInfo(SS
, false));
1124 static void AdjustAPSInt(llvm::APSInt
&Val
, unsigned BitWidth
, bool IsSigned
) {
1125 Val
= Val
.extOrTrunc(BitWidth
);
1126 Val
.setIsSigned(IsSigned
);
1129 /// Check the specified case value is in range for the given unpromoted switch
1131 static void checkCaseValue(Sema
&S
, SourceLocation Loc
, const llvm::APSInt
&Val
,
1132 unsigned UnpromotedWidth
, bool UnpromotedSign
) {
1133 // In C++11 onwards, this is checked by the language rules.
1134 if (S
.getLangOpts().CPlusPlus11
)
1137 // If the case value was signed and negative and the switch expression is
1138 // unsigned, don't bother to warn: this is implementation-defined behavior.
1139 // FIXME: Introduce a second, default-ignored warning for this case?
1140 if (UnpromotedWidth
< Val
.getBitWidth()) {
1141 llvm::APSInt
ConvVal(Val
);
1142 AdjustAPSInt(ConvVal
, UnpromotedWidth
, UnpromotedSign
);
1143 AdjustAPSInt(ConvVal
, Val
.getBitWidth(), Val
.isSigned());
1144 // FIXME: Use different diagnostics for overflow in conversion to promoted
1145 // type versus "switch expression cannot have this value". Use proper
1146 // IntRange checking rather than just looking at the unpromoted type here.
1148 S
.Diag(Loc
, diag::warn_case_value_overflow
) << toString(Val
, 10)
1149 << toString(ConvVal
, 10);
1153 typedef SmallVector
<std::pair
<llvm::APSInt
, EnumConstantDecl
*>, 64> EnumValsTy
;
1155 /// Returns true if we should emit a diagnostic about this case expression not
1156 /// being a part of the enum used in the switch controlling expression.
1157 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema
&S
,
1159 const Expr
*CaseExpr
,
1160 EnumValsTy::iterator
&EI
,
1161 EnumValsTy::iterator
&EIEnd
,
1162 const llvm::APSInt
&Val
) {
1163 if (!ED
->isClosed())
1166 if (const DeclRefExpr
*DRE
=
1167 dyn_cast
<DeclRefExpr
>(CaseExpr
->IgnoreParenImpCasts())) {
1168 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
1169 QualType VarType
= VD
->getType();
1170 QualType EnumType
= S
.Context
.getTypeDeclType(ED
);
1171 if (VD
->hasGlobalStorage() && VarType
.isConstQualified() &&
1172 S
.Context
.hasSameUnqualifiedType(EnumType
, VarType
))
1177 if (ED
->hasAttr
<FlagEnumAttr
>())
1178 return !S
.IsValueInFlagEnum(ED
, Val
, false);
1180 while (EI
!= EIEnd
&& EI
->first
< Val
)
1183 if (EI
!= EIEnd
&& EI
->first
== Val
)
1189 static void checkEnumTypesInSwitchStmt(Sema
&S
, const Expr
*Cond
,
1191 QualType CondType
= Cond
->getType();
1192 QualType CaseType
= Case
->getType();
1194 const EnumType
*CondEnumType
= CondType
->getAs
<EnumType
>();
1195 const EnumType
*CaseEnumType
= CaseType
->getAs
<EnumType
>();
1196 if (!CondEnumType
|| !CaseEnumType
)
1199 // Ignore anonymous enums.
1200 if (!CondEnumType
->getDecl()->getIdentifier() &&
1201 !CondEnumType
->getDecl()->getTypedefNameForAnonDecl())
1203 if (!CaseEnumType
->getDecl()->getIdentifier() &&
1204 !CaseEnumType
->getDecl()->getTypedefNameForAnonDecl())
1207 if (S
.Context
.hasSameUnqualifiedType(CondType
, CaseType
))
1210 S
.Diag(Case
->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch
)
1211 << CondType
<< CaseType
<< Cond
->getSourceRange()
1212 << Case
->getSourceRange();
1216 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc
, Stmt
*Switch
,
1218 SwitchStmt
*SS
= cast
<SwitchStmt
>(Switch
);
1219 bool CaseListIsIncomplete
= getCurFunction()->SwitchStack
.back().getInt();
1220 assert(SS
== getCurFunction()->SwitchStack
.back().getPointer() &&
1221 "switch stack missing push/pop!");
1223 getCurFunction()->SwitchStack
.pop_back();
1225 if (!BodyStmt
) return StmtError();
1226 SS
->setBody(BodyStmt
, SwitchLoc
);
1228 Expr
*CondExpr
= SS
->getCond();
1229 if (!CondExpr
) return StmtError();
1231 QualType CondType
= CondExpr
->getType();
1234 // Integral promotions are performed (on the switch condition).
1236 // A case value unrepresentable by the original switch condition
1237 // type (before the promotion) doesn't make sense, even when it can
1238 // be represented by the promoted type. Therefore we need to find
1239 // the pre-promotion type of the switch condition.
1240 const Expr
*CondExprBeforePromotion
= CondExpr
;
1241 QualType CondTypeBeforePromotion
=
1242 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion
);
1244 // Get the bitwidth of the switched-on value after promotions. We must
1245 // convert the integer case values to this width before comparison.
1246 bool HasDependentValue
1247 = CondExpr
->isTypeDependent() || CondExpr
->isValueDependent();
1248 unsigned CondWidth
= HasDependentValue
? 0 : Context
.getIntWidth(CondType
);
1249 bool CondIsSigned
= CondType
->isSignedIntegerOrEnumerationType();
1251 // Get the width and signedness that the condition might actually have, for
1252 // warning purposes.
1253 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
1255 unsigned CondWidthBeforePromotion
1256 = HasDependentValue
? 0 : Context
.getIntWidth(CondTypeBeforePromotion
);
1257 bool CondIsSignedBeforePromotion
1258 = CondTypeBeforePromotion
->isSignedIntegerOrEnumerationType();
1260 // Accumulate all of the case values in a vector so that we can sort them
1261 // and detect duplicates. This vector contains the APInt for the case after
1262 // it has been converted to the condition type.
1263 typedef SmallVector
<std::pair
<llvm::APSInt
, CaseStmt
*>, 64> CaseValsTy
;
1264 CaseValsTy CaseVals
;
1266 // Keep track of any GNU case ranges we see. The APSInt is the low value.
1267 typedef std::vector
<std::pair
<llvm::APSInt
, CaseStmt
*> > CaseRangesTy
;
1268 CaseRangesTy CaseRanges
;
1270 DefaultStmt
*TheDefaultStmt
= nullptr;
1272 bool CaseListIsErroneous
= false;
1274 for (SwitchCase
*SC
= SS
->getSwitchCaseList(); SC
&& !HasDependentValue
;
1275 SC
= SC
->getNextSwitchCase()) {
1277 if (DefaultStmt
*DS
= dyn_cast
<DefaultStmt
>(SC
)) {
1278 if (TheDefaultStmt
) {
1279 Diag(DS
->getDefaultLoc(), diag::err_multiple_default_labels_defined
);
1280 Diag(TheDefaultStmt
->getDefaultLoc(), diag::note_duplicate_case_prev
);
1282 // FIXME: Remove the default statement from the switch block so that
1283 // we'll return a valid AST. This requires recursing down the AST and
1284 // finding it, not something we are set up to do right now. For now,
1285 // just lop the entire switch stmt out of the AST.
1286 CaseListIsErroneous
= true;
1288 TheDefaultStmt
= DS
;
1291 CaseStmt
*CS
= cast
<CaseStmt
>(SC
);
1293 Expr
*Lo
= CS
->getLHS();
1295 if (Lo
->isValueDependent()) {
1296 HasDependentValue
= true;
1300 // We already verified that the expression has a constant value;
1301 // get that value (prior to conversions).
1302 const Expr
*LoBeforePromotion
= Lo
;
1303 GetTypeBeforeIntegralPromotion(LoBeforePromotion
);
1304 llvm::APSInt LoVal
= LoBeforePromotion
->EvaluateKnownConstInt(Context
);
1306 // Check the unconverted value is within the range of possible values of
1307 // the switch expression.
1308 checkCaseValue(*this, Lo
->getBeginLoc(), LoVal
, CondWidthBeforePromotion
,
1309 CondIsSignedBeforePromotion
);
1311 // FIXME: This duplicates the check performed for warn_not_in_enum below.
1312 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion
,
1315 // Convert the value to the same width/sign as the condition.
1316 AdjustAPSInt(LoVal
, CondWidth
, CondIsSigned
);
1318 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
1320 if (CS
->getRHS()->isValueDependent()) {
1321 HasDependentValue
= true;
1324 CaseRanges
.push_back(std::make_pair(LoVal
, CS
));
1326 CaseVals
.push_back(std::make_pair(LoVal
, CS
));
1330 if (!HasDependentValue
) {
1331 // If we don't have a default statement, check whether the
1332 // condition is constant.
1333 llvm::APSInt ConstantCondValue
;
1334 bool HasConstantCond
= false;
1335 if (!TheDefaultStmt
) {
1336 Expr::EvalResult Result
;
1337 HasConstantCond
= CondExpr
->EvaluateAsInt(Result
, Context
,
1338 Expr::SE_AllowSideEffects
);
1339 if (Result
.Val
.isInt())
1340 ConstantCondValue
= Result
.Val
.getInt();
1341 assert(!HasConstantCond
||
1342 (ConstantCondValue
.getBitWidth() == CondWidth
&&
1343 ConstantCondValue
.isSigned() == CondIsSigned
));
1345 bool ShouldCheckConstantCond
= HasConstantCond
;
1347 // Sort all the scalar case values so we can easily detect duplicates.
1348 llvm::stable_sort(CaseVals
, CmpCaseVals
);
1350 if (!CaseVals
.empty()) {
1351 for (unsigned i
= 0, e
= CaseVals
.size(); i
!= e
; ++i
) {
1352 if (ShouldCheckConstantCond
&&
1353 CaseVals
[i
].first
== ConstantCondValue
)
1354 ShouldCheckConstantCond
= false;
1356 if (i
!= 0 && CaseVals
[i
].first
== CaseVals
[i
-1].first
) {
1357 // If we have a duplicate, report it.
1358 // First, determine if either case value has a name
1359 StringRef PrevString
, CurrString
;
1360 Expr
*PrevCase
= CaseVals
[i
-1].second
->getLHS()->IgnoreParenCasts();
1361 Expr
*CurrCase
= CaseVals
[i
].second
->getLHS()->IgnoreParenCasts();
1362 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(PrevCase
)) {
1363 PrevString
= DeclRef
->getDecl()->getName();
1365 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(CurrCase
)) {
1366 CurrString
= DeclRef
->getDecl()->getName();
1368 SmallString
<16> CaseValStr
;
1369 CaseVals
[i
-1].first
.toString(CaseValStr
);
1371 if (PrevString
== CurrString
)
1372 Diag(CaseVals
[i
].second
->getLHS()->getBeginLoc(),
1373 diag::err_duplicate_case
)
1374 << (PrevString
.empty() ? CaseValStr
.str() : PrevString
);
1376 Diag(CaseVals
[i
].second
->getLHS()->getBeginLoc(),
1377 diag::err_duplicate_case_differing_expr
)
1378 << (PrevString
.empty() ? CaseValStr
.str() : PrevString
)
1379 << (CurrString
.empty() ? CaseValStr
.str() : CurrString
)
1382 Diag(CaseVals
[i
- 1].second
->getLHS()->getBeginLoc(),
1383 diag::note_duplicate_case_prev
);
1384 // FIXME: We really want to remove the bogus case stmt from the
1385 // substmt, but we have no way to do this right now.
1386 CaseListIsErroneous
= true;
1391 // Detect duplicate case ranges, which usually don't exist at all in
1393 if (!CaseRanges
.empty()) {
1394 // Sort all the case ranges by their low value so we can easily detect
1395 // overlaps between ranges.
1396 llvm::stable_sort(CaseRanges
);
1398 // Scan the ranges, computing the high values and removing empty ranges.
1399 std::vector
<llvm::APSInt
> HiVals
;
1400 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
1401 llvm::APSInt
&LoVal
= CaseRanges
[i
].first
;
1402 CaseStmt
*CR
= CaseRanges
[i
].second
;
1403 Expr
*Hi
= CR
->getRHS();
1405 const Expr
*HiBeforePromotion
= Hi
;
1406 GetTypeBeforeIntegralPromotion(HiBeforePromotion
);
1407 llvm::APSInt HiVal
= HiBeforePromotion
->EvaluateKnownConstInt(Context
);
1409 // Check the unconverted value is within the range of possible values of
1410 // the switch expression.
1411 checkCaseValue(*this, Hi
->getBeginLoc(), HiVal
,
1412 CondWidthBeforePromotion
, CondIsSignedBeforePromotion
);
1414 // Convert the value to the same width/sign as the condition.
1415 AdjustAPSInt(HiVal
, CondWidth
, CondIsSigned
);
1417 // If the low value is bigger than the high value, the case is empty.
1418 if (LoVal
> HiVal
) {
1419 Diag(CR
->getLHS()->getBeginLoc(), diag::warn_case_empty_range
)
1420 << SourceRange(CR
->getLHS()->getBeginLoc(), Hi
->getEndLoc());
1421 CaseRanges
.erase(CaseRanges
.begin()+i
);
1427 if (ShouldCheckConstantCond
&&
1428 LoVal
<= ConstantCondValue
&&
1429 ConstantCondValue
<= HiVal
)
1430 ShouldCheckConstantCond
= false;
1432 HiVals
.push_back(HiVal
);
1435 // Rescan the ranges, looking for overlap with singleton values and other
1436 // ranges. Since the range list is sorted, we only need to compare case
1437 // ranges with their neighbors.
1438 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
1439 llvm::APSInt
&CRLo
= CaseRanges
[i
].first
;
1440 llvm::APSInt
&CRHi
= HiVals
[i
];
1441 CaseStmt
*CR
= CaseRanges
[i
].second
;
1443 // Check to see whether the case range overlaps with any
1445 CaseStmt
*OverlapStmt
= nullptr;
1446 llvm::APSInt
OverlapVal(32);
1448 // Find the smallest value >= the lower bound. If I is in the
1449 // case range, then we have overlap.
1450 CaseValsTy::iterator I
=
1451 llvm::lower_bound(CaseVals
, CRLo
, CaseCompareFunctor());
1452 if (I
!= CaseVals
.end() && I
->first
< CRHi
) {
1453 OverlapVal
= I
->first
; // Found overlap with scalar.
1454 OverlapStmt
= I
->second
;
1457 // Find the smallest value bigger than the upper bound.
1458 I
= std::upper_bound(I
, CaseVals
.end(), CRHi
, CaseCompareFunctor());
1459 if (I
!= CaseVals
.begin() && (I
-1)->first
>= CRLo
) {
1460 OverlapVal
= (I
-1)->first
; // Found overlap with scalar.
1461 OverlapStmt
= (I
-1)->second
;
1464 // Check to see if this case stmt overlaps with the subsequent
1466 if (i
&& CRLo
<= HiVals
[i
-1]) {
1467 OverlapVal
= HiVals
[i
-1]; // Found overlap with range.
1468 OverlapStmt
= CaseRanges
[i
-1].second
;
1472 // If we have a duplicate, report it.
1473 Diag(CR
->getLHS()->getBeginLoc(), diag::err_duplicate_case
)
1474 << toString(OverlapVal
, 10);
1475 Diag(OverlapStmt
->getLHS()->getBeginLoc(),
1476 diag::note_duplicate_case_prev
);
1477 // FIXME: We really want to remove the bogus case stmt from the
1478 // substmt, but we have no way to do this right now.
1479 CaseListIsErroneous
= true;
1484 // Complain if we have a constant condition and we didn't find a match.
1485 if (!CaseListIsErroneous
&& !CaseListIsIncomplete
&&
1486 ShouldCheckConstantCond
) {
1487 // TODO: it would be nice if we printed enums as enums, chars as
1489 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case_for_condition
)
1490 << toString(ConstantCondValue
, 10)
1491 << CondExpr
->getSourceRange();
1494 // Check to see if switch is over an Enum and handles all of its
1495 // values. We only issue a warning if there is not 'default:', but
1496 // we still do the analysis to preserve this information in the AST
1497 // (which can be used by flow-based analyes).
1499 const EnumType
*ET
= CondTypeBeforePromotion
->getAs
<EnumType
>();
1501 // If switch has default case, then ignore it.
1502 if (!CaseListIsErroneous
&& !CaseListIsIncomplete
&& !HasConstantCond
&&
1503 ET
&& ET
->getDecl()->isCompleteDefinition() &&
1504 !ET
->getDecl()->enumerators().empty()) {
1505 const EnumDecl
*ED
= ET
->getDecl();
1506 EnumValsTy EnumVals
;
1508 // Gather all enum values, set their type and sort them,
1509 // allowing easier comparison with CaseVals.
1510 for (auto *EDI
: ED
->enumerators()) {
1511 llvm::APSInt Val
= EDI
->getInitVal();
1512 AdjustAPSInt(Val
, CondWidth
, CondIsSigned
);
1513 EnumVals
.push_back(std::make_pair(Val
, EDI
));
1515 llvm::stable_sort(EnumVals
, CmpEnumVals
);
1516 auto EI
= EnumVals
.begin(), EIEnd
=
1517 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
1519 // See which case values aren't in enum.
1520 for (CaseValsTy::const_iterator CI
= CaseVals
.begin();
1521 CI
!= CaseVals
.end(); CI
++) {
1522 Expr
*CaseExpr
= CI
->second
->getLHS();
1523 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1525 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1526 << CondTypeBeforePromotion
;
1529 // See which of case ranges aren't in enum
1530 EI
= EnumVals
.begin();
1531 for (CaseRangesTy::const_iterator RI
= CaseRanges
.begin();
1532 RI
!= CaseRanges
.end(); RI
++) {
1533 Expr
*CaseExpr
= RI
->second
->getLHS();
1534 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1536 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1537 << CondTypeBeforePromotion
;
1540 RI
->second
->getRHS()->EvaluateKnownConstInt(Context
);
1541 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
1543 CaseExpr
= RI
->second
->getRHS();
1544 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1546 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1547 << CondTypeBeforePromotion
;
1550 // Check which enum vals aren't in switch
1551 auto CI
= CaseVals
.begin();
1552 auto RI
= CaseRanges
.begin();
1553 bool hasCasesNotInSwitch
= false;
1555 SmallVector
<DeclarationName
,8> UnhandledNames
;
1557 for (EI
= EnumVals
.begin(); EI
!= EIEnd
; EI
++) {
1558 // Don't warn about omitted unavailable EnumConstantDecls.
1559 switch (EI
->second
->getAvailability()) {
1561 // Omitting a deprecated constant is ok; it should never materialize.
1562 case AR_Unavailable
:
1565 case AR_NotYetIntroduced
:
1566 // Partially available enum constants should be present. Note that we
1567 // suppress -Wunguarded-availability diagnostics for such uses.
1572 if (EI
->second
->hasAttr
<UnusedAttr
>())
1575 // Drop unneeded case values
1576 while (CI
!= CaseVals
.end() && CI
->first
< EI
->first
)
1579 if (CI
!= CaseVals
.end() && CI
->first
== EI
->first
)
1582 // Drop unneeded case ranges
1583 for (; RI
!= CaseRanges
.end(); RI
++) {
1585 RI
->second
->getRHS()->EvaluateKnownConstInt(Context
);
1586 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
1587 if (EI
->first
<= Hi
)
1591 if (RI
== CaseRanges
.end() || EI
->first
< RI
->first
) {
1592 hasCasesNotInSwitch
= true;
1593 UnhandledNames
.push_back(EI
->second
->getDeclName());
1597 if (TheDefaultStmt
&& UnhandledNames
.empty() && ED
->isClosedNonFlag())
1598 Diag(TheDefaultStmt
->getDefaultLoc(), diag::warn_unreachable_default
);
1600 // Produce a nice diagnostic if multiple values aren't handled.
1601 if (!UnhandledNames
.empty()) {
1602 auto DB
= Diag(CondExpr
->getExprLoc(), TheDefaultStmt
1603 ? diag::warn_def_missing_case
1604 : diag::warn_missing_case
)
1605 << CondExpr
->getSourceRange() << (int)UnhandledNames
.size();
1607 for (size_t I
= 0, E
= std::min(UnhandledNames
.size(), (size_t)3);
1609 DB
<< UnhandledNames
[I
];
1612 if (!hasCasesNotInSwitch
)
1613 SS
->setAllEnumCasesCovered();
1618 DiagnoseEmptyStmtBody(CondExpr
->getEndLoc(), BodyStmt
,
1619 diag::warn_empty_switch_body
);
1621 // FIXME: If the case list was broken is some way, we don't have a good system
1622 // to patch it up. Instead, just return the whole substmt as broken.
1623 if (CaseListIsErroneous
)
1630 Sema::DiagnoseAssignmentEnum(QualType DstType
, QualType SrcType
,
1632 if (Diags
.isIgnored(diag::warn_not_in_enum_assignment
, SrcExpr
->getExprLoc()))
1635 if (const EnumType
*ET
= DstType
->getAs
<EnumType
>())
1636 if (!Context
.hasSameUnqualifiedType(SrcType
, DstType
) &&
1637 SrcType
->isIntegerType()) {
1638 if (!SrcExpr
->isTypeDependent() && !SrcExpr
->isValueDependent() &&
1639 SrcExpr
->isIntegerConstantExpr(Context
)) {
1640 // Get the bitwidth of the enum value before promotions.
1641 unsigned DstWidth
= Context
.getIntWidth(DstType
);
1642 bool DstIsSigned
= DstType
->isSignedIntegerOrEnumerationType();
1644 llvm::APSInt RhsVal
= SrcExpr
->EvaluateKnownConstInt(Context
);
1645 AdjustAPSInt(RhsVal
, DstWidth
, DstIsSigned
);
1646 const EnumDecl
*ED
= ET
->getDecl();
1648 if (!ED
->isClosed())
1651 if (ED
->hasAttr
<FlagEnumAttr
>()) {
1652 if (!IsValueInFlagEnum(ED
, RhsVal
, true))
1653 Diag(SrcExpr
->getExprLoc(), diag::warn_not_in_enum_assignment
)
1654 << DstType
.getUnqualifiedType();
1656 typedef SmallVector
<std::pair
<llvm::APSInt
, EnumConstantDecl
*>, 64>
1658 EnumValsTy EnumVals
;
1660 // Gather all enum values, set their type and sort them,
1661 // allowing easier comparison with rhs constant.
1662 for (auto *EDI
: ED
->enumerators()) {
1663 llvm::APSInt Val
= EDI
->getInitVal();
1664 AdjustAPSInt(Val
, DstWidth
, DstIsSigned
);
1665 EnumVals
.push_back(std::make_pair(Val
, EDI
));
1667 if (EnumVals
.empty())
1669 llvm::stable_sort(EnumVals
, CmpEnumVals
);
1670 EnumValsTy::iterator EIend
=
1671 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
1673 // See which values aren't in the enum.
1674 EnumValsTy::const_iterator EI
= EnumVals
.begin();
1675 while (EI
!= EIend
&& EI
->first
< RhsVal
)
1677 if (EI
== EIend
|| EI
->first
!= RhsVal
) {
1678 Diag(SrcExpr
->getExprLoc(), diag::warn_not_in_enum_assignment
)
1679 << DstType
.getUnqualifiedType();
1686 StmtResult
Sema::ActOnWhileStmt(SourceLocation WhileLoc
,
1687 SourceLocation LParenLoc
, ConditionResult Cond
,
1688 SourceLocation RParenLoc
, Stmt
*Body
) {
1689 if (Cond
.isInvalid())
1692 auto CondVal
= Cond
.get();
1693 CheckBreakContinueBinding(CondVal
.second
);
1695 if (CondVal
.second
&&
1696 !Diags
.isIgnored(diag::warn_comma_operator
, CondVal
.second
->getExprLoc()))
1697 CommaVisitor(*this).Visit(CondVal
.second
);
1699 if (isa
<NullStmt
>(Body
))
1700 getCurCompoundScope().setHasEmptyLoopBodies();
1702 return WhileStmt::Create(Context
, CondVal
.first
, CondVal
.second
, Body
,
1703 WhileLoc
, LParenLoc
, RParenLoc
);
1707 Sema::ActOnDoStmt(SourceLocation DoLoc
, Stmt
*Body
,
1708 SourceLocation WhileLoc
, SourceLocation CondLParen
,
1709 Expr
*Cond
, SourceLocation CondRParen
) {
1710 assert(Cond
&& "ActOnDoStmt(): missing expression");
1712 CheckBreakContinueBinding(Cond
);
1713 ExprResult CondResult
= CheckBooleanCondition(DoLoc
, Cond
);
1714 if (CondResult
.isInvalid())
1716 Cond
= CondResult
.get();
1718 CondResult
= ActOnFinishFullExpr(Cond
, DoLoc
, /*DiscardedValue*/ false);
1719 if (CondResult
.isInvalid())
1721 Cond
= CondResult
.get();
1723 // Only call the CommaVisitor for C89 due to differences in scope flags.
1724 if (Cond
&& !getLangOpts().C99
&& !getLangOpts().CPlusPlus
&&
1725 !Diags
.isIgnored(diag::warn_comma_operator
, Cond
->getExprLoc()))
1726 CommaVisitor(*this).Visit(Cond
);
1728 return new (Context
) DoStmt(Body
, Cond
, DoLoc
, WhileLoc
, CondRParen
);
1732 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1733 using DeclSetVector
= llvm::SmallSetVector
<VarDecl
*, 8>;
1735 // This visitor will traverse a conditional statement and store all
1736 // the evaluated decls into a vector. Simple is set to true if none
1737 // of the excluded constructs are used.
1738 class DeclExtractor
: public EvaluatedExprVisitor
<DeclExtractor
> {
1739 DeclSetVector
&Decls
;
1740 SmallVectorImpl
<SourceRange
> &Ranges
;
1743 typedef EvaluatedExprVisitor
<DeclExtractor
> Inherited
;
1745 DeclExtractor(Sema
&S
, DeclSetVector
&Decls
,
1746 SmallVectorImpl
<SourceRange
> &Ranges
) :
1747 Inherited(S
.Context
),
1752 bool isSimple() { return Simple
; }
1754 // Replaces the method in EvaluatedExprVisitor.
1755 void VisitMemberExpr(MemberExpr
* E
) {
1759 // Any Stmt not explicitly listed will cause the condition to be marked
1761 void VisitStmt(Stmt
*S
) { Simple
= false; }
1763 void VisitBinaryOperator(BinaryOperator
*E
) {
1768 void VisitCastExpr(CastExpr
*E
) {
1769 Visit(E
->getSubExpr());
1772 void VisitUnaryOperator(UnaryOperator
*E
) {
1773 // Skip checking conditionals with derefernces.
1774 if (E
->getOpcode() == UO_Deref
)
1777 Visit(E
->getSubExpr());
1780 void VisitConditionalOperator(ConditionalOperator
*E
) {
1781 Visit(E
->getCond());
1782 Visit(E
->getTrueExpr());
1783 Visit(E
->getFalseExpr());
1786 void VisitParenExpr(ParenExpr
*E
) {
1787 Visit(E
->getSubExpr());
1790 void VisitBinaryConditionalOperator(BinaryConditionalOperator
*E
) {
1791 Visit(E
->getOpaqueValue()->getSourceExpr());
1792 Visit(E
->getFalseExpr());
1795 void VisitIntegerLiteral(IntegerLiteral
*E
) { }
1796 void VisitFloatingLiteral(FloatingLiteral
*E
) { }
1797 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr
*E
) { }
1798 void VisitCharacterLiteral(CharacterLiteral
*E
) { }
1799 void VisitGNUNullExpr(GNUNullExpr
*E
) { }
1800 void VisitImaginaryLiteral(ImaginaryLiteral
*E
) { }
1802 void VisitDeclRefExpr(DeclRefExpr
*E
) {
1803 VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl());
1805 // Don't allow unhandled Decl types.
1810 Ranges
.push_back(E
->getSourceRange());
1815 }; // end class DeclExtractor
1817 // DeclMatcher checks to see if the decls are used in a non-evaluated
1819 class DeclMatcher
: public EvaluatedExprVisitor
<DeclMatcher
> {
1820 DeclSetVector
&Decls
;
1824 typedef EvaluatedExprVisitor
<DeclMatcher
> Inherited
;
1826 DeclMatcher(Sema
&S
, DeclSetVector
&Decls
, Stmt
*Statement
) :
1827 Inherited(S
.Context
), Decls(Decls
), FoundDecl(false) {
1828 if (!Statement
) return;
1833 void VisitReturnStmt(ReturnStmt
*S
) {
1837 void VisitBreakStmt(BreakStmt
*S
) {
1841 void VisitGotoStmt(GotoStmt
*S
) {
1845 void VisitCastExpr(CastExpr
*E
) {
1846 if (E
->getCastKind() == CK_LValueToRValue
)
1847 CheckLValueToRValueCast(E
->getSubExpr());
1849 Visit(E
->getSubExpr());
1852 void CheckLValueToRValueCast(Expr
*E
) {
1853 E
= E
->IgnoreParenImpCasts();
1855 if (isa
<DeclRefExpr
>(E
)) {
1859 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
1860 Visit(CO
->getCond());
1861 CheckLValueToRValueCast(CO
->getTrueExpr());
1862 CheckLValueToRValueCast(CO
->getFalseExpr());
1866 if (BinaryConditionalOperator
*BCO
=
1867 dyn_cast
<BinaryConditionalOperator
>(E
)) {
1868 CheckLValueToRValueCast(BCO
->getOpaqueValue()->getSourceExpr());
1869 CheckLValueToRValueCast(BCO
->getFalseExpr());
1876 void VisitDeclRefExpr(DeclRefExpr
*E
) {
1877 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl()))
1878 if (Decls
.count(VD
))
1882 void VisitPseudoObjectExpr(PseudoObjectExpr
*POE
) {
1883 // Only need to visit the semantics for POE.
1884 // SyntaticForm doesn't really use the Decal.
1885 for (auto *S
: POE
->semantics()) {
1886 if (auto *OVE
= dyn_cast
<OpaqueValueExpr
>(S
))
1887 // Look past the OVE into the expression it binds.
1888 Visit(OVE
->getSourceExpr());
1894 bool FoundDeclInUse() { return FoundDecl
; }
1896 }; // end class DeclMatcher
1898 void CheckForLoopConditionalStatement(Sema
&S
, Expr
*Second
,
1899 Expr
*Third
, Stmt
*Body
) {
1900 // Condition is empty
1901 if (!Second
) return;
1903 if (S
.Diags
.isIgnored(diag::warn_variables_not_in_loop_body
,
1904 Second
->getBeginLoc()))
1907 PartialDiagnostic PDiag
= S
.PDiag(diag::warn_variables_not_in_loop_body
);
1908 DeclSetVector Decls
;
1909 SmallVector
<SourceRange
, 10> Ranges
;
1910 DeclExtractor
DE(S
, Decls
, Ranges
);
1913 // Don't analyze complex conditionals.
1914 if (!DE
.isSimple()) return;
1917 if (Decls
.size() == 0) return;
1919 // Don't warn on volatile, static, or global variables.
1920 for (auto *VD
: Decls
)
1921 if (VD
->getType().isVolatileQualified() || VD
->hasGlobalStorage())
1924 if (DeclMatcher(S
, Decls
, Second
).FoundDeclInUse() ||
1925 DeclMatcher(S
, Decls
, Third
).FoundDeclInUse() ||
1926 DeclMatcher(S
, Decls
, Body
).FoundDeclInUse())
1929 // Load decl names into diagnostic.
1930 if (Decls
.size() > 4) {
1933 PDiag
<< (unsigned)Decls
.size();
1934 for (auto *VD
: Decls
)
1935 PDiag
<< VD
->getDeclName();
1938 for (auto Range
: Ranges
)
1941 S
.Diag(Ranges
.begin()->getBegin(), PDiag
);
1944 // If Statement is an incemement or decrement, return true and sets the
1945 // variables Increment and DRE.
1946 bool ProcessIterationStmt(Sema
&S
, Stmt
* Statement
, bool &Increment
,
1947 DeclRefExpr
*&DRE
) {
1948 if (auto Cleanups
= dyn_cast
<ExprWithCleanups
>(Statement
))
1949 if (!Cleanups
->cleanupsHaveSideEffects())
1950 Statement
= Cleanups
->getSubExpr();
1952 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(Statement
)) {
1953 switch (UO
->getOpcode()) {
1954 default: return false;
1964 DRE
= dyn_cast
<DeclRefExpr
>(UO
->getSubExpr());
1968 if (CXXOperatorCallExpr
*Call
= dyn_cast
<CXXOperatorCallExpr
>(Statement
)) {
1969 FunctionDecl
*FD
= Call
->getDirectCallee();
1970 if (!FD
|| !FD
->isOverloadedOperator()) return false;
1971 switch (FD
->getOverloadedOperator()) {
1972 default: return false;
1980 DRE
= dyn_cast
<DeclRefExpr
>(Call
->getArg(0));
1987 // A visitor to determine if a continue or break statement is a
1989 class BreakContinueFinder
: public ConstEvaluatedExprVisitor
<BreakContinueFinder
> {
1990 SourceLocation BreakLoc
;
1991 SourceLocation ContinueLoc
;
1992 bool InSwitch
= false;
1995 BreakContinueFinder(Sema
&S
, const Stmt
* Body
) :
1996 Inherited(S
.Context
) {
2000 typedef ConstEvaluatedExprVisitor
<BreakContinueFinder
> Inherited
;
2002 void VisitContinueStmt(const ContinueStmt
* E
) {
2003 ContinueLoc
= E
->getContinueLoc();
2006 void VisitBreakStmt(const BreakStmt
* E
) {
2008 BreakLoc
= E
->getBreakLoc();
2011 void VisitSwitchStmt(const SwitchStmt
* S
) {
2012 if (const Stmt
*Init
= S
->getInit())
2014 if (const Stmt
*CondVar
= S
->getConditionVariableDeclStmt())
2016 if (const Stmt
*Cond
= S
->getCond())
2019 // Don't return break statements from the body of a switch.
2021 if (const Stmt
*Body
= S
->getBody())
2026 void VisitForStmt(const ForStmt
*S
) {
2027 // Only visit the init statement of a for loop; the body
2028 // has a different break/continue scope.
2029 if (const Stmt
*Init
= S
->getInit())
2033 void VisitWhileStmt(const WhileStmt
*) {
2034 // Do nothing; the children of a while loop have a different
2035 // break/continue scope.
2038 void VisitDoStmt(const DoStmt
*) {
2039 // Do nothing; the children of a while loop have a different
2040 // break/continue scope.
2043 void VisitCXXForRangeStmt(const CXXForRangeStmt
*S
) {
2044 // Only visit the initialization of a for loop; the body
2045 // has a different break/continue scope.
2046 if (const Stmt
*Init
= S
->getInit())
2048 if (const Stmt
*Range
= S
->getRangeStmt())
2050 if (const Stmt
*Begin
= S
->getBeginStmt())
2052 if (const Stmt
*End
= S
->getEndStmt())
2056 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt
*S
) {
2057 // Only visit the initialization of a for loop; the body
2058 // has a different break/continue scope.
2059 if (const Stmt
*Element
= S
->getElement())
2061 if (const Stmt
*Collection
= S
->getCollection())
2065 bool ContinueFound() { return ContinueLoc
.isValid(); }
2066 bool BreakFound() { return BreakLoc
.isValid(); }
2067 SourceLocation
GetContinueLoc() { return ContinueLoc
; }
2068 SourceLocation
GetBreakLoc() { return BreakLoc
; }
2070 }; // end class BreakContinueFinder
2072 // Emit a warning when a loop increment/decrement appears twice per loop
2073 // iteration. The conditions which trigger this warning are:
2074 // 1) The last statement in the loop body and the third expression in the
2075 // for loop are both increment or both decrement of the same variable
2076 // 2) No continue statements in the loop body.
2077 void CheckForRedundantIteration(Sema
&S
, Expr
*Third
, Stmt
*Body
) {
2078 // Return when there is nothing to check.
2079 if (!Body
|| !Third
) return;
2081 if (S
.Diags
.isIgnored(diag::warn_redundant_loop_iteration
,
2082 Third
->getBeginLoc()))
2085 // Get the last statement from the loop body.
2086 CompoundStmt
*CS
= dyn_cast
<CompoundStmt
>(Body
);
2087 if (!CS
|| CS
->body_empty()) return;
2088 Stmt
*LastStmt
= CS
->body_back();
2089 if (!LastStmt
) return;
2091 bool LoopIncrement
, LastIncrement
;
2092 DeclRefExpr
*LoopDRE
, *LastDRE
;
2094 if (!ProcessIterationStmt(S
, Third
, LoopIncrement
, LoopDRE
)) return;
2095 if (!ProcessIterationStmt(S
, LastStmt
, LastIncrement
, LastDRE
)) return;
2097 // Check that the two statements are both increments or both decrements
2098 // on the same variable.
2099 if (LoopIncrement
!= LastIncrement
||
2100 LoopDRE
->getDecl() != LastDRE
->getDecl()) return;
2102 if (BreakContinueFinder(S
, Body
).ContinueFound()) return;
2104 S
.Diag(LastDRE
->getLocation(), diag::warn_redundant_loop_iteration
)
2105 << LastDRE
->getDecl() << LastIncrement
;
2106 S
.Diag(LoopDRE
->getLocation(), diag::note_loop_iteration_here
)
2113 void Sema::CheckBreakContinueBinding(Expr
*E
) {
2114 if (!E
|| getLangOpts().CPlusPlus
)
2116 BreakContinueFinder
BCFinder(*this, E
);
2117 Scope
*BreakParent
= CurScope
->getBreakParent();
2118 if (BCFinder
.BreakFound() && BreakParent
) {
2119 if (BreakParent
->getFlags() & Scope::SwitchScope
) {
2120 Diag(BCFinder
.GetBreakLoc(), diag::warn_break_binds_to_switch
);
2122 Diag(BCFinder
.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner
)
2125 } else if (BCFinder
.ContinueFound() && CurScope
->getContinueParent()) {
2126 Diag(BCFinder
.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner
)
2131 StmtResult
Sema::ActOnForStmt(SourceLocation ForLoc
, SourceLocation LParenLoc
,
2132 Stmt
*First
, ConditionResult Second
,
2133 FullExprArg third
, SourceLocation RParenLoc
,
2135 if (Second
.isInvalid())
2138 if (!getLangOpts().CPlusPlus
) {
2139 if (DeclStmt
*DS
= dyn_cast_or_null
<DeclStmt
>(First
)) {
2140 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2141 // declare identifiers for objects having storage class 'auto' or
2143 const Decl
*NonVarSeen
= nullptr;
2144 bool VarDeclSeen
= false;
2145 for (auto *DI
: DS
->decls()) {
2146 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(DI
)) {
2148 if (VD
->isLocalVarDecl() && !VD
->hasLocalStorage()) {
2149 Diag(DI
->getLocation(), diag::err_non_local_variable_decl_in_for
);
2150 DI
->setInvalidDecl();
2152 } else if (!NonVarSeen
) {
2153 // Keep track of the first non-variable declaration we saw so that
2154 // we can diagnose if we don't see any variable declarations. This
2155 // covers a case like declaring a typedef, function, or structure
2156 // type rather than a variable.
2160 // Diagnose if we saw a non-variable declaration but no variable
2162 if (NonVarSeen
&& !VarDeclSeen
)
2163 Diag(NonVarSeen
->getLocation(), diag::err_non_variable_decl_in_for
);
2167 CheckBreakContinueBinding(Second
.get().second
);
2168 CheckBreakContinueBinding(third
.get());
2170 if (!Second
.get().first
)
2171 CheckForLoopConditionalStatement(*this, Second
.get().second
, third
.get(),
2173 CheckForRedundantIteration(*this, third
.get(), Body
);
2175 if (Second
.get().second
&&
2176 !Diags
.isIgnored(diag::warn_comma_operator
,
2177 Second
.get().second
->getExprLoc()))
2178 CommaVisitor(*this).Visit(Second
.get().second
);
2180 Expr
*Third
= third
.release().getAs
<Expr
>();
2181 if (isa
<NullStmt
>(Body
))
2182 getCurCompoundScope().setHasEmptyLoopBodies();
2184 return new (Context
)
2185 ForStmt(Context
, First
, Second
.get().second
, Second
.get().first
, Third
,
2186 Body
, ForLoc
, LParenLoc
, RParenLoc
);
2189 /// In an Objective C collection iteration statement:
2191 /// x can be an arbitrary l-value expression. Bind it up as a
2192 /// full-expression.
2193 StmtResult
Sema::ActOnForEachLValueExpr(Expr
*E
) {
2194 // Reduce placeholder expressions here. Note that this rejects the
2195 // use of pseudo-object l-values in this position.
2196 ExprResult result
= CheckPlaceholderExpr(E
);
2197 if (result
.isInvalid()) return StmtError();
2200 ExprResult FullExpr
= ActOnFinishFullExpr(E
, /*DiscardedValue*/ false);
2201 if (FullExpr
.isInvalid())
2203 return StmtResult(static_cast<Stmt
*>(FullExpr
.get()));
2207 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc
, Expr
*collection
) {
2211 ExprResult result
= CorrectDelayedTyposInExpr(collection
);
2212 if (!result
.isUsable())
2214 collection
= result
.get();
2216 // Bail out early if we've got a type-dependent expression.
2217 if (collection
->isTypeDependent()) return collection
;
2219 // Perform normal l-value conversion.
2220 result
= DefaultFunctionArrayLvalueConversion(collection
);
2221 if (result
.isInvalid())
2223 collection
= result
.get();
2225 // The operand needs to have object-pointer type.
2226 // TODO: should we do a contextual conversion?
2227 const ObjCObjectPointerType
*pointerType
=
2228 collection
->getType()->getAs
<ObjCObjectPointerType
>();
2230 return Diag(forLoc
, diag::err_collection_expr_type
)
2231 << collection
->getType() << collection
->getSourceRange();
2233 // Check that the operand provides
2234 // - countByEnumeratingWithState:objects:count:
2235 const ObjCObjectType
*objectType
= pointerType
->getObjectType();
2236 ObjCInterfaceDecl
*iface
= objectType
->getInterface();
2238 // If we have a forward-declared type, we can't do this check.
2239 // Under ARC, it is an error not to have a forward-declared class.
2241 (getLangOpts().ObjCAutoRefCount
2242 ? RequireCompleteType(forLoc
, QualType(objectType
, 0),
2243 diag::err_arc_collection_forward
, collection
)
2244 : !isCompleteType(forLoc
, QualType(objectType
, 0)))) {
2245 // Otherwise, if we have any useful type information, check that
2246 // the type declares the appropriate method.
2247 } else if (iface
|| !objectType
->qual_empty()) {
2248 IdentifierInfo
*selectorIdents
[] = {
2249 &Context
.Idents
.get("countByEnumeratingWithState"),
2250 &Context
.Idents
.get("objects"),
2251 &Context
.Idents
.get("count")
2253 Selector selector
= Context
.Selectors
.getSelector(3, &selectorIdents
[0]);
2255 ObjCMethodDecl
*method
= nullptr;
2257 // If there's an interface, look in both the public and private APIs.
2259 method
= iface
->lookupInstanceMethod(selector
);
2260 if (!method
) method
= iface
->lookupPrivateMethod(selector
);
2263 // Also check protocol qualifiers.
2265 method
= LookupMethodInQualifiedType(selector
, pointerType
,
2268 // If we didn't find it anywhere, give up.
2270 Diag(forLoc
, diag::warn_collection_expr_type
)
2271 << collection
->getType() << selector
<< collection
->getSourceRange();
2274 // TODO: check for an incompatible signature?
2277 // Wrap up any cleanups in the expression.
2282 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc
,
2283 Stmt
*First
, Expr
*collection
,
2284 SourceLocation RParenLoc
) {
2285 setFunctionHasBranchProtectedScope();
2287 ExprResult CollectionExprResult
=
2288 CheckObjCForCollectionOperand(ForLoc
, collection
);
2292 if (DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
)) {
2293 if (!DS
->isSingleDecl())
2294 return StmtError(Diag((*DS
->decl_begin())->getLocation(),
2295 diag::err_toomany_element_decls
));
2297 VarDecl
*D
= dyn_cast
<VarDecl
>(DS
->getSingleDecl());
2298 if (!D
|| D
->isInvalidDecl())
2301 FirstType
= D
->getType();
2302 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2303 // declare identifiers for objects having storage class 'auto' or
2305 if (!D
->hasLocalStorage())
2306 return StmtError(Diag(D
->getLocation(),
2307 diag::err_non_local_variable_decl_in_for
));
2309 // If the type contained 'auto', deduce the 'auto' to 'id'.
2310 if (FirstType
->getContainedAutoType()) {
2311 SourceLocation Loc
= D
->getLocation();
2312 OpaqueValueExpr
OpaqueId(Loc
, Context
.getObjCIdType(), VK_PRValue
);
2313 Expr
*DeducedInit
= &OpaqueId
;
2314 TemplateDeductionInfo
Info(Loc
);
2315 FirstType
= QualType();
2316 TemplateDeductionResult Result
= DeduceAutoType(
2317 D
->getTypeSourceInfo()->getTypeLoc(), DeducedInit
, FirstType
, Info
);
2318 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
)
2319 DiagnoseAutoDeductionFailure(D
, DeducedInit
);
2320 if (FirstType
.isNull()) {
2321 D
->setInvalidDecl();
2325 D
->setType(FirstType
);
2327 if (!inTemplateInstantiation()) {
2328 SourceLocation Loc
=
2329 D
->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
2330 Diag(Loc
, diag::warn_auto_var_is_id
)
2331 << D
->getDeclName();
2336 Expr
*FirstE
= cast
<Expr
>(First
);
2337 if (!FirstE
->isTypeDependent() && !FirstE
->isLValue())
2339 Diag(First
->getBeginLoc(), diag::err_selector_element_not_lvalue
)
2340 << First
->getSourceRange());
2342 FirstType
= static_cast<Expr
*>(First
)->getType();
2343 if (FirstType
.isConstQualified())
2344 Diag(ForLoc
, diag::err_selector_element_const_type
)
2345 << FirstType
<< First
->getSourceRange();
2347 if (!FirstType
->isDependentType() &&
2348 !FirstType
->isObjCObjectPointerType() &&
2349 !FirstType
->isBlockPointerType())
2350 return StmtError(Diag(ForLoc
, diag::err_selector_element_type
)
2351 << FirstType
<< First
->getSourceRange());
2354 if (CollectionExprResult
.isInvalid())
2357 CollectionExprResult
=
2358 ActOnFinishFullExpr(CollectionExprResult
.get(), /*DiscardedValue*/ false);
2359 if (CollectionExprResult
.isInvalid())
2362 return new (Context
) ObjCForCollectionStmt(First
, CollectionExprResult
.get(),
2363 nullptr, ForLoc
, RParenLoc
);
2366 /// Finish building a variable declaration for a for-range statement.
2367 /// \return true if an error occurs.
2368 static bool FinishForRangeVarDecl(Sema
&SemaRef
, VarDecl
*Decl
, Expr
*Init
,
2369 SourceLocation Loc
, int DiagID
) {
2370 if (Decl
->getType()->isUndeducedType()) {
2371 ExprResult Res
= SemaRef
.CorrectDelayedTyposInExpr(Init
);
2372 if (!Res
.isUsable()) {
2373 Decl
->setInvalidDecl();
2379 // Deduce the type for the iterator variable now rather than leaving it to
2380 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2382 if (!isa
<InitListExpr
>(Init
) && Init
->getType()->isVoidType()) {
2383 SemaRef
.Diag(Loc
, DiagID
) << Init
->getType();
2385 TemplateDeductionInfo
Info(Init
->getExprLoc());
2386 Sema::TemplateDeductionResult Result
= SemaRef
.DeduceAutoType(
2387 Decl
->getTypeSourceInfo()->getTypeLoc(), Init
, InitType
, Info
);
2388 if (Result
!= Sema::TDK_Success
&& Result
!= Sema::TDK_AlreadyDiagnosed
)
2389 SemaRef
.Diag(Loc
, DiagID
) << Init
->getType();
2392 if (InitType
.isNull()) {
2393 Decl
->setInvalidDecl();
2396 Decl
->setType(InitType
);
2398 // In ARC, infer lifetime.
2399 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2400 // we're doing the equivalent of fast iteration.
2401 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
2402 SemaRef
.inferObjCARCLifetime(Decl
))
2403 Decl
->setInvalidDecl();
2405 SemaRef
.AddInitializerToDecl(Decl
, Init
, /*DirectInit=*/false);
2406 SemaRef
.FinalizeDeclaration(Decl
);
2407 SemaRef
.CurContext
->addHiddenDecl(Decl
);
2412 // An enum to represent whether something is dealing with a call to begin()
2413 // or a call to end() in a range-based for loop.
2414 enum BeginEndFunction
{
2419 /// Produce a note indicating which begin/end function was implicitly called
2420 /// by a C++11 for-range statement. This is often not obvious from the code,
2421 /// nor from the diagnostics produced when analysing the implicit expressions
2422 /// required in a for-range statement.
2423 void NoteForRangeBeginEndFunction(Sema
&SemaRef
, Expr
*E
,
2424 BeginEndFunction BEF
) {
2425 CallExpr
*CE
= dyn_cast
<CallExpr
>(E
);
2428 FunctionDecl
*D
= dyn_cast
<FunctionDecl
>(CE
->getCalleeDecl());
2431 SourceLocation Loc
= D
->getLocation();
2433 std::string Description
;
2434 bool IsTemplate
= false;
2435 if (FunctionTemplateDecl
*FunTmpl
= D
->getPrimaryTemplate()) {
2436 Description
= SemaRef
.getTemplateArgumentBindingsText(
2437 FunTmpl
->getTemplateParameters(), *D
->getTemplateSpecializationArgs());
2441 SemaRef
.Diag(Loc
, diag::note_for_range_begin_end
)
2442 << BEF
<< IsTemplate
<< Description
<< E
->getType();
2445 /// Build a variable declaration for a for-range statement.
2446 VarDecl
*BuildForRangeVarDecl(Sema
&SemaRef
, SourceLocation Loc
,
2447 QualType Type
, StringRef Name
) {
2448 DeclContext
*DC
= SemaRef
.CurContext
;
2449 IdentifierInfo
*II
= &SemaRef
.PP
.getIdentifierTable().get(Name
);
2450 TypeSourceInfo
*TInfo
= SemaRef
.Context
.getTrivialTypeSourceInfo(Type
, Loc
);
2451 VarDecl
*Decl
= VarDecl::Create(SemaRef
.Context
, DC
, Loc
, Loc
, II
, Type
,
2453 Decl
->setImplicit();
2459 static bool ObjCEnumerationCollection(Expr
*Collection
) {
2460 return !Collection
->isTypeDependent()
2461 && Collection
->getType()->getAs
<ObjCObjectPointerType
>() != nullptr;
2464 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2466 /// C++11 [stmt.ranged]:
2467 /// A range-based for statement is equivalent to
2470 /// auto && __range = range-init;
2471 /// for ( auto __begin = begin-expr,
2472 /// __end = end-expr;
2473 /// __begin != __end;
2475 /// for-range-declaration = *__begin;
2480 /// The body of the loop is not available yet, since it cannot be analysed until
2481 /// we have determined the type of the for-range-declaration.
2482 StmtResult
Sema::ActOnCXXForRangeStmt(Scope
*S
, SourceLocation ForLoc
,
2483 SourceLocation CoawaitLoc
, Stmt
*InitStmt
,
2484 Stmt
*First
, SourceLocation ColonLoc
,
2485 Expr
*Range
, SourceLocation RParenLoc
,
2486 BuildForRangeKind Kind
) {
2487 // FIXME: recover in order to allow the body to be parsed.
2491 if (Range
&& ObjCEnumerationCollection(Range
)) {
2492 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2494 return Diag(InitStmt
->getBeginLoc(), diag::err_objc_for_range_init_stmt
)
2495 << InitStmt
->getSourceRange();
2496 return ActOnObjCForCollectionStmt(ForLoc
, First
, Range
, RParenLoc
);
2499 DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
);
2500 assert(DS
&& "first part of for range not a decl stmt");
2502 if (!DS
->isSingleDecl()) {
2503 Diag(DS
->getBeginLoc(), diag::err_type_defined_in_for_range
);
2507 // This function is responsible for attaching an initializer to LoopVar. We
2508 // must call ActOnInitializerError if we fail to do so.
2509 Decl
*LoopVar
= DS
->getSingleDecl();
2510 if (LoopVar
->isInvalidDecl() || !Range
||
2511 DiagnoseUnexpandedParameterPack(Range
, UPPC_Expression
)) {
2512 ActOnInitializerError(LoopVar
);
2516 // Build the coroutine state immediately and not later during template
2518 if (!CoawaitLoc
.isInvalid()) {
2519 if (!ActOnCoroutineBodyStart(S
, CoawaitLoc
, "co_await")) {
2520 ActOnInitializerError(LoopVar
);
2525 // Build auto && __range = range-init
2526 // Divide by 2, since the variables are in the inner scope (loop body).
2527 const auto DepthStr
= std::to_string(S
->getDepth() / 2);
2528 SourceLocation RangeLoc
= Range
->getBeginLoc();
2529 VarDecl
*RangeVar
= BuildForRangeVarDecl(*this, RangeLoc
,
2530 Context
.getAutoRRefDeductType(),
2531 std::string("__range") + DepthStr
);
2532 if (FinishForRangeVarDecl(*this, RangeVar
, Range
, RangeLoc
,
2533 diag::err_for_range_deduction_failure
)) {
2534 ActOnInitializerError(LoopVar
);
2538 // Claim the type doesn't contain auto: we've already done the checking.
2539 DeclGroupPtrTy RangeGroup
=
2540 BuildDeclaratorGroup(MutableArrayRef
<Decl
*>((Decl
**)&RangeVar
, 1));
2541 StmtResult RangeDecl
= ActOnDeclStmt(RangeGroup
, RangeLoc
, RangeLoc
);
2542 if (RangeDecl
.isInvalid()) {
2543 ActOnInitializerError(LoopVar
);
2547 StmtResult R
= BuildCXXForRangeStmt(
2548 ForLoc
, CoawaitLoc
, InitStmt
, ColonLoc
, RangeDecl
.get(),
2549 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2550 /*Cond=*/nullptr, /*Inc=*/nullptr, DS
, RParenLoc
, Kind
);
2551 if (R
.isInvalid()) {
2552 ActOnInitializerError(LoopVar
);
2559 /// Create the initialization, compare, and increment steps for
2560 /// the range-based for loop expression.
2561 /// This function does not handle array-based for loops,
2562 /// which are created in Sema::BuildCXXForRangeStmt.
2564 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2565 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2566 /// CandidateSet and BEF are set and some non-success value is returned on
2568 static Sema::ForRangeStatus
2569 BuildNonArrayForRange(Sema
&SemaRef
, Expr
*BeginRange
, Expr
*EndRange
,
2570 QualType RangeType
, VarDecl
*BeginVar
, VarDecl
*EndVar
,
2571 SourceLocation ColonLoc
, SourceLocation CoawaitLoc
,
2572 OverloadCandidateSet
*CandidateSet
, ExprResult
*BeginExpr
,
2573 ExprResult
*EndExpr
, BeginEndFunction
*BEF
) {
2574 DeclarationNameInfo
BeginNameInfo(
2575 &SemaRef
.PP
.getIdentifierTable().get("begin"), ColonLoc
);
2576 DeclarationNameInfo
EndNameInfo(&SemaRef
.PP
.getIdentifierTable().get("end"),
2579 LookupResult
BeginMemberLookup(SemaRef
, BeginNameInfo
,
2580 Sema::LookupMemberName
);
2581 LookupResult
EndMemberLookup(SemaRef
, EndNameInfo
, Sema::LookupMemberName
);
2583 auto BuildBegin
= [&] {
2585 Sema::ForRangeStatus RangeStatus
=
2586 SemaRef
.BuildForRangeBeginEndCall(ColonLoc
, ColonLoc
, BeginNameInfo
,
2587 BeginMemberLookup
, CandidateSet
,
2588 BeginRange
, BeginExpr
);
2590 if (RangeStatus
!= Sema::FRS_Success
) {
2591 if (RangeStatus
== Sema::FRS_DiagnosticIssued
)
2592 SemaRef
.Diag(BeginRange
->getBeginLoc(), diag::note_in_for_range
)
2593 << ColonLoc
<< BEF_begin
<< BeginRange
->getType();
2596 if (!CoawaitLoc
.isInvalid()) {
2597 // FIXME: getCurScope() should not be used during template instantiation.
2598 // We should pick up the set of unqualified lookup results for operator
2599 // co_await during the initial parse.
2600 *BeginExpr
= SemaRef
.ActOnCoawaitExpr(SemaRef
.getCurScope(), ColonLoc
,
2602 if (BeginExpr
->isInvalid())
2603 return Sema::FRS_DiagnosticIssued
;
2605 if (FinishForRangeVarDecl(SemaRef
, BeginVar
, BeginExpr
->get(), ColonLoc
,
2606 diag::err_for_range_iter_deduction_failure
)) {
2607 NoteForRangeBeginEndFunction(SemaRef
, BeginExpr
->get(), *BEF
);
2608 return Sema::FRS_DiagnosticIssued
;
2610 return Sema::FRS_Success
;
2613 auto BuildEnd
= [&] {
2615 Sema::ForRangeStatus RangeStatus
=
2616 SemaRef
.BuildForRangeBeginEndCall(ColonLoc
, ColonLoc
, EndNameInfo
,
2617 EndMemberLookup
, CandidateSet
,
2619 if (RangeStatus
!= Sema::FRS_Success
) {
2620 if (RangeStatus
== Sema::FRS_DiagnosticIssued
)
2621 SemaRef
.Diag(EndRange
->getBeginLoc(), diag::note_in_for_range
)
2622 << ColonLoc
<< BEF_end
<< EndRange
->getType();
2625 if (FinishForRangeVarDecl(SemaRef
, EndVar
, EndExpr
->get(), ColonLoc
,
2626 diag::err_for_range_iter_deduction_failure
)) {
2627 NoteForRangeBeginEndFunction(SemaRef
, EndExpr
->get(), *BEF
);
2628 return Sema::FRS_DiagnosticIssued
;
2630 return Sema::FRS_Success
;
2633 if (CXXRecordDecl
*D
= RangeType
->getAsCXXRecordDecl()) {
2634 // - if _RangeT is a class type, the unqualified-ids begin and end are
2635 // looked up in the scope of class _RangeT as if by class member access
2636 // lookup (3.4.5), and if either (or both) finds at least one
2637 // declaration, begin-expr and end-expr are __range.begin() and
2638 // __range.end(), respectively;
2639 SemaRef
.LookupQualifiedName(BeginMemberLookup
, D
);
2640 if (BeginMemberLookup
.isAmbiguous())
2641 return Sema::FRS_DiagnosticIssued
;
2643 SemaRef
.LookupQualifiedName(EndMemberLookup
, D
);
2644 if (EndMemberLookup
.isAmbiguous())
2645 return Sema::FRS_DiagnosticIssued
;
2647 if (BeginMemberLookup
.empty() != EndMemberLookup
.empty()) {
2648 // Look up the non-member form of the member we didn't find, first.
2649 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2650 // a 'begin' but ignored it because there was no member 'end'"
2652 auto BuildNonmember
= [&](
2653 BeginEndFunction BEFFound
, LookupResult
&Found
,
2654 llvm::function_ref
<Sema::ForRangeStatus()> BuildFound
,
2655 llvm::function_ref
<Sema::ForRangeStatus()> BuildNotFound
) {
2656 LookupResult OldFound
= std::move(Found
);
2659 if (Sema::ForRangeStatus Result
= BuildNotFound())
2662 switch (BuildFound()) {
2663 case Sema::FRS_Success
:
2664 return Sema::FRS_Success
;
2666 case Sema::FRS_NoViableFunction
:
2667 CandidateSet
->NoteCandidates(
2668 PartialDiagnosticAt(BeginRange
->getBeginLoc(),
2669 SemaRef
.PDiag(diag::err_for_range_invalid
)
2670 << BeginRange
->getType() << BEFFound
),
2671 SemaRef
, OCD_AllCandidates
, BeginRange
);
2674 case Sema::FRS_DiagnosticIssued
:
2675 for (NamedDecl
*D
: OldFound
) {
2676 SemaRef
.Diag(D
->getLocation(),
2677 diag::note_for_range_member_begin_end_ignored
)
2678 << BeginRange
->getType() << BEFFound
;
2680 return Sema::FRS_DiagnosticIssued
;
2682 llvm_unreachable("unexpected ForRangeStatus");
2684 if (BeginMemberLookup
.empty())
2685 return BuildNonmember(BEF_end
, EndMemberLookup
, BuildEnd
, BuildBegin
);
2686 return BuildNonmember(BEF_begin
, BeginMemberLookup
, BuildBegin
, BuildEnd
);
2689 // - otherwise, begin-expr and end-expr are begin(__range) and
2690 // end(__range), respectively, where begin and end are looked up with
2691 // argument-dependent lookup (3.4.2). For the purposes of this name
2692 // lookup, namespace std is an associated namespace.
2695 if (Sema::ForRangeStatus Result
= BuildBegin())
2700 /// Speculatively attempt to dereference an invalid range expression.
2701 /// If the attempt fails, this function will return a valid, null StmtResult
2702 /// and emit no diagnostics.
2703 static StmtResult
RebuildForRangeWithDereference(Sema
&SemaRef
, Scope
*S
,
2704 SourceLocation ForLoc
,
2705 SourceLocation CoawaitLoc
,
2708 SourceLocation ColonLoc
,
2710 SourceLocation RangeLoc
,
2711 SourceLocation RParenLoc
) {
2712 // Determine whether we can rebuild the for-range statement with a
2713 // dereferenced range expression.
2714 ExprResult AdjustedRange
;
2716 Sema::SFINAETrap
Trap(SemaRef
);
2718 AdjustedRange
= SemaRef
.BuildUnaryOp(S
, RangeLoc
, UO_Deref
, Range
);
2719 if (AdjustedRange
.isInvalid())
2720 return StmtResult();
2722 StmtResult SR
= SemaRef
.ActOnCXXForRangeStmt(
2723 S
, ForLoc
, CoawaitLoc
, InitStmt
, LoopVarDecl
, ColonLoc
,
2724 AdjustedRange
.get(), RParenLoc
, Sema::BFRK_Check
);
2726 return StmtResult();
2729 // The attempt to dereference worked well enough that it could produce a valid
2730 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2731 // case there are any other (non-fatal) problems with it.
2732 SemaRef
.Diag(RangeLoc
, diag::err_for_range_dereference
)
2733 << Range
->getType() << FixItHint::CreateInsertion(RangeLoc
, "*");
2734 return SemaRef
.ActOnCXXForRangeStmt(
2735 S
, ForLoc
, CoawaitLoc
, InitStmt
, LoopVarDecl
, ColonLoc
,
2736 AdjustedRange
.get(), RParenLoc
, Sema::BFRK_Rebuild
);
2739 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2740 StmtResult
Sema::BuildCXXForRangeStmt(SourceLocation ForLoc
,
2741 SourceLocation CoawaitLoc
, Stmt
*InitStmt
,
2742 SourceLocation ColonLoc
, Stmt
*RangeDecl
,
2743 Stmt
*Begin
, Stmt
*End
, Expr
*Cond
,
2744 Expr
*Inc
, Stmt
*LoopVarDecl
,
2745 SourceLocation RParenLoc
,
2746 BuildForRangeKind Kind
) {
2747 // FIXME: This should not be used during template instantiation. We should
2748 // pick up the set of unqualified lookup results for the != and + operators
2749 // in the initial parse.
2751 // Testcase (accepts-invalid):
2752 // template<typename T> void f() { for (auto x : T()) {} }
2753 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2754 // bool operator!=(N::X, N::X); void operator++(N::X);
2755 // void g() { f<N::X>(); }
2756 Scope
*S
= getCurScope();
2758 DeclStmt
*RangeDS
= cast
<DeclStmt
>(RangeDecl
);
2759 VarDecl
*RangeVar
= cast
<VarDecl
>(RangeDS
->getSingleDecl());
2760 QualType RangeVarType
= RangeVar
->getType();
2762 DeclStmt
*LoopVarDS
= cast
<DeclStmt
>(LoopVarDecl
);
2763 VarDecl
*LoopVar
= cast
<VarDecl
>(LoopVarDS
->getSingleDecl());
2765 StmtResult BeginDeclStmt
= Begin
;
2766 StmtResult EndDeclStmt
= End
;
2767 ExprResult NotEqExpr
= Cond
, IncrExpr
= Inc
;
2769 if (RangeVarType
->isDependentType()) {
2770 // The range is implicitly used as a placeholder when it is dependent.
2771 RangeVar
->markUsed(Context
);
2773 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2774 // them in properly when we instantiate the loop.
2775 if (!LoopVar
->isInvalidDecl() && Kind
!= BFRK_Check
) {
2776 if (auto *DD
= dyn_cast
<DecompositionDecl
>(LoopVar
))
2777 for (auto *Binding
: DD
->bindings())
2778 Binding
->setType(Context
.DependentTy
);
2779 LoopVar
->setType(SubstAutoTypeDependent(LoopVar
->getType()));
2781 } else if (!BeginDeclStmt
.get()) {
2782 SourceLocation RangeLoc
= RangeVar
->getLocation();
2784 const QualType RangeVarNonRefType
= RangeVarType
.getNonReferenceType();
2786 ExprResult BeginRangeRef
= BuildDeclRefExpr(RangeVar
, RangeVarNonRefType
,
2787 VK_LValue
, ColonLoc
);
2788 if (BeginRangeRef
.isInvalid())
2791 ExprResult EndRangeRef
= BuildDeclRefExpr(RangeVar
, RangeVarNonRefType
,
2792 VK_LValue
, ColonLoc
);
2793 if (EndRangeRef
.isInvalid())
2796 QualType AutoType
= Context
.getAutoDeductType();
2797 Expr
*Range
= RangeVar
->getInit();
2800 QualType RangeType
= Range
->getType();
2802 if (RequireCompleteType(RangeLoc
, RangeType
,
2803 diag::err_for_range_incomplete_type
))
2806 // Build auto __begin = begin-expr, __end = end-expr.
2807 // Divide by 2, since the variables are in the inner scope (loop body).
2808 const auto DepthStr
= std::to_string(S
->getDepth() / 2);
2809 VarDecl
*BeginVar
= BuildForRangeVarDecl(*this, ColonLoc
, AutoType
,
2810 std::string("__begin") + DepthStr
);
2811 VarDecl
*EndVar
= BuildForRangeVarDecl(*this, ColonLoc
, AutoType
,
2812 std::string("__end") + DepthStr
);
2814 // Build begin-expr and end-expr and attach to __begin and __end variables.
2815 ExprResult BeginExpr
, EndExpr
;
2816 if (const ArrayType
*UnqAT
= RangeType
->getAsArrayTypeUnsafe()) {
2817 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2818 // __range + __bound, respectively, where __bound is the array bound. If
2819 // _RangeT is an array of unknown size or an array of incomplete type,
2820 // the program is ill-formed;
2822 // begin-expr is __range.
2823 BeginExpr
= BeginRangeRef
;
2824 if (!CoawaitLoc
.isInvalid()) {
2825 BeginExpr
= ActOnCoawaitExpr(S
, ColonLoc
, BeginExpr
.get());
2826 if (BeginExpr
.isInvalid())
2829 if (FinishForRangeVarDecl(*this, BeginVar
, BeginRangeRef
.get(), ColonLoc
,
2830 diag::err_for_range_iter_deduction_failure
)) {
2831 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
2835 // Find the array bound.
2836 ExprResult BoundExpr
;
2837 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(UnqAT
))
2838 BoundExpr
= IntegerLiteral::Create(
2839 Context
, CAT
->getSize(), Context
.getPointerDiffType(), RangeLoc
);
2840 else if (const VariableArrayType
*VAT
=
2841 dyn_cast
<VariableArrayType
>(UnqAT
)) {
2842 // For a variably modified type we can't just use the expression within
2843 // the array bounds, since we don't want that to be re-evaluated here.
2844 // Rather, we need to determine what it was when the array was first
2845 // created - so we resort to using sizeof(vla)/sizeof(element).
2849 // b = -1; <-- This should not affect the num of iterations below
2850 // for (int &c : vla) { .. }
2853 // FIXME: This results in codegen generating IR that recalculates the
2854 // run-time number of elements (as opposed to just using the IR Value
2855 // that corresponds to the run-time value of each bound that was
2856 // generated when the array was created.) If this proves too embarrassing
2857 // even for unoptimized IR, consider passing a magic-value/cookie to
2858 // codegen that then knows to simply use that initial llvm::Value (that
2859 // corresponds to the bound at time of array creation) within
2860 // getelementptr. But be prepared to pay the price of increasing a
2861 // customized form of coupling between the two components - which could
2862 // be hard to maintain as the codebase evolves.
2864 ExprResult SizeOfVLAExprR
= ActOnUnaryExprOrTypeTraitExpr(
2865 EndVar
->getLocation(), UETT_SizeOf
,
2867 CreateParsedType(VAT
->desugar(), Context
.getTrivialTypeSourceInfo(
2868 VAT
->desugar(), RangeLoc
))
2870 EndVar
->getSourceRange());
2871 if (SizeOfVLAExprR
.isInvalid())
2874 ExprResult SizeOfEachElementExprR
= ActOnUnaryExprOrTypeTraitExpr(
2875 EndVar
->getLocation(), UETT_SizeOf
,
2877 CreateParsedType(VAT
->desugar(),
2878 Context
.getTrivialTypeSourceInfo(
2879 VAT
->getElementType(), RangeLoc
))
2881 EndVar
->getSourceRange());
2882 if (SizeOfEachElementExprR
.isInvalid())
2886 ActOnBinOp(S
, EndVar
->getLocation(), tok::slash
,
2887 SizeOfVLAExprR
.get(), SizeOfEachElementExprR
.get());
2888 if (BoundExpr
.isInvalid())
2892 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2893 // UnqAT is not incomplete and Range is not type-dependent.
2894 llvm_unreachable("Unexpected array type in for-range");
2897 // end-expr is __range + __bound.
2898 EndExpr
= ActOnBinOp(S
, ColonLoc
, tok::plus
, EndRangeRef
.get(),
2900 if (EndExpr
.isInvalid())
2902 if (FinishForRangeVarDecl(*this, EndVar
, EndExpr
.get(), ColonLoc
,
2903 diag::err_for_range_iter_deduction_failure
)) {
2904 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
2908 OverloadCandidateSet
CandidateSet(RangeLoc
,
2909 OverloadCandidateSet::CSK_Normal
);
2910 BeginEndFunction BEFFailure
;
2911 ForRangeStatus RangeStatus
= BuildNonArrayForRange(
2912 *this, BeginRangeRef
.get(), EndRangeRef
.get(), RangeType
, BeginVar
,
2913 EndVar
, ColonLoc
, CoawaitLoc
, &CandidateSet
, &BeginExpr
, &EndExpr
,
2916 if (Kind
== BFRK_Build
&& RangeStatus
== FRS_NoViableFunction
&&
2917 BEFFailure
== BEF_begin
) {
2918 // If the range is being built from an array parameter, emit a
2919 // a diagnostic that it is being treated as a pointer.
2920 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Range
)) {
2921 if (ParmVarDecl
*PVD
= dyn_cast
<ParmVarDecl
>(DRE
->getDecl())) {
2922 QualType ArrayTy
= PVD
->getOriginalType();
2923 QualType PointerTy
= PVD
->getType();
2924 if (PointerTy
->isPointerType() && ArrayTy
->isArrayType()) {
2925 Diag(Range
->getBeginLoc(), diag::err_range_on_array_parameter
)
2926 << RangeLoc
<< PVD
<< ArrayTy
<< PointerTy
;
2927 Diag(PVD
->getLocation(), diag::note_declared_at
);
2933 // If building the range failed, try dereferencing the range expression
2934 // unless a diagnostic was issued or the end function is problematic.
2935 StmtResult SR
= RebuildForRangeWithDereference(*this, S
, ForLoc
,
2936 CoawaitLoc
, InitStmt
,
2937 LoopVarDecl
, ColonLoc
,
2940 if (SR
.isInvalid() || SR
.isUsable())
2944 // Otherwise, emit diagnostics if we haven't already.
2945 if (RangeStatus
== FRS_NoViableFunction
) {
2946 Expr
*Range
= BEFFailure
? EndRangeRef
.get() : BeginRangeRef
.get();
2947 CandidateSet
.NoteCandidates(
2948 PartialDiagnosticAt(Range
->getBeginLoc(),
2949 PDiag(diag::err_for_range_invalid
)
2950 << RangeLoc
<< Range
->getType()
2952 *this, OCD_AllCandidates
, Range
);
2954 // Return an error if no fix was discovered.
2955 if (RangeStatus
!= FRS_Success
)
2959 assert(!BeginExpr
.isInvalid() && !EndExpr
.isInvalid() &&
2960 "invalid range expression in for loop");
2962 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2963 // C++1z removes this restriction.
2964 QualType BeginType
= BeginVar
->getType(), EndType
= EndVar
->getType();
2965 if (!Context
.hasSameType(BeginType
, EndType
)) {
2966 Diag(RangeLoc
, getLangOpts().CPlusPlus17
2967 ? diag::warn_for_range_begin_end_types_differ
2968 : diag::ext_for_range_begin_end_types_differ
)
2969 << BeginType
<< EndType
;
2970 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
2971 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
2975 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar
), ColonLoc
, ColonLoc
);
2977 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar
), ColonLoc
, ColonLoc
);
2979 const QualType BeginRefNonRefType
= BeginType
.getNonReferenceType();
2980 ExprResult BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
2981 VK_LValue
, ColonLoc
);
2982 if (BeginRef
.isInvalid())
2985 ExprResult EndRef
= BuildDeclRefExpr(EndVar
, EndType
.getNonReferenceType(),
2986 VK_LValue
, ColonLoc
);
2987 if (EndRef
.isInvalid())
2990 // Build and check __begin != __end expression.
2991 NotEqExpr
= ActOnBinOp(S
, ColonLoc
, tok::exclaimequal
,
2992 BeginRef
.get(), EndRef
.get());
2993 if (!NotEqExpr
.isInvalid())
2994 NotEqExpr
= CheckBooleanCondition(ColonLoc
, NotEqExpr
.get());
2995 if (!NotEqExpr
.isInvalid())
2997 ActOnFinishFullExpr(NotEqExpr
.get(), /*DiscardedValue*/ false);
2998 if (NotEqExpr
.isInvalid()) {
2999 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3000 << RangeLoc
<< 0 << BeginRangeRef
.get()->getType();
3001 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3002 if (!Context
.hasSameType(BeginType
, EndType
))
3003 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
3007 // Build and check ++__begin expression.
3008 BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3009 VK_LValue
, ColonLoc
);
3010 if (BeginRef
.isInvalid())
3013 IncrExpr
= ActOnUnaryOp(S
, ColonLoc
, tok::plusplus
, BeginRef
.get());
3014 if (!IncrExpr
.isInvalid() && CoawaitLoc
.isValid())
3015 // FIXME: getCurScope() should not be used during template instantiation.
3016 // We should pick up the set of unqualified lookup results for operator
3017 // co_await during the initial parse.
3018 IncrExpr
= ActOnCoawaitExpr(S
, CoawaitLoc
, IncrExpr
.get());
3019 if (!IncrExpr
.isInvalid())
3020 IncrExpr
= ActOnFinishFullExpr(IncrExpr
.get(), /*DiscardedValue*/ false);
3021 if (IncrExpr
.isInvalid()) {
3022 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3023 << RangeLoc
<< 2 << BeginRangeRef
.get()->getType() ;
3024 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3028 // Build and check *__begin expression.
3029 BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3030 VK_LValue
, ColonLoc
);
3031 if (BeginRef
.isInvalid())
3034 ExprResult DerefExpr
= ActOnUnaryOp(S
, ColonLoc
, tok::star
, BeginRef
.get());
3035 if (DerefExpr
.isInvalid()) {
3036 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3037 << RangeLoc
<< 1 << BeginRangeRef
.get()->getType();
3038 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3042 // Attach *__begin as initializer for VD. Don't touch it if we're just
3043 // trying to determine whether this would be a valid range.
3044 if (!LoopVar
->isInvalidDecl() && Kind
!= BFRK_Check
) {
3045 AddInitializerToDecl(LoopVar
, DerefExpr
.get(), /*DirectInit=*/false);
3046 if (LoopVar
->isInvalidDecl() ||
3047 (LoopVar
->getInit() && LoopVar
->getInit()->containsErrors()))
3048 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3052 // Don't bother to actually allocate the result if we're just trying to
3053 // determine whether it would be valid.
3054 if (Kind
== BFRK_Check
)
3055 return StmtResult();
3057 // In OpenMP loop region loop control variable must be private. Perform
3058 // analysis of first part (if any).
3059 if (getLangOpts().OpenMP
>= 50 && BeginDeclStmt
.isUsable())
3060 ActOnOpenMPLoopInitialization(ForLoc
, BeginDeclStmt
.get());
3062 return new (Context
) CXXForRangeStmt(
3063 InitStmt
, RangeDS
, cast_or_null
<DeclStmt
>(BeginDeclStmt
.get()),
3064 cast_or_null
<DeclStmt
>(EndDeclStmt
.get()), NotEqExpr
.get(),
3065 IncrExpr
.get(), LoopVarDS
, /*Body=*/nullptr, ForLoc
, CoawaitLoc
,
3066 ColonLoc
, RParenLoc
);
3069 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
3071 StmtResult
Sema::FinishObjCForCollectionStmt(Stmt
*S
, Stmt
*B
) {
3074 ObjCForCollectionStmt
* ForStmt
= cast
<ObjCForCollectionStmt
>(S
);
3076 ForStmt
->setBody(B
);
3080 // Warn when the loop variable is a const reference that creates a copy.
3081 // Suggest using the non-reference type for copies. If a copy can be prevented
3082 // suggest the const reference type that would do so.
3083 // For instance, given "for (const &Foo : Range)", suggest
3084 // "for (const Foo : Range)" to denote a copy is made for the loop. If
3085 // possible, also suggest "for (const &Bar : Range)" if this type prevents
3086 // the copy altogether.
3087 static void DiagnoseForRangeReferenceVariableCopies(Sema
&SemaRef
,
3089 QualType RangeInitType
) {
3090 const Expr
*InitExpr
= VD
->getInit();
3094 QualType VariableType
= VD
->getType();
3096 if (auto Cleanups
= dyn_cast
<ExprWithCleanups
>(InitExpr
))
3097 if (!Cleanups
->cleanupsHaveSideEffects())
3098 InitExpr
= Cleanups
->getSubExpr();
3100 const MaterializeTemporaryExpr
*MTE
=
3101 dyn_cast
<MaterializeTemporaryExpr
>(InitExpr
);
3107 const Expr
*E
= MTE
->getSubExpr()->IgnoreImpCasts();
3109 // Searching for either UnaryOperator for dereference of a pointer or
3110 // CXXOperatorCallExpr for handling iterators.
3111 while (!isa
<CXXOperatorCallExpr
>(E
) && !isa
<UnaryOperator
>(E
)) {
3112 if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(E
)) {
3114 } else if (const CXXMemberCallExpr
*Call
= dyn_cast
<CXXMemberCallExpr
>(E
)) {
3115 const MemberExpr
*ME
= cast
<MemberExpr
>(Call
->getCallee());
3118 const MaterializeTemporaryExpr
*MTE
= cast
<MaterializeTemporaryExpr
>(E
);
3119 E
= MTE
->getSubExpr();
3121 E
= E
->IgnoreImpCasts();
3124 QualType ReferenceReturnType
;
3125 if (isa
<UnaryOperator
>(E
)) {
3126 ReferenceReturnType
= SemaRef
.Context
.getLValueReferenceType(E
->getType());
3128 const CXXOperatorCallExpr
*Call
= cast
<CXXOperatorCallExpr
>(E
);
3129 const FunctionDecl
*FD
= Call
->getDirectCallee();
3130 QualType ReturnType
= FD
->getReturnType();
3131 if (ReturnType
->isReferenceType())
3132 ReferenceReturnType
= ReturnType
;
3135 if (!ReferenceReturnType
.isNull()) {
3136 // Loop variable creates a temporary. Suggest either to go with
3137 // non-reference loop variable to indicate a copy is made, or
3138 // the correct type to bind a const reference.
3139 SemaRef
.Diag(VD
->getLocation(),
3140 diag::warn_for_range_const_ref_binds_temp_built_from_ref
)
3141 << VD
<< VariableType
<< ReferenceReturnType
;
3142 QualType NonReferenceType
= VariableType
.getNonReferenceType();
3143 NonReferenceType
.removeLocalConst();
3144 QualType NewReferenceType
=
3145 SemaRef
.Context
.getLValueReferenceType(E
->getType().withConst());
3146 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_type_or_non_reference
)
3147 << NonReferenceType
<< NewReferenceType
<< VD
->getSourceRange()
3148 << FixItHint::CreateRemoval(VD
->getTypeSpecEndLoc());
3149 } else if (!VariableType
->isRValueReferenceType()) {
3150 // The range always returns a copy, so a temporary is always created.
3151 // Suggest removing the reference from the loop variable.
3152 // If the type is a rvalue reference do not warn since that changes the
3153 // semantic of the code.
3154 SemaRef
.Diag(VD
->getLocation(), diag::warn_for_range_ref_binds_ret_temp
)
3155 << VD
<< RangeInitType
;
3156 QualType NonReferenceType
= VariableType
.getNonReferenceType();
3157 NonReferenceType
.removeLocalConst();
3158 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_non_reference_type
)
3159 << NonReferenceType
<< VD
->getSourceRange()
3160 << FixItHint::CreateRemoval(VD
->getTypeSpecEndLoc());
3164 /// Determines whether the @p VariableType's declaration is a record with the
3165 /// clang::trivial_abi attribute.
3166 static bool hasTrivialABIAttr(QualType VariableType
) {
3167 if (CXXRecordDecl
*RD
= VariableType
->getAsCXXRecordDecl())
3168 return RD
->hasAttr
<TrivialABIAttr
>();
3173 // Warns when the loop variable can be changed to a reference type to
3174 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3175 // "for (const Foo &x : Range)" if this form does not make a copy.
3176 static void DiagnoseForRangeConstVariableCopies(Sema
&SemaRef
,
3177 const VarDecl
*VD
) {
3178 const Expr
*InitExpr
= VD
->getInit();
3182 QualType VariableType
= VD
->getType();
3184 if (const CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(InitExpr
)) {
3185 if (!CE
->getConstructor()->isCopyConstructor())
3187 } else if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(InitExpr
)) {
3188 if (CE
->getCastKind() != CK_LValueToRValue
)
3194 // Small trivially copyable types are cheap to copy. Do not emit the
3195 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3196 // (The function `getTypeSize` returns the size in bits.)
3197 ASTContext
&Ctx
= SemaRef
.Context
;
3198 if (Ctx
.getTypeSize(VariableType
) <= 64 * 8 &&
3199 (VariableType
.isTriviallyCopyableType(Ctx
) ||
3200 hasTrivialABIAttr(VariableType
)))
3203 // Suggest changing from a const variable to a const reference variable
3204 // if doing so will prevent a copy.
3205 SemaRef
.Diag(VD
->getLocation(), diag::warn_for_range_copy
)
3206 << VD
<< VariableType
;
3207 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_reference_type
)
3208 << SemaRef
.Context
.getLValueReferenceType(VariableType
)
3209 << VD
->getSourceRange()
3210 << FixItHint::CreateInsertion(VD
->getLocation(), "&");
3213 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3214 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3215 /// using "const foo x" to show that a copy is made
3216 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3217 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
3218 /// prevent the copy.
3219 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
3220 /// Suggest "const foo &x" to prevent the copy.
3221 static void DiagnoseForRangeVariableCopies(Sema
&SemaRef
,
3222 const CXXForRangeStmt
*ForStmt
) {
3223 if (SemaRef
.inTemplateInstantiation())
3226 if (SemaRef
.Diags
.isIgnored(
3227 diag::warn_for_range_const_ref_binds_temp_built_from_ref
,
3228 ForStmt
->getBeginLoc()) &&
3229 SemaRef
.Diags
.isIgnored(diag::warn_for_range_ref_binds_ret_temp
,
3230 ForStmt
->getBeginLoc()) &&
3231 SemaRef
.Diags
.isIgnored(diag::warn_for_range_copy
,
3232 ForStmt
->getBeginLoc())) {
3236 const VarDecl
*VD
= ForStmt
->getLoopVariable();
3240 QualType VariableType
= VD
->getType();
3242 if (VariableType
->isIncompleteType())
3245 const Expr
*InitExpr
= VD
->getInit();
3249 if (InitExpr
->getExprLoc().isMacroID())
3252 if (VariableType
->isReferenceType()) {
3253 DiagnoseForRangeReferenceVariableCopies(SemaRef
, VD
,
3254 ForStmt
->getRangeInit()->getType());
3255 } else if (VariableType
.isConstQualified()) {
3256 DiagnoseForRangeConstVariableCopies(SemaRef
, VD
);
3260 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
3261 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
3262 /// body cannot be performed until after the type of the range variable is
3264 StmtResult
Sema::FinishCXXForRangeStmt(Stmt
*S
, Stmt
*B
) {
3268 if (isa
<ObjCForCollectionStmt
>(S
))
3269 return FinishObjCForCollectionStmt(S
, B
);
3271 CXXForRangeStmt
*ForStmt
= cast
<CXXForRangeStmt
>(S
);
3272 ForStmt
->setBody(B
);
3274 DiagnoseEmptyStmtBody(ForStmt
->getRParenLoc(), B
,
3275 diag::warn_empty_range_based_for_body
);
3277 DiagnoseForRangeVariableCopies(*this, ForStmt
);
3282 StmtResult
Sema::ActOnGotoStmt(SourceLocation GotoLoc
,
3283 SourceLocation LabelLoc
,
3284 LabelDecl
*TheDecl
) {
3285 setFunctionHasBranchIntoScope();
3286 TheDecl
->markUsed(Context
);
3287 return new (Context
) GotoStmt(TheDecl
, GotoLoc
, LabelLoc
);
3291 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc
, SourceLocation StarLoc
,
3293 // Convert operand to void*
3294 if (!E
->isTypeDependent()) {
3295 QualType ETy
= E
->getType();
3296 QualType DestTy
= Context
.getPointerType(Context
.VoidTy
.withConst());
3297 ExprResult ExprRes
= E
;
3298 AssignConvertType ConvTy
=
3299 CheckSingleAssignmentConstraints(DestTy
, ExprRes
);
3300 if (ExprRes
.isInvalid())
3303 if (DiagnoseAssignmentResult(ConvTy
, StarLoc
, DestTy
, ETy
, E
, AA_Passing
))
3307 ExprResult ExprRes
= ActOnFinishFullExpr(E
, /*DiscardedValue*/ false);
3308 if (ExprRes
.isInvalid())
3312 setFunctionHasIndirectGoto();
3314 return new (Context
) IndirectGotoStmt(GotoLoc
, StarLoc
, E
);
3317 static void CheckJumpOutOfSEHFinally(Sema
&S
, SourceLocation Loc
,
3318 const Scope
&DestScope
) {
3319 if (!S
.CurrentSEHFinally
.empty() &&
3320 DestScope
.Contains(*S
.CurrentSEHFinally
.back())) {
3321 S
.Diag(Loc
, diag::warn_jump_out_of_seh_finally
);
3326 Sema::ActOnContinueStmt(SourceLocation ContinueLoc
, Scope
*CurScope
) {
3327 Scope
*S
= CurScope
->getContinueParent();
3329 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3330 return StmtError(Diag(ContinueLoc
, diag::err_continue_not_in_loop
));
3332 if (S
->isConditionVarScope()) {
3333 // We cannot 'continue;' from within a statement expression in the
3334 // initializer of a condition variable because we would jump past the
3335 // initialization of that variable.
3336 return StmtError(Diag(ContinueLoc
, diag::err_continue_from_cond_var_init
));
3338 CheckJumpOutOfSEHFinally(*this, ContinueLoc
, *S
);
3340 return new (Context
) ContinueStmt(ContinueLoc
);
3344 Sema::ActOnBreakStmt(SourceLocation BreakLoc
, Scope
*CurScope
) {
3345 Scope
*S
= CurScope
->getBreakParent();
3347 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3348 return StmtError(Diag(BreakLoc
, diag::err_break_not_in_loop_or_switch
));
3350 if (S
->isOpenMPLoopScope())
3351 return StmtError(Diag(BreakLoc
, diag::err_omp_loop_cannot_use_stmt
)
3353 CheckJumpOutOfSEHFinally(*this, BreakLoc
, *S
);
3355 return new (Context
) BreakStmt(BreakLoc
);
3358 /// Determine whether the given expression might be move-eligible or
3359 /// copy-elidable in either a (co_)return statement or throw expression,
3360 /// without considering function return type, if applicable.
3362 /// \param E The expression being returned from the function or block,
3363 /// being thrown, or being co_returned from a coroutine. This expression
3364 /// might be modified by the implementation.
3366 /// \param Mode Overrides detection of current language mode
3367 /// and uses the rules for C++23.
3369 /// \returns An aggregate which contains the Candidate and isMoveEligible
3370 /// and isCopyElidable methods. If Candidate is non-null, it means
3371 /// isMoveEligible() would be true under the most permissive language standard.
3372 Sema::NamedReturnInfo
Sema::getNamedReturnInfo(Expr
*&E
,
3373 SimplerImplicitMoveMode Mode
) {
3375 return NamedReturnInfo();
3376 // - in a return statement in a function [where] ...
3377 // ... the expression is the name of a non-volatile automatic object ...
3378 const auto *DR
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens());
3379 if (!DR
|| DR
->refersToEnclosingVariableOrCapture())
3380 return NamedReturnInfo();
3381 const auto *VD
= dyn_cast
<VarDecl
>(DR
->getDecl());
3383 return NamedReturnInfo();
3384 NamedReturnInfo Res
= getNamedReturnInfo(VD
);
3385 if (Res
.Candidate
&& !E
->isXValue() &&
3386 (Mode
== SimplerImplicitMoveMode::ForceOn
||
3387 (Mode
!= SimplerImplicitMoveMode::ForceOff
&&
3388 getLangOpts().CPlusPlus23
))) {
3389 E
= ImplicitCastExpr::Create(Context
, VD
->getType().getNonReferenceType(),
3390 CK_NoOp
, E
, nullptr, VK_XValue
,
3391 FPOptionsOverride());
3396 /// Determine whether the given NRVO candidate variable is move-eligible or
3397 /// copy-elidable, without considering function return type.
3399 /// \param VD The NRVO candidate variable.
3401 /// \returns An aggregate which contains the Candidate and isMoveEligible
3402 /// and isCopyElidable methods. If Candidate is non-null, it means
3403 /// isMoveEligible() would be true under the most permissive language standard.
3404 Sema::NamedReturnInfo
Sema::getNamedReturnInfo(const VarDecl
*VD
) {
3405 NamedReturnInfo Info
{VD
, NamedReturnInfo::MoveEligibleAndCopyElidable
};
3407 // C++20 [class.copy.elision]p3:
3408 // - in a return statement in a function with ...
3409 // (other than a function ... parameter)
3410 if (VD
->getKind() == Decl::ParmVar
)
3411 Info
.S
= NamedReturnInfo::MoveEligible
;
3412 else if (VD
->getKind() != Decl::Var
)
3413 return NamedReturnInfo();
3415 // (other than ... a catch-clause parameter)
3416 if (VD
->isExceptionVariable())
3417 Info
.S
= NamedReturnInfo::MoveEligible
;
3420 if (!VD
->hasLocalStorage())
3421 return NamedReturnInfo();
3423 // We don't want to implicitly move out of a __block variable during a return
3424 // because we cannot assume the variable will no longer be used.
3425 if (VD
->hasAttr
<BlocksAttr
>())
3426 return NamedReturnInfo();
3428 QualType VDType
= VD
->getType();
3429 if (VDType
->isObjectType()) {
3430 // C++17 [class.copy.elision]p3:
3431 // ...non-volatile automatic object...
3432 if (VDType
.isVolatileQualified())
3433 return NamedReturnInfo();
3434 } else if (VDType
->isRValueReferenceType()) {
3435 // C++20 [class.copy.elision]p3:
3436 // ...either a non-volatile object or an rvalue reference to a non-volatile
3438 QualType VDReferencedType
= VDType
.getNonReferenceType();
3439 if (VDReferencedType
.isVolatileQualified() ||
3440 !VDReferencedType
->isObjectType())
3441 return NamedReturnInfo();
3442 Info
.S
= NamedReturnInfo::MoveEligible
;
3444 return NamedReturnInfo();
3447 // Variables with higher required alignment than their type's ABI
3448 // alignment cannot use NRVO.
3449 if (!VD
->hasDependentAlignment() &&
3450 Context
.getDeclAlign(VD
) > Context
.getTypeAlignInChars(VDType
))
3451 Info
.S
= NamedReturnInfo::MoveEligible
;
3456 /// Updates given NamedReturnInfo's move-eligible and
3457 /// copy-elidable statuses, considering the function
3458 /// return type criteria as applicable to return statements.
3460 /// \param Info The NamedReturnInfo object to update.
3462 /// \param ReturnType This is the return type of the function.
3463 /// \returns The copy elision candidate, in case the initial return expression
3464 /// was copy elidable, or nullptr otherwise.
3465 const VarDecl
*Sema::getCopyElisionCandidate(NamedReturnInfo
&Info
,
3466 QualType ReturnType
) {
3467 if (!Info
.Candidate
)
3470 auto invalidNRVO
= [&] {
3471 Info
= NamedReturnInfo();
3475 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3476 // there is no point in allowing copy elision since we won't have it deduced
3477 // by the point the VardDecl is instantiated, which is the last chance we have
3478 // of deciding if the candidate is really copy elidable.
3479 if ((ReturnType
->getTypeClass() == Type::TypeClass::Auto
&&
3480 ReturnType
->isCanonicalUnqualified()) ||
3481 ReturnType
->isSpecificBuiltinType(BuiltinType::Dependent
))
3482 return invalidNRVO();
3484 if (!ReturnType
->isDependentType()) {
3485 // - in a return statement in a function with ...
3486 // ... a class return type ...
3487 if (!ReturnType
->isRecordType())
3488 return invalidNRVO();
3490 QualType VDType
= Info
.Candidate
->getType();
3491 // ... the same cv-unqualified type as the function return type ...
3492 // When considering moving this expression out, allow dissimilar types.
3493 if (!VDType
->isDependentType() &&
3494 !Context
.hasSameUnqualifiedType(ReturnType
, VDType
))
3495 Info
.S
= NamedReturnInfo::MoveEligible
;
3497 return Info
.isCopyElidable() ? Info
.Candidate
: nullptr;
3500 /// Verify that the initialization sequence that was picked for the
3501 /// first overload resolution is permissible under C++98.
3503 /// Reject (possibly converting) constructors not taking an rvalue reference,
3504 /// or user conversion operators which are not ref-qualified.
3506 VerifyInitializationSequenceCXX98(const Sema
&S
,
3507 const InitializationSequence
&Seq
) {
3508 const auto *Step
= llvm::find_if(Seq
.steps(), [](const auto &Step
) {
3509 return Step
.Kind
== InitializationSequence::SK_ConstructorInitialization
||
3510 Step
.Kind
== InitializationSequence::SK_UserConversion
;
3512 if (Step
!= Seq
.step_end()) {
3513 const auto *FD
= Step
->Function
.Function
;
3514 if (isa
<CXXConstructorDecl
>(FD
)
3515 ? !FD
->getParamDecl(0)->getType()->isRValueReferenceType()
3516 : cast
<CXXMethodDecl
>(FD
)->getRefQualifier() == RQ_None
)
3522 /// Perform the initialization of a potentially-movable value, which
3523 /// is the result of return value.
3525 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
3526 /// treat returned lvalues as rvalues in certain cases (to prefer move
3527 /// construction), then falls back to treating them as lvalues if that failed.
3528 ExprResult
Sema::PerformMoveOrCopyInitialization(
3529 const InitializedEntity
&Entity
, const NamedReturnInfo
&NRInfo
, Expr
*Value
,
3530 bool SupressSimplerImplicitMoves
) {
3531 if (getLangOpts().CPlusPlus
&&
3532 (!getLangOpts().CPlusPlus23
|| SupressSimplerImplicitMoves
) &&
3533 NRInfo
.isMoveEligible()) {
3534 ImplicitCastExpr
AsRvalue(ImplicitCastExpr::OnStack
, Value
->getType(),
3535 CK_NoOp
, Value
, VK_XValue
, FPOptionsOverride());
3536 Expr
*InitExpr
= &AsRvalue
;
3537 auto Kind
= InitializationKind::CreateCopy(Value
->getBeginLoc(),
3538 Value
->getBeginLoc());
3539 InitializationSequence
Seq(*this, Entity
, Kind
, InitExpr
);
3540 auto Res
= Seq
.getFailedOverloadResult();
3541 if ((Res
== OR_Success
|| Res
== OR_Deleted
) &&
3542 (getLangOpts().CPlusPlus11
||
3543 VerifyInitializationSequenceCXX98(*this, Seq
))) {
3544 // Promote "AsRvalue" to the heap, since we now need this
3545 // expression node to persist.
3547 ImplicitCastExpr::Create(Context
, Value
->getType(), CK_NoOp
, Value
,
3548 nullptr, VK_XValue
, FPOptionsOverride());
3549 // Complete type-checking the initialization of the return type
3550 // using the constructor we found.
3551 return Seq
.Perform(*this, Entity
, Kind
, Value
);
3554 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3555 // above, or overload resolution failed. Either way, we need to try
3556 // (again) now with the return value expression as written.
3557 return PerformCopyInitialization(Entity
, SourceLocation(), Value
);
3560 /// Determine whether the declared return type of the specified function
3561 /// contains 'auto'.
3562 static bool hasDeducedReturnType(FunctionDecl
*FD
) {
3563 const FunctionProtoType
*FPT
=
3564 FD
->getTypeSourceInfo()->getType()->castAs
<FunctionProtoType
>();
3565 return FPT
->getReturnType()->isUndeducedType();
3568 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3569 /// for capturing scopes.
3571 StmtResult
Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc
,
3573 NamedReturnInfo
&NRInfo
,
3574 bool SupressSimplerImplicitMoves
) {
3575 // If this is the first return we've seen, infer the return type.
3576 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3577 CapturingScopeInfo
*CurCap
= cast
<CapturingScopeInfo
>(getCurFunction());
3578 QualType FnRetType
= CurCap
->ReturnType
;
3579 LambdaScopeInfo
*CurLambda
= dyn_cast
<LambdaScopeInfo
>(CurCap
);
3580 if (CurLambda
&& CurLambda
->CallOperator
->getType().isNull())
3582 bool HasDeducedReturnType
=
3583 CurLambda
&& hasDeducedReturnType(CurLambda
->CallOperator
);
3585 if (ExprEvalContexts
.back().isDiscardedStatementContext() &&
3586 (HasDeducedReturnType
|| CurCap
->HasImplicitReturnType
)) {
3589 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
3592 RetValExp
= ER
.get();
3594 return ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
3595 /* NRVOCandidate=*/nullptr);
3598 if (HasDeducedReturnType
) {
3599 FunctionDecl
*FD
= CurLambda
->CallOperator
;
3600 // If we've already decided this lambda is invalid, e.g. because
3601 // we saw a `return` whose expression had an error, don't keep
3602 // trying to deduce its return type.
3603 if (FD
->isInvalidDecl())
3605 // In C++1y, the return type may involve 'auto'.
3606 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3607 if (CurCap
->ReturnType
.isNull())
3608 CurCap
->ReturnType
= FD
->getReturnType();
3610 AutoType
*AT
= CurCap
->ReturnType
->getContainedAutoType();
3611 assert(AT
&& "lost auto type from lambda return type");
3612 if (DeduceFunctionTypeFromReturnExpr(FD
, ReturnLoc
, RetValExp
, AT
)) {
3613 FD
->setInvalidDecl();
3614 // FIXME: preserve the ill-formed return expression.
3617 CurCap
->ReturnType
= FnRetType
= FD
->getReturnType();
3618 } else if (CurCap
->HasImplicitReturnType
) {
3619 // For blocks/lambdas with implicit return types, we check each return
3620 // statement individually, and deduce the common return type when the block
3621 // or lambda is completed.
3622 // FIXME: Fold this into the 'auto' codepath above.
3623 if (RetValExp
&& !isa
<InitListExpr
>(RetValExp
)) {
3624 ExprResult Result
= DefaultFunctionArrayLvalueConversion(RetValExp
);
3625 if (Result
.isInvalid())
3627 RetValExp
= Result
.get();
3629 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3630 // when deducing a return type for a lambda-expression (or by extension
3631 // for a block). These rules differ from the stated C++11 rules only in
3632 // that they remove top-level cv-qualifiers.
3633 if (!CurContext
->isDependentContext())
3634 FnRetType
= RetValExp
->getType().getUnqualifiedType();
3636 FnRetType
= CurCap
->ReturnType
= Context
.DependentTy
;
3639 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3640 // initializer list, because it is not an expression (even
3641 // though we represent it as one). We still deduce 'void'.
3642 Diag(ReturnLoc
, diag::err_lambda_return_init_list
)
3643 << RetValExp
->getSourceRange();
3646 FnRetType
= Context
.VoidTy
;
3649 // Although we'll properly infer the type of the block once it's completed,
3650 // make sure we provide a return type now for better error recovery.
3651 if (CurCap
->ReturnType
.isNull())
3652 CurCap
->ReturnType
= FnRetType
;
3654 const VarDecl
*NRVOCandidate
= getCopyElisionCandidate(NRInfo
, FnRetType
);
3656 if (auto *CurBlock
= dyn_cast
<BlockScopeInfo
>(CurCap
)) {
3657 if (CurBlock
->FunctionType
->castAs
<FunctionType
>()->getNoReturnAttr()) {
3658 Diag(ReturnLoc
, diag::err_noreturn_block_has_return_expr
);
3661 } else if (auto *CurRegion
= dyn_cast
<CapturedRegionScopeInfo
>(CurCap
)) {
3662 Diag(ReturnLoc
, diag::err_return_in_captured_stmt
) << CurRegion
->getRegionName();
3665 assert(CurLambda
&& "unknown kind of captured scope");
3666 if (CurLambda
->CallOperator
->getType()
3667 ->castAs
<FunctionType
>()
3668 ->getNoReturnAttr()) {
3669 Diag(ReturnLoc
, diag::err_noreturn_lambda_has_return_expr
);
3674 // Otherwise, verify that this result type matches the previous one. We are
3675 // pickier with blocks than for normal functions because we don't have GCC
3676 // compatibility to worry about here.
3677 if (FnRetType
->isDependentType()) {
3678 // Delay processing for now. TODO: there are lots of dependent
3679 // types we can conclusively prove aren't void.
3680 } else if (FnRetType
->isVoidType()) {
3681 if (RetValExp
&& !isa
<InitListExpr
>(RetValExp
) &&
3682 !(getLangOpts().CPlusPlus
&&
3683 (RetValExp
->isTypeDependent() ||
3684 RetValExp
->getType()->isVoidType()))) {
3685 if (!getLangOpts().CPlusPlus
&&
3686 RetValExp
->getType()->isVoidType())
3687 Diag(ReturnLoc
, diag::ext_return_has_void_expr
) << "literal" << 2;
3689 Diag(ReturnLoc
, diag::err_return_block_has_expr
);
3690 RetValExp
= nullptr;
3693 } else if (!RetValExp
) {
3694 return StmtError(Diag(ReturnLoc
, diag::err_block_return_missing_expr
));
3695 } else if (!RetValExp
->isTypeDependent()) {
3696 // we have a non-void block with an expression, continue checking
3698 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3699 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3702 // In C++ the return statement is handled via a copy initialization.
3703 // the C version of which boils down to CheckSingleAssignmentConstraints.
3704 InitializedEntity Entity
=
3705 InitializedEntity::InitializeResult(ReturnLoc
, FnRetType
);
3706 ExprResult Res
= PerformMoveOrCopyInitialization(
3707 Entity
, NRInfo
, RetValExp
, SupressSimplerImplicitMoves
);
3708 if (Res
.isInvalid()) {
3709 // FIXME: Cleanup temporaries here, anyway?
3712 RetValExp
= Res
.get();
3713 CheckReturnValExpr(RetValExp
, FnRetType
, ReturnLoc
);
3718 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
3721 RetValExp
= ER
.get();
3724 ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
, NRVOCandidate
);
3726 // If we need to check for the named return value optimization,
3727 // or if we need to infer the return type,
3728 // save the return statement in our scope for later processing.
3729 if (CurCap
->HasImplicitReturnType
|| NRVOCandidate
)
3730 FunctionScopes
.back()->Returns
.push_back(Result
);
3732 if (FunctionScopes
.back()->FirstReturnLoc
.isInvalid())
3733 FunctionScopes
.back()->FirstReturnLoc
= ReturnLoc
;
3735 if (auto *CurBlock
= dyn_cast
<BlockScopeInfo
>(CurCap
);
3736 CurBlock
&& CurCap
->HasImplicitReturnType
&& RetValExp
&&
3737 RetValExp
->containsErrors())
3738 CurBlock
->TheDecl
->setInvalidDecl();
3744 /// Marks all typedefs in all local classes in a type referenced.
3746 /// In a function like
3748 /// struct S { typedef int a; };
3752 /// the local type escapes and could be referenced in some TUs but not in
3753 /// others. Pretend that all local typedefs are always referenced, to not warn
3754 /// on this. This isn't necessary if f has internal linkage, or the typedef
3756 class LocalTypedefNameReferencer
3757 : public RecursiveASTVisitor
<LocalTypedefNameReferencer
> {
3759 LocalTypedefNameReferencer(Sema
&S
) : S(S
) {}
3760 bool VisitRecordType(const RecordType
*RT
);
3764 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType
*RT
) {
3765 auto *R
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl());
3766 if (!R
|| !R
->isLocalClass() || !R
->isLocalClass()->isExternallyVisible() ||
3767 R
->isDependentType())
3769 for (auto *TmpD
: R
->decls())
3770 if (auto *T
= dyn_cast
<TypedefNameDecl
>(TmpD
))
3771 if (T
->getAccess() != AS_private
|| R
->hasFriends())
3772 S
.MarkAnyDeclReferenced(T
->getLocation(), T
, /*OdrUse=*/false);
3777 TypeLoc
Sema::getReturnTypeLoc(FunctionDecl
*FD
) const {
3778 return FD
->getTypeSourceInfo()
3780 .getAsAdjusted
<FunctionProtoTypeLoc
>()
3784 /// Deduce the return type for a function from a returned expression, per
3785 /// C++1y [dcl.spec.auto]p6.
3786 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl
*FD
,
3787 SourceLocation ReturnLoc
,
3788 Expr
*RetExpr
, const AutoType
*AT
) {
3789 // If this is the conversion function for a lambda, we choose to deduce its
3790 // type from the corresponding call operator, not from the synthesized return
3791 // statement within it. See Sema::DeduceReturnType.
3792 if (isLambdaConversionOperator(FD
))
3795 if (RetExpr
&& isa
<InitListExpr
>(RetExpr
)) {
3796 // If the deduction is for a return statement and the initializer is
3797 // a braced-init-list, the program is ill-formed.
3798 Diag(RetExpr
->getExprLoc(),
3799 getCurLambda() ? diag::err_lambda_return_init_list
3800 : diag::err_auto_fn_return_init_list
)
3801 << RetExpr
->getSourceRange();
3805 if (FD
->isDependentContext()) {
3806 // C++1y [dcl.spec.auto]p12:
3807 // Return type deduction [...] occurs when the definition is
3808 // instantiated even if the function body contains a return
3809 // statement with a non-type-dependent operand.
3810 assert(AT
->isDeduced() && "should have deduced to dependent type");
3814 TypeLoc OrigResultType
= getReturnTypeLoc(FD
);
3815 // In the case of a return with no operand, the initializer is considered
3817 CXXScalarValueInitExpr
VoidVal(Context
.VoidTy
, nullptr, SourceLocation());
3819 // For a function with a deduced result type to return with omitted
3820 // expression, the result type as written must be 'auto' or
3821 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3823 if (!OrigResultType
.getType()->getAs
<AutoType
>()) {
3824 Diag(ReturnLoc
, diag::err_auto_fn_return_void_but_not_auto
)
3825 << OrigResultType
.getType();
3831 QualType Deduced
= AT
->getDeducedType();
3833 // Otherwise, [...] deduce a value for U using the rules of template
3834 // argument deduction.
3835 auto RetExprLoc
= RetExpr
->getExprLoc();
3836 TemplateDeductionInfo
Info(RetExprLoc
);
3837 SourceLocation TemplateSpecLoc
;
3838 if (RetExpr
->getType() == Context
.OverloadTy
) {
3839 auto FindResult
= OverloadExpr::find(RetExpr
);
3840 if (FindResult
.Expression
)
3841 TemplateSpecLoc
= FindResult
.Expression
->getNameLoc();
3843 TemplateSpecCandidateSet
FailedTSC(TemplateSpecLoc
);
3844 TemplateDeductionResult Res
= DeduceAutoType(
3845 OrigResultType
, RetExpr
, Deduced
, Info
, /*DependentDeduction=*/false,
3846 /*IgnoreConstraints=*/false, &FailedTSC
);
3847 if (Res
!= TDK_Success
&& FD
->isInvalidDecl())
3852 case TDK_AlreadyDiagnosed
:
3854 case TDK_Inconsistent
: {
3855 // If a function with a declared return type that contains a placeholder
3856 // type has multiple return statements, the return type is deduced for
3857 // each return statement. [...] if the type deduced is not the same in
3858 // each deduction, the program is ill-formed.
3859 const LambdaScopeInfo
*LambdaSI
= getCurLambda();
3860 if (LambdaSI
&& LambdaSI
->HasImplicitReturnType
)
3861 Diag(ReturnLoc
, diag::err_typecheck_missing_return_type_incompatible
)
3862 << Info
.SecondArg
<< Info
.FirstArg
<< true /*IsLambda*/;
3864 Diag(ReturnLoc
, diag::err_auto_fn_different_deductions
)
3865 << (AT
->isDecltypeAuto() ? 1 : 0) << Info
.SecondArg
3870 Diag(RetExpr
->getExprLoc(), diag::err_auto_fn_deduction_failure
)
3871 << OrigResultType
.getType() << RetExpr
->getType();
3872 FailedTSC
.NoteCandidates(*this, RetExprLoc
);
3877 // If a local type is part of the returned type, mark its fields as
3879 LocalTypedefNameReferencer(*this).TraverseType(RetExpr
->getType());
3881 // CUDA: Kernel function must have 'void' return type.
3882 if (getLangOpts().CUDA
&& FD
->hasAttr
<CUDAGlobalAttr
>() &&
3883 !Deduced
->isVoidType()) {
3884 Diag(FD
->getLocation(), diag::err_kern_type_not_void_return
)
3885 << FD
->getType() << FD
->getSourceRange();
3889 if (!FD
->isInvalidDecl() && AT
->getDeducedType() != Deduced
)
3890 // Update all declarations of the function to have the deduced return type.
3891 Context
.adjustDeducedFunctionResultType(FD
, Deduced
);
3897 Sema::ActOnReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
,
3899 // Correct typos, in case the containing function returns 'auto' and
3900 // RetValExp should determine the deduced type.
3901 ExprResult RetVal
= CorrectDelayedTyposInExpr(
3902 RetValExp
, nullptr, /*RecoverUncorrectedTypos=*/true);
3903 if (RetVal
.isInvalid())
3906 BuildReturnStmt(ReturnLoc
, RetVal
.get(), /*AllowRecovery=*/true);
3907 if (R
.isInvalid() || ExprEvalContexts
.back().isDiscardedStatementContext())
3911 const_cast<VarDecl
*>(cast
<ReturnStmt
>(R
.get())->getNRVOCandidate());
3913 CurScope
->updateNRVOCandidate(VD
);
3915 CheckJumpOutOfSEHFinally(*this, ReturnLoc
, *CurScope
->getFnParent());
3920 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema
&S
,
3922 if (!E
|| !S
.getLangOpts().CPlusPlus23
|| !S
.getLangOpts().MSVCCompat
)
3924 const Decl
*D
= E
->getReferencedDeclOfCallee();
3925 if (!D
|| !S
.SourceMgr
.isInSystemHeader(D
->getLocation()))
3927 for (const DeclContext
*DC
= D
->getDeclContext(); DC
; DC
= DC
->getParent()) {
3928 if (DC
->isStdNamespace())
3934 StmtResult
Sema::BuildReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
,
3935 bool AllowRecovery
) {
3936 // Check for unexpanded parameter packs.
3937 if (RetValExp
&& DiagnoseUnexpandedParameterPack(RetValExp
))
3940 // HACK: We suppress simpler implicit move here in msvc compatibility mode
3941 // just as a temporary work around, as the MSVC STL has issues with
3943 bool SupressSimplerImplicitMoves
=
3944 CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp
);
3945 NamedReturnInfo NRInfo
= getNamedReturnInfo(
3946 RetValExp
, SupressSimplerImplicitMoves
? SimplerImplicitMoveMode::ForceOff
3947 : SimplerImplicitMoveMode::Normal
);
3949 if (isa
<CapturingScopeInfo
>(getCurFunction()))
3950 return ActOnCapScopeReturnStmt(ReturnLoc
, RetValExp
, NRInfo
,
3951 SupressSimplerImplicitMoves
);
3954 QualType RelatedRetType
;
3955 const AttrVec
*Attrs
= nullptr;
3956 bool isObjCMethod
= false;
3958 if (const FunctionDecl
*FD
= getCurFunctionDecl()) {
3959 FnRetType
= FD
->getReturnType();
3961 Attrs
= &FD
->getAttrs();
3962 if (FD
->isNoReturn())
3963 Diag(ReturnLoc
, diag::warn_noreturn_function_has_return_expr
) << FD
;
3964 if (FD
->isMain() && RetValExp
)
3965 if (isa
<CXXBoolLiteralExpr
>(RetValExp
))
3966 Diag(ReturnLoc
, diag::warn_main_returns_bool_literal
)
3967 << RetValExp
->getSourceRange();
3968 if (FD
->hasAttr
<CmseNSEntryAttr
>() && RetValExp
) {
3969 if (const auto *RT
= dyn_cast
<RecordType
>(FnRetType
.getCanonicalType())) {
3970 if (RT
->getDecl()->isOrContainsUnion())
3971 Diag(RetValExp
->getBeginLoc(), diag::warn_cmse_nonsecure_union
) << 1;
3974 } else if (ObjCMethodDecl
*MD
= getCurMethodDecl()) {
3975 FnRetType
= MD
->getReturnType();
3976 isObjCMethod
= true;
3978 Attrs
= &MD
->getAttrs();
3979 if (MD
->hasRelatedResultType() && MD
->getClassInterface()) {
3980 // In the implementation of a method with a related return type, the
3981 // type used to type-check the validity of return statements within the
3982 // method body is a pointer to the type of the class being implemented.
3983 RelatedRetType
= Context
.getObjCInterfaceType(MD
->getClassInterface());
3984 RelatedRetType
= Context
.getObjCObjectPointerType(RelatedRetType
);
3986 } else // If we don't have a function/method context, bail.
3990 const auto *ATy
= dyn_cast
<ArrayType
>(RetValExp
->getType());
3991 if (ATy
&& ATy
->getElementType().isWebAssemblyReferenceType()) {
3992 Diag(ReturnLoc
, diag::err_wasm_table_art
) << 1;
3997 // C++1z: discarded return statements are not considered when deducing a
3999 if (ExprEvalContexts
.back().isDiscardedStatementContext() &&
4000 FnRetType
->getContainedAutoType()) {
4003 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4006 RetValExp
= ER
.get();
4008 return ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
4009 /* NRVOCandidate=*/nullptr);
4012 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
4014 if (getLangOpts().CPlusPlus14
) {
4015 if (AutoType
*AT
= FnRetType
->getContainedAutoType()) {
4016 FunctionDecl
*FD
= cast
<FunctionDecl
>(CurContext
);
4017 // If we've already decided this function is invalid, e.g. because
4018 // we saw a `return` whose expression had an error, don't keep
4019 // trying to deduce its return type.
4020 // (Some return values may be needlessly wrapped in RecoveryExpr).
4021 if (FD
->isInvalidDecl() ||
4022 DeduceFunctionTypeFromReturnExpr(FD
, ReturnLoc
, RetValExp
, AT
)) {
4023 FD
->setInvalidDecl();
4026 // The deduction failure is diagnosed and marked, try to recover.
4028 // Wrap return value with a recovery expression of the previous type.
4029 // If no deduction yet, use DependentTy.
4030 auto Recovery
= CreateRecoveryExpr(
4031 RetValExp
->getBeginLoc(), RetValExp
->getEndLoc(), RetValExp
,
4032 AT
->isDeduced() ? FnRetType
: QualType());
4033 if (Recovery
.isInvalid())
4035 RetValExp
= Recovery
.get();
4037 // Nothing to do: a ReturnStmt with no value is fine recovery.
4040 FnRetType
= FD
->getReturnType();
4044 const VarDecl
*NRVOCandidate
= getCopyElisionCandidate(NRInfo
, FnRetType
);
4046 bool HasDependentReturnType
= FnRetType
->isDependentType();
4048 ReturnStmt
*Result
= nullptr;
4049 if (FnRetType
->isVoidType()) {
4051 if (auto *ILE
= dyn_cast
<InitListExpr
>(RetValExp
)) {
4052 // We simply never allow init lists as the return value of void
4053 // functions. This is compatible because this was never allowed before,
4054 // so there's no legacy code to deal with.
4055 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4056 int FunctionKind
= 0;
4057 if (isa
<ObjCMethodDecl
>(CurDecl
))
4059 else if (isa
<CXXConstructorDecl
>(CurDecl
))
4061 else if (isa
<CXXDestructorDecl
>(CurDecl
))
4064 Diag(ReturnLoc
, diag::err_return_init_list
)
4065 << CurDecl
<< FunctionKind
<< RetValExp
->getSourceRange();
4067 // Preserve the initializers in the AST.
4068 RetValExp
= AllowRecovery
4069 ? CreateRecoveryExpr(ILE
->getLBraceLoc(),
4070 ILE
->getRBraceLoc(), ILE
->inits())
4073 } else if (!RetValExp
->isTypeDependent()) {
4074 // C99 6.8.6.4p1 (ext_ since GCC warns)
4075 unsigned D
= diag::ext_return_has_expr
;
4076 if (RetValExp
->getType()->isVoidType()) {
4077 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4078 if (isa
<CXXConstructorDecl
>(CurDecl
) ||
4079 isa
<CXXDestructorDecl
>(CurDecl
))
4080 D
= diag::err_ctor_dtor_returns_void
;
4082 D
= diag::ext_return_has_void_expr
;
4085 ExprResult Result
= RetValExp
;
4086 Result
= IgnoredValueConversions(Result
.get());
4087 if (Result
.isInvalid())
4089 RetValExp
= Result
.get();
4090 RetValExp
= ImpCastExprToType(RetValExp
,
4091 Context
.VoidTy
, CK_ToVoid
).get();
4093 // return of void in constructor/destructor is illegal in C++.
4094 if (D
== diag::err_ctor_dtor_returns_void
) {
4095 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4096 Diag(ReturnLoc
, D
) << CurDecl
<< isa
<CXXDestructorDecl
>(CurDecl
)
4097 << RetValExp
->getSourceRange();
4099 // return (some void expression); is legal in C++.
4100 else if (D
!= diag::ext_return_has_void_expr
||
4101 !getLangOpts().CPlusPlus
) {
4102 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4104 int FunctionKind
= 0;
4105 if (isa
<ObjCMethodDecl
>(CurDecl
))
4107 else if (isa
<CXXConstructorDecl
>(CurDecl
))
4109 else if (isa
<CXXDestructorDecl
>(CurDecl
))
4113 << CurDecl
<< FunctionKind
<< RetValExp
->getSourceRange();
4119 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4122 RetValExp
= ER
.get();
4126 Result
= ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
4127 /* NRVOCandidate=*/nullptr);
4128 } else if (!RetValExp
&& !HasDependentReturnType
) {
4129 FunctionDecl
*FD
= getCurFunctionDecl();
4131 if ((FD
&& FD
->isInvalidDecl()) || FnRetType
->containsErrors()) {
4132 // The intended return type might have been "void", so don't warn.
4133 } else if (getLangOpts().CPlusPlus11
&& FD
&& FD
->isConstexpr()) {
4134 // C++11 [stmt.return]p2
4135 Diag(ReturnLoc
, diag::err_constexpr_return_missing_expr
)
4136 << FD
<< FD
->isConsteval();
4137 FD
->setInvalidDecl();
4139 // C99 6.8.6.4p1 (ext_ since GCC warns)
4141 unsigned DiagID
= getLangOpts().C99
? diag::ext_return_missing_expr
4142 : diag::warn_return_missing_expr
;
4143 // Note that at this point one of getCurFunctionDecl() or
4144 // getCurMethodDecl() must be non-null (see above).
4145 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4146 "Not in a FunctionDecl or ObjCMethodDecl?");
4147 bool IsMethod
= FD
== nullptr;
4148 const NamedDecl
*ND
=
4149 IsMethod
? cast
<NamedDecl
>(getCurMethodDecl()) : cast
<NamedDecl
>(FD
);
4150 Diag(ReturnLoc
, DiagID
) << ND
<< IsMethod
;
4153 Result
= ReturnStmt::Create(Context
, ReturnLoc
, /* RetExpr=*/nullptr,
4154 /* NRVOCandidate=*/nullptr);
4156 assert(RetValExp
|| HasDependentReturnType
);
4157 QualType RetType
= RelatedRetType
.isNull() ? FnRetType
: RelatedRetType
;
4159 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4160 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4163 // In C++ the return statement is handled via a copy initialization,
4164 // the C version of which boils down to CheckSingleAssignmentConstraints.
4165 if (!HasDependentReturnType
&& !RetValExp
->isTypeDependent()) {
4166 // we have a non-void function with an expression, continue checking
4167 InitializedEntity Entity
=
4168 InitializedEntity::InitializeResult(ReturnLoc
, RetType
);
4169 ExprResult Res
= PerformMoveOrCopyInitialization(
4170 Entity
, NRInfo
, RetValExp
, SupressSimplerImplicitMoves
);
4171 if (Res
.isInvalid() && AllowRecovery
)
4172 Res
= CreateRecoveryExpr(RetValExp
->getBeginLoc(),
4173 RetValExp
->getEndLoc(), RetValExp
, RetType
);
4174 if (Res
.isInvalid()) {
4175 // FIXME: Clean up temporaries here anyway?
4178 RetValExp
= Res
.getAs
<Expr
>();
4180 // If we have a related result type, we need to implicitly
4181 // convert back to the formal result type. We can't pretend to
4182 // initialize the result again --- we might end double-retaining
4183 // --- so instead we initialize a notional temporary.
4184 if (!RelatedRetType
.isNull()) {
4185 Entity
= InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
4187 Res
= PerformCopyInitialization(Entity
, ReturnLoc
, RetValExp
);
4188 if (Res
.isInvalid()) {
4189 // FIXME: Clean up temporaries here anyway?
4192 RetValExp
= Res
.getAs
<Expr
>();
4195 CheckReturnValExpr(RetValExp
, FnRetType
, ReturnLoc
, isObjCMethod
, Attrs
,
4196 getCurFunctionDecl());
4201 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4204 RetValExp
= ER
.get();
4206 Result
= ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
, NRVOCandidate
);
4209 // If we need to check for the named return value optimization, save the
4210 // return statement in our scope for later processing.
4211 if (Result
->getNRVOCandidate())
4212 FunctionScopes
.back()->Returns
.push_back(Result
);
4214 if (FunctionScopes
.back()->FirstReturnLoc
.isInvalid())
4215 FunctionScopes
.back()->FirstReturnLoc
= ReturnLoc
;
4221 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc
,
4222 SourceLocation RParen
, Decl
*Parm
,
4224 VarDecl
*Var
= cast_or_null
<VarDecl
>(Parm
);
4225 if (Var
&& Var
->isInvalidDecl())
4228 return new (Context
) ObjCAtCatchStmt(AtLoc
, RParen
, Var
, Body
);
4232 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc
, Stmt
*Body
) {
4233 return new (Context
) ObjCAtFinallyStmt(AtLoc
, Body
);
4237 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc
, Stmt
*Try
,
4238 MultiStmtArg CatchStmts
, Stmt
*Finally
) {
4239 if (!getLangOpts().ObjCExceptions
)
4240 Diag(AtLoc
, diag::err_objc_exceptions_disabled
) << "@try";
4242 // Objective-C try is incompatible with SEH __try.
4243 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4244 if (FSI
->FirstSEHTryLoc
.isValid()) {
4245 Diag(AtLoc
, diag::err_mixing_cxx_try_seh_try
) << 1;
4246 Diag(FSI
->FirstSEHTryLoc
, diag::note_conflicting_try_here
) << "'__try'";
4249 FSI
->setHasObjCTry(AtLoc
);
4250 unsigned NumCatchStmts
= CatchStmts
.size();
4251 return ObjCAtTryStmt::Create(Context
, AtLoc
, Try
, CatchStmts
.data(),
4252 NumCatchStmts
, Finally
);
4255 StmtResult
Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
) {
4257 ExprResult Result
= DefaultLvalueConversion(Throw
);
4258 if (Result
.isInvalid())
4261 Result
= ActOnFinishFullExpr(Result
.get(), /*DiscardedValue*/ false);
4262 if (Result
.isInvalid())
4264 Throw
= Result
.get();
4266 QualType ThrowType
= Throw
->getType();
4267 // Make sure the expression type is an ObjC pointer or "void *".
4268 if (!ThrowType
->isDependentType() &&
4269 !ThrowType
->isObjCObjectPointerType()) {
4270 const PointerType
*PT
= ThrowType
->getAs
<PointerType
>();
4271 if (!PT
|| !PT
->getPointeeType()->isVoidType())
4272 return StmtError(Diag(AtLoc
, diag::err_objc_throw_expects_object
)
4273 << Throw
->getType() << Throw
->getSourceRange());
4277 return new (Context
) ObjCAtThrowStmt(AtLoc
, Throw
);
4281 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
,
4283 if (!getLangOpts().ObjCExceptions
)
4284 Diag(AtLoc
, diag::err_objc_exceptions_disabled
) << "@throw";
4287 // @throw without an expression designates a rethrow (which must occur
4288 // in the context of an @catch clause).
4289 Scope
*AtCatchParent
= CurScope
;
4290 while (AtCatchParent
&& !AtCatchParent
->isAtCatchScope())
4291 AtCatchParent
= AtCatchParent
->getParent();
4293 return StmtError(Diag(AtLoc
, diag::err_rethrow_used_outside_catch
));
4295 return BuildObjCAtThrowStmt(AtLoc
, Throw
);
4299 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc
, Expr
*operand
) {
4300 ExprResult result
= DefaultLvalueConversion(operand
);
4301 if (result
.isInvalid())
4303 operand
= result
.get();
4305 // Make sure the expression type is an ObjC pointer or "void *".
4306 QualType type
= operand
->getType();
4307 if (!type
->isDependentType() &&
4308 !type
->isObjCObjectPointerType()) {
4309 const PointerType
*pointerType
= type
->getAs
<PointerType
>();
4310 if (!pointerType
|| !pointerType
->getPointeeType()->isVoidType()) {
4311 if (getLangOpts().CPlusPlus
) {
4312 if (RequireCompleteType(atLoc
, type
,
4313 diag::err_incomplete_receiver_type
))
4314 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4315 << type
<< operand
->getSourceRange();
4317 ExprResult result
= PerformContextuallyConvertToObjCPointer(operand
);
4318 if (result
.isInvalid())
4320 if (!result
.isUsable())
4321 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4322 << type
<< operand
->getSourceRange();
4324 operand
= result
.get();
4326 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4327 << type
<< operand
->getSourceRange();
4332 // The operand to @synchronized is a full-expression.
4333 return ActOnFinishFullExpr(operand
, /*DiscardedValue*/ false);
4337 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc
, Expr
*SyncExpr
,
4339 // We can't jump into or indirect-jump out of a @synchronized block.
4340 setFunctionHasBranchProtectedScope();
4341 return new (Context
) ObjCAtSynchronizedStmt(AtLoc
, SyncExpr
, SyncBody
);
4344 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
4345 /// and creates a proper catch handler from them.
4347 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc
, Decl
*ExDecl
,
4348 Stmt
*HandlerBlock
) {
4349 // There's nothing to test that ActOnExceptionDecl didn't already test.
4350 return new (Context
)
4351 CXXCatchStmt(CatchLoc
, cast_or_null
<VarDecl
>(ExDecl
), HandlerBlock
);
4355 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc
, Stmt
*Body
) {
4356 setFunctionHasBranchProtectedScope();
4357 return new (Context
) ObjCAutoreleasePoolStmt(AtLoc
, Body
);
4361 class CatchHandlerType
{
4363 unsigned IsPointer
: 1;
4365 // This is a special constructor to be used only with DenseMapInfo's
4366 // getEmptyKey() and getTombstoneKey() functions.
4367 friend struct llvm::DenseMapInfo
<CatchHandlerType
>;
4368 enum Unique
{ ForDenseMap
};
4369 CatchHandlerType(QualType QT
, Unique
) : QT(QT
), IsPointer(false) {}
4372 /// Used when creating a CatchHandlerType from a handler type; will determine
4373 /// whether the type is a pointer or reference and will strip off the top
4374 /// level pointer and cv-qualifiers.
4375 CatchHandlerType(QualType Q
) : QT(Q
), IsPointer(false) {
4376 if (QT
->isPointerType())
4379 QT
= QT
.getUnqualifiedType();
4380 if (IsPointer
|| QT
->isReferenceType())
4381 QT
= QT
->getPointeeType();
4384 /// Used when creating a CatchHandlerType from a base class type; pretends the
4385 /// type passed in had the pointer qualifier, does not need to get an
4386 /// unqualified type.
4387 CatchHandlerType(QualType QT
, bool IsPointer
)
4388 : QT(QT
), IsPointer(IsPointer
) {}
4390 QualType
underlying() const { return QT
; }
4391 bool isPointer() const { return IsPointer
; }
4393 friend bool operator==(const CatchHandlerType
&LHS
,
4394 const CatchHandlerType
&RHS
) {
4395 // If the pointer qualification does not match, we can return early.
4396 if (LHS
.IsPointer
!= RHS
.IsPointer
)
4398 // Otherwise, check the underlying type without cv-qualifiers.
4399 return LHS
.QT
== RHS
.QT
;
4405 template <> struct DenseMapInfo
<CatchHandlerType
> {
4406 static CatchHandlerType
getEmptyKey() {
4407 return CatchHandlerType(DenseMapInfo
<QualType
>::getEmptyKey(),
4408 CatchHandlerType::ForDenseMap
);
4411 static CatchHandlerType
getTombstoneKey() {
4412 return CatchHandlerType(DenseMapInfo
<QualType
>::getTombstoneKey(),
4413 CatchHandlerType::ForDenseMap
);
4416 static unsigned getHashValue(const CatchHandlerType
&Base
) {
4417 return DenseMapInfo
<QualType
>::getHashValue(Base
.underlying());
4420 static bool isEqual(const CatchHandlerType
&LHS
,
4421 const CatchHandlerType
&RHS
) {
4428 class CatchTypePublicBases
{
4429 const llvm::DenseMap
<QualType
, CXXCatchStmt
*> &TypesToCheck
;
4431 CXXCatchStmt
*FoundHandler
;
4432 QualType FoundHandlerType
;
4433 QualType TestAgainstType
;
4436 CatchTypePublicBases(const llvm::DenseMap
<QualType
, CXXCatchStmt
*> &T
,
4438 : TypesToCheck(T
), FoundHandler(nullptr), TestAgainstType(QT
) {}
4440 CXXCatchStmt
*getFoundHandler() const { return FoundHandler
; }
4441 QualType
getFoundHandlerType() const { return FoundHandlerType
; }
4443 bool operator()(const CXXBaseSpecifier
*S
, CXXBasePath
&) {
4444 if (S
->getAccessSpecifier() == AccessSpecifier::AS_public
) {
4445 QualType Check
= S
->getType().getCanonicalType();
4446 const auto &M
= TypesToCheck
;
4447 auto I
= M
.find(Check
);
4449 // We're pretty sure we found what we need to find. However, we still
4450 // need to make sure that we properly compare for pointers and
4451 // references, to handle cases like:
4453 // } catch (Base *b) {
4454 // } catch (Derived &d) {
4457 // where there is a qualification mismatch that disqualifies this
4458 // handler as a potential problem.
4459 if (I
->second
->getCaughtType()->isPointerType() ==
4460 TestAgainstType
->isPointerType()) {
4461 FoundHandler
= I
->second
;
4462 FoundHandlerType
= Check
;
4472 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4473 /// handlers and creates a try statement from them.
4474 StmtResult
Sema::ActOnCXXTryBlock(SourceLocation TryLoc
, Stmt
*TryBlock
,
4475 ArrayRef
<Stmt
*> Handlers
) {
4476 const llvm::Triple
&T
= Context
.getTargetInfo().getTriple();
4477 const bool IsOpenMPGPUTarget
=
4478 getLangOpts().OpenMPIsTargetDevice
&& (T
.isNVPTX() || T
.isAMDGCN());
4479 // Don't report an error if 'try' is used in system headers or in an OpenMP
4480 // target region compiled for a GPU architecture.
4481 if (!IsOpenMPGPUTarget
&& !getLangOpts().CXXExceptions
&&
4482 !getSourceManager().isInSystemHeader(TryLoc
) && !getLangOpts().CUDA
) {
4483 // Delay error emission for the OpenMP device code.
4484 targetDiag(TryLoc
, diag::err_exceptions_disabled
) << "try";
4487 // In OpenMP target regions, we assume that catch is never reached on GPU
4489 if (IsOpenMPGPUTarget
)
4490 targetDiag(TryLoc
, diag::warn_try_not_valid_on_target
) << T
.str();
4492 // Exceptions aren't allowed in CUDA device code.
4493 if (getLangOpts().CUDA
)
4494 CUDADiagIfDeviceCode(TryLoc
, diag::err_cuda_device_exceptions
)
4495 << "try" << CurrentCUDATarget();
4497 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4498 Diag(TryLoc
, diag::err_omp_simd_region_cannot_use_stmt
) << "try";
4500 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4502 // C++ try is incompatible with SEH __try.
4503 if (!getLangOpts().Borland
&& FSI
->FirstSEHTryLoc
.isValid()) {
4504 Diag(TryLoc
, diag::err_mixing_cxx_try_seh_try
) << 0;
4505 Diag(FSI
->FirstSEHTryLoc
, diag::note_conflicting_try_here
) << "'__try'";
4508 const unsigned NumHandlers
= Handlers
.size();
4509 assert(!Handlers
.empty() &&
4510 "The parser shouldn't call this if there are no handlers.");
4512 llvm::DenseMap
<QualType
, CXXCatchStmt
*> HandledBaseTypes
;
4513 llvm::DenseMap
<CatchHandlerType
, CXXCatchStmt
*> HandledTypes
;
4514 for (unsigned i
= 0; i
< NumHandlers
; ++i
) {
4515 CXXCatchStmt
*H
= cast
<CXXCatchStmt
>(Handlers
[i
]);
4517 // Diagnose when the handler is a catch-all handler, but it isn't the last
4518 // handler for the try block. [except.handle]p5. Also, skip exception
4519 // declarations that are invalid, since we can't usefully report on them.
4520 if (!H
->getExceptionDecl()) {
4521 if (i
< NumHandlers
- 1)
4522 return StmtError(Diag(H
->getBeginLoc(), diag::err_early_catch_all
));
4524 } else if (H
->getExceptionDecl()->isInvalidDecl())
4527 // Walk the type hierarchy to diagnose when this type has already been
4528 // handled (duplication), or cannot be handled (derivation inversion). We
4529 // ignore top-level cv-qualifiers, per [except.handle]p3
4530 CatchHandlerType HandlerCHT
= H
->getCaughtType().getCanonicalType();
4532 // We can ignore whether the type is a reference or a pointer; we need the
4533 // underlying declaration type in order to get at the underlying record
4534 // decl, if there is one.
4535 QualType Underlying
= HandlerCHT
.underlying();
4536 if (auto *RD
= Underlying
->getAsCXXRecordDecl()) {
4537 if (!RD
->hasDefinition())
4539 // Check that none of the public, unambiguous base classes are in the
4540 // map ([except.handle]p1). Give the base classes the same pointer
4541 // qualification as the original type we are basing off of. This allows
4542 // comparison against the handler type using the same top-level pointer
4543 // as the original type.
4545 Paths
.setOrigin(RD
);
4546 CatchTypePublicBases
CTPB(HandledBaseTypes
,
4547 H
->getCaughtType().getCanonicalType());
4548 if (RD
->lookupInBases(CTPB
, Paths
)) {
4549 const CXXCatchStmt
*Problem
= CTPB
.getFoundHandler();
4550 if (!Paths
.isAmbiguous(
4551 CanQualType::CreateUnsafe(CTPB
.getFoundHandlerType()))) {
4552 Diag(H
->getExceptionDecl()->getTypeSpecStartLoc(),
4553 diag::warn_exception_caught_by_earlier_handler
)
4554 << H
->getCaughtType();
4555 Diag(Problem
->getExceptionDecl()->getTypeSpecStartLoc(),
4556 diag::note_previous_exception_handler
)
4557 << Problem
->getCaughtType();
4560 // Strip the qualifiers here because we're going to be comparing this
4561 // type to the base type specifiers of a class, which are ignored in a
4562 // base specifier per [class.derived.general]p2.
4563 HandledBaseTypes
[Underlying
.getUnqualifiedType()] = H
;
4566 // Add the type the list of ones we have handled; diagnose if we've already
4568 auto R
= HandledTypes
.insert(
4569 std::make_pair(H
->getCaughtType().getCanonicalType(), H
));
4571 const CXXCatchStmt
*Problem
= R
.first
->second
;
4572 Diag(H
->getExceptionDecl()->getTypeSpecStartLoc(),
4573 diag::warn_exception_caught_by_earlier_handler
)
4574 << H
->getCaughtType();
4575 Diag(Problem
->getExceptionDecl()->getTypeSpecStartLoc(),
4576 diag::note_previous_exception_handler
)
4577 << Problem
->getCaughtType();
4581 FSI
->setHasCXXTry(TryLoc
);
4583 return CXXTryStmt::Create(Context
, TryLoc
, cast
<CompoundStmt
>(TryBlock
),
4587 StmtResult
Sema::ActOnSEHTryBlock(bool IsCXXTry
, SourceLocation TryLoc
,
4588 Stmt
*TryBlock
, Stmt
*Handler
) {
4589 assert(TryBlock
&& Handler
);
4591 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4593 // SEH __try is incompatible with C++ try. Borland appears to support this,
4595 if (!getLangOpts().Borland
) {
4596 if (FSI
->FirstCXXOrObjCTryLoc
.isValid()) {
4597 Diag(TryLoc
, diag::err_mixing_cxx_try_seh_try
) << FSI
->FirstTryType
;
4598 Diag(FSI
->FirstCXXOrObjCTryLoc
, diag::note_conflicting_try_here
)
4599 << (FSI
->FirstTryType
== sema::FunctionScopeInfo::TryLocIsCXX
4605 FSI
->setHasSEHTry(TryLoc
);
4607 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4608 // track if they use SEH.
4609 DeclContext
*DC
= CurContext
;
4610 while (DC
&& !DC
->isFunctionOrMethod())
4611 DC
= DC
->getParent();
4612 FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(DC
);
4614 FD
->setUsesSEHTry(true);
4616 Diag(TryLoc
, diag::err_seh_try_outside_functions
);
4618 // Reject __try on unsupported targets.
4619 if (!Context
.getTargetInfo().isSEHTrySupported())
4620 Diag(TryLoc
, diag::err_seh_try_unsupported
);
4622 return SEHTryStmt::Create(Context
, IsCXXTry
, TryLoc
, TryBlock
, Handler
);
4625 StmtResult
Sema::ActOnSEHExceptBlock(SourceLocation Loc
, Expr
*FilterExpr
,
4627 assert(FilterExpr
&& Block
);
4628 QualType FTy
= FilterExpr
->getType();
4629 if (!FTy
->isIntegerType() && !FTy
->isDependentType()) {
4631 Diag(FilterExpr
->getExprLoc(), diag::err_filter_expression_integral
)
4634 return SEHExceptStmt::Create(Context
, Loc
, FilterExpr
, Block
);
4637 void Sema::ActOnStartSEHFinallyBlock() {
4638 CurrentSEHFinally
.push_back(CurScope
);
4641 void Sema::ActOnAbortSEHFinallyBlock() {
4642 CurrentSEHFinally
.pop_back();
4645 StmtResult
Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc
, Stmt
*Block
) {
4647 CurrentSEHFinally
.pop_back();
4648 return SEHFinallyStmt::Create(Context
, Loc
, Block
);
4652 Sema::ActOnSEHLeaveStmt(SourceLocation Loc
, Scope
*CurScope
) {
4653 Scope
*SEHTryParent
= CurScope
;
4654 while (SEHTryParent
&& !SEHTryParent
->isSEHTryScope())
4655 SEHTryParent
= SEHTryParent
->getParent();
4657 return StmtError(Diag(Loc
, diag::err_ms___leave_not_in___try
));
4658 CheckJumpOutOfSEHFinally(*this, Loc
, *SEHTryParent
);
4660 return new (Context
) SEHLeaveStmt(Loc
);
4663 StmtResult
Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc
,
4665 NestedNameSpecifierLoc QualifierLoc
,
4666 DeclarationNameInfo NameInfo
,
4669 return new (Context
) MSDependentExistsStmt(KeywordLoc
, IsIfExists
,
4670 QualifierLoc
, NameInfo
,
4671 cast
<CompoundStmt
>(Nested
));
4675 StmtResult
Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc
,
4678 UnqualifiedId
&Name
,
4680 return BuildMSDependentExistsStmt(KeywordLoc
, IsIfExists
,
4681 SS
.getWithLocInContext(Context
),
4682 GetNameFromUnqualifiedId(Name
),
4687 Sema::CreateCapturedStmtRecordDecl(CapturedDecl
*&CD
, SourceLocation Loc
,
4688 unsigned NumParams
) {
4689 DeclContext
*DC
= CurContext
;
4690 while (!(DC
->isFunctionOrMethod() || DC
->isRecord() || DC
->isFileContext()))
4691 DC
= DC
->getParent();
4693 RecordDecl
*RD
= nullptr;
4694 if (getLangOpts().CPlusPlus
)
4695 RD
= CXXRecordDecl::Create(Context
, TTK_Struct
, DC
, Loc
, Loc
,
4698 RD
= RecordDecl::Create(Context
, TTK_Struct
, DC
, Loc
, Loc
, /*Id=*/nullptr);
4700 RD
->setCapturedRecord();
4703 RD
->startDefinition();
4705 assert(NumParams
> 0 && "CapturedStmt requires context parameter");
4706 CD
= CapturedDecl::Create(Context
, CurContext
, NumParams
);
4712 buildCapturedStmtCaptureList(Sema
&S
, CapturedRegionScopeInfo
*RSI
,
4713 SmallVectorImpl
<CapturedStmt::Capture
> &Captures
,
4714 SmallVectorImpl
<Expr
*> &CaptureInits
) {
4715 for (const sema::Capture
&Cap
: RSI
->Captures
) {
4716 if (Cap
.isInvalid())
4719 // Form the initializer for the capture.
4720 ExprResult Init
= S
.BuildCaptureInit(Cap
, Cap
.getLocation(),
4721 RSI
->CapRegionKind
== CR_OpenMP
);
4723 // FIXME: Bail out now if the capture is not used and the initializer has
4726 // Create a field for this capture.
4727 FieldDecl
*Field
= S
.BuildCaptureField(RSI
->TheRecordDecl
, Cap
);
4729 // Add the capture to our list of captures.
4730 if (Cap
.isThisCapture()) {
4731 Captures
.push_back(CapturedStmt::Capture(Cap
.getLocation(),
4732 CapturedStmt::VCK_This
));
4733 } else if (Cap
.isVLATypeCapture()) {
4735 CapturedStmt::Capture(Cap
.getLocation(), CapturedStmt::VCK_VLAType
));
4737 assert(Cap
.isVariableCapture() && "unknown kind of capture");
4739 if (S
.getLangOpts().OpenMP
&& RSI
->CapRegionKind
== CR_OpenMP
)
4740 S
.setOpenMPCaptureKind(Field
, Cap
.getVariable(), RSI
->OpenMPLevel
);
4742 Captures
.push_back(CapturedStmt::Capture(
4744 Cap
.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4745 : CapturedStmt::VCK_ByCopy
,
4746 cast
<VarDecl
>(Cap
.getVariable())));
4748 CaptureInits
.push_back(Init
.get());
4753 void Sema::ActOnCapturedRegionStart(SourceLocation Loc
, Scope
*CurScope
,
4754 CapturedRegionKind Kind
,
4755 unsigned NumParams
) {
4756 CapturedDecl
*CD
= nullptr;
4757 RecordDecl
*RD
= CreateCapturedStmtRecordDecl(CD
, Loc
, NumParams
);
4759 // Build the context parameter
4760 DeclContext
*DC
= CapturedDecl::castToDeclContext(CD
);
4761 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4762 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
));
4764 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4765 ImplicitParamDecl::CapturedContext
);
4768 CD
->setContextParam(0, Param
);
4770 // Enter the capturing scope for this captured region.
4771 PushCapturedRegionScope(CurScope
, CD
, RD
, Kind
);
4774 PushDeclContext(CurScope
, CD
);
4778 PushExpressionEvaluationContext(
4779 ExpressionEvaluationContext::PotentiallyEvaluated
);
4780 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
= false;
4783 void Sema::ActOnCapturedRegionStart(SourceLocation Loc
, Scope
*CurScope
,
4784 CapturedRegionKind Kind
,
4785 ArrayRef
<CapturedParamNameType
> Params
,
4786 unsigned OpenMPCaptureLevel
) {
4787 CapturedDecl
*CD
= nullptr;
4788 RecordDecl
*RD
= CreateCapturedStmtRecordDecl(CD
, Loc
, Params
.size());
4790 // Build the context parameter
4791 DeclContext
*DC
= CapturedDecl::castToDeclContext(CD
);
4792 bool ContextIsFound
= false;
4793 unsigned ParamNum
= 0;
4794 for (ArrayRef
<CapturedParamNameType
>::iterator I
= Params
.begin(),
4796 I
!= E
; ++I
, ++ParamNum
) {
4797 if (I
->second
.isNull()) {
4798 assert(!ContextIsFound
&&
4799 "null type has been found already for '__context' parameter");
4800 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4801 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
))
4805 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4806 ImplicitParamDecl::CapturedContext
);
4808 CD
->setContextParam(ParamNum
, Param
);
4809 ContextIsFound
= true;
4811 IdentifierInfo
*ParamName
= &Context
.Idents
.get(I
->first
);
4813 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, I
->second
,
4814 ImplicitParamDecl::CapturedContext
);
4816 CD
->setParam(ParamNum
, Param
);
4819 assert(ContextIsFound
&& "no null type for '__context' parameter");
4820 if (!ContextIsFound
) {
4821 // Add __context implicitly if it is not specified.
4822 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4823 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
));
4825 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4826 ImplicitParamDecl::CapturedContext
);
4828 CD
->setContextParam(ParamNum
, Param
);
4830 // Enter the capturing scope for this captured region.
4831 PushCapturedRegionScope(CurScope
, CD
, RD
, Kind
, OpenMPCaptureLevel
);
4834 PushDeclContext(CurScope
, CD
);
4838 PushExpressionEvaluationContext(
4839 ExpressionEvaluationContext::PotentiallyEvaluated
);
4842 void Sema::ActOnCapturedRegionError() {
4843 DiscardCleanupsInEvaluationContext();
4844 PopExpressionEvaluationContext();
4846 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo();
4847 CapturedRegionScopeInfo
*RSI
= cast
<CapturedRegionScopeInfo
>(ScopeRAII
.get());
4849 RecordDecl
*Record
= RSI
->TheRecordDecl
;
4850 Record
->setInvalidDecl();
4852 SmallVector
<Decl
*, 4> Fields(Record
->fields());
4853 ActOnFields(/*Scope=*/nullptr, Record
->getLocation(), Record
, Fields
,
4854 SourceLocation(), SourceLocation(), ParsedAttributesView());
4857 StmtResult
Sema::ActOnCapturedRegionEnd(Stmt
*S
) {
4858 // Leave the captured scope before we start creating captures in the
4860 DiscardCleanupsInEvaluationContext();
4861 PopExpressionEvaluationContext();
4863 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo();
4864 CapturedRegionScopeInfo
*RSI
= cast
<CapturedRegionScopeInfo
>(ScopeRAII
.get());
4866 SmallVector
<CapturedStmt::Capture
, 4> Captures
;
4867 SmallVector
<Expr
*, 4> CaptureInits
;
4868 if (buildCapturedStmtCaptureList(*this, RSI
, Captures
, CaptureInits
))
4871 CapturedDecl
*CD
= RSI
->TheCapturedDecl
;
4872 RecordDecl
*RD
= RSI
->TheRecordDecl
;
4874 CapturedStmt
*Res
= CapturedStmt::Create(
4875 getASTContext(), S
, static_cast<CapturedRegionKind
>(RSI
->CapRegionKind
),
4876 Captures
, CaptureInits
, CD
, RD
);
4878 CD
->setBody(Res
->getCapturedStmt());
4879 RD
->completeDefinition();