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 (!TheDefaultStmt
)
1331 Diag(SwitchLoc
, diag::warn_switch_default
);
1333 if (!HasDependentValue
) {
1334 // If we don't have a default statement, check whether the
1335 // condition is constant.
1336 llvm::APSInt ConstantCondValue
;
1337 bool HasConstantCond
= false;
1338 if (!TheDefaultStmt
) {
1339 Expr::EvalResult Result
;
1340 HasConstantCond
= CondExpr
->EvaluateAsInt(Result
, Context
,
1341 Expr::SE_AllowSideEffects
);
1342 if (Result
.Val
.isInt())
1343 ConstantCondValue
= Result
.Val
.getInt();
1344 assert(!HasConstantCond
||
1345 (ConstantCondValue
.getBitWidth() == CondWidth
&&
1346 ConstantCondValue
.isSigned() == CondIsSigned
));
1348 bool ShouldCheckConstantCond
= HasConstantCond
;
1350 // Sort all the scalar case values so we can easily detect duplicates.
1351 llvm::stable_sort(CaseVals
, CmpCaseVals
);
1353 if (!CaseVals
.empty()) {
1354 for (unsigned i
= 0, e
= CaseVals
.size(); i
!= e
; ++i
) {
1355 if (ShouldCheckConstantCond
&&
1356 CaseVals
[i
].first
== ConstantCondValue
)
1357 ShouldCheckConstantCond
= false;
1359 if (i
!= 0 && CaseVals
[i
].first
== CaseVals
[i
-1].first
) {
1360 // If we have a duplicate, report it.
1361 // First, determine if either case value has a name
1362 StringRef PrevString
, CurrString
;
1363 Expr
*PrevCase
= CaseVals
[i
-1].second
->getLHS()->IgnoreParenCasts();
1364 Expr
*CurrCase
= CaseVals
[i
].second
->getLHS()->IgnoreParenCasts();
1365 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(PrevCase
)) {
1366 PrevString
= DeclRef
->getDecl()->getName();
1368 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(CurrCase
)) {
1369 CurrString
= DeclRef
->getDecl()->getName();
1371 SmallString
<16> CaseValStr
;
1372 CaseVals
[i
-1].first
.toString(CaseValStr
);
1374 if (PrevString
== CurrString
)
1375 Diag(CaseVals
[i
].second
->getLHS()->getBeginLoc(),
1376 diag::err_duplicate_case
)
1377 << (PrevString
.empty() ? CaseValStr
.str() : PrevString
);
1379 Diag(CaseVals
[i
].second
->getLHS()->getBeginLoc(),
1380 diag::err_duplicate_case_differing_expr
)
1381 << (PrevString
.empty() ? CaseValStr
.str() : PrevString
)
1382 << (CurrString
.empty() ? CaseValStr
.str() : CurrString
)
1385 Diag(CaseVals
[i
- 1].second
->getLHS()->getBeginLoc(),
1386 diag::note_duplicate_case_prev
);
1387 // FIXME: We really want to remove the bogus case stmt from the
1388 // substmt, but we have no way to do this right now.
1389 CaseListIsErroneous
= true;
1394 // Detect duplicate case ranges, which usually don't exist at all in
1396 if (!CaseRanges
.empty()) {
1397 // Sort all the case ranges by their low value so we can easily detect
1398 // overlaps between ranges.
1399 llvm::stable_sort(CaseRanges
);
1401 // Scan the ranges, computing the high values and removing empty ranges.
1402 std::vector
<llvm::APSInt
> HiVals
;
1403 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
1404 llvm::APSInt
&LoVal
= CaseRanges
[i
].first
;
1405 CaseStmt
*CR
= CaseRanges
[i
].second
;
1406 Expr
*Hi
= CR
->getRHS();
1408 const Expr
*HiBeforePromotion
= Hi
;
1409 GetTypeBeforeIntegralPromotion(HiBeforePromotion
);
1410 llvm::APSInt HiVal
= HiBeforePromotion
->EvaluateKnownConstInt(Context
);
1412 // Check the unconverted value is within the range of possible values of
1413 // the switch expression.
1414 checkCaseValue(*this, Hi
->getBeginLoc(), HiVal
,
1415 CondWidthBeforePromotion
, CondIsSignedBeforePromotion
);
1417 // Convert the value to the same width/sign as the condition.
1418 AdjustAPSInt(HiVal
, CondWidth
, CondIsSigned
);
1420 // If the low value is bigger than the high value, the case is empty.
1421 if (LoVal
> HiVal
) {
1422 Diag(CR
->getLHS()->getBeginLoc(), diag::warn_case_empty_range
)
1423 << SourceRange(CR
->getLHS()->getBeginLoc(), Hi
->getEndLoc());
1424 CaseRanges
.erase(CaseRanges
.begin()+i
);
1430 if (ShouldCheckConstantCond
&&
1431 LoVal
<= ConstantCondValue
&&
1432 ConstantCondValue
<= HiVal
)
1433 ShouldCheckConstantCond
= false;
1435 HiVals
.push_back(HiVal
);
1438 // Rescan the ranges, looking for overlap with singleton values and other
1439 // ranges. Since the range list is sorted, we only need to compare case
1440 // ranges with their neighbors.
1441 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
1442 llvm::APSInt
&CRLo
= CaseRanges
[i
].first
;
1443 llvm::APSInt
&CRHi
= HiVals
[i
];
1444 CaseStmt
*CR
= CaseRanges
[i
].second
;
1446 // Check to see whether the case range overlaps with any
1448 CaseStmt
*OverlapStmt
= nullptr;
1449 llvm::APSInt
OverlapVal(32);
1451 // Find the smallest value >= the lower bound. If I is in the
1452 // case range, then we have overlap.
1453 CaseValsTy::iterator I
=
1454 llvm::lower_bound(CaseVals
, CRLo
, CaseCompareFunctor());
1455 if (I
!= CaseVals
.end() && I
->first
< CRHi
) {
1456 OverlapVal
= I
->first
; // Found overlap with scalar.
1457 OverlapStmt
= I
->second
;
1460 // Find the smallest value bigger than the upper bound.
1461 I
= std::upper_bound(I
, CaseVals
.end(), CRHi
, CaseCompareFunctor());
1462 if (I
!= CaseVals
.begin() && (I
-1)->first
>= CRLo
) {
1463 OverlapVal
= (I
-1)->first
; // Found overlap with scalar.
1464 OverlapStmt
= (I
-1)->second
;
1467 // Check to see if this case stmt overlaps with the subsequent
1469 if (i
&& CRLo
<= HiVals
[i
-1]) {
1470 OverlapVal
= HiVals
[i
-1]; // Found overlap with range.
1471 OverlapStmt
= CaseRanges
[i
-1].second
;
1475 // If we have a duplicate, report it.
1476 Diag(CR
->getLHS()->getBeginLoc(), diag::err_duplicate_case
)
1477 << toString(OverlapVal
, 10);
1478 Diag(OverlapStmt
->getLHS()->getBeginLoc(),
1479 diag::note_duplicate_case_prev
);
1480 // FIXME: We really want to remove the bogus case stmt from the
1481 // substmt, but we have no way to do this right now.
1482 CaseListIsErroneous
= true;
1487 // Complain if we have a constant condition and we didn't find a match.
1488 if (!CaseListIsErroneous
&& !CaseListIsIncomplete
&&
1489 ShouldCheckConstantCond
) {
1490 // TODO: it would be nice if we printed enums as enums, chars as
1492 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case_for_condition
)
1493 << toString(ConstantCondValue
, 10)
1494 << CondExpr
->getSourceRange();
1497 // Check to see if switch is over an Enum and handles all of its
1498 // values. We only issue a warning if there is not 'default:', but
1499 // we still do the analysis to preserve this information in the AST
1500 // (which can be used by flow-based analyes).
1502 const EnumType
*ET
= CondTypeBeforePromotion
->getAs
<EnumType
>();
1504 // If switch has default case, then ignore it.
1505 if (!CaseListIsErroneous
&& !CaseListIsIncomplete
&& !HasConstantCond
&&
1506 ET
&& ET
->getDecl()->isCompleteDefinition() &&
1507 !ET
->getDecl()->enumerators().empty()) {
1508 const EnumDecl
*ED
= ET
->getDecl();
1509 EnumValsTy EnumVals
;
1511 // Gather all enum values, set their type and sort them,
1512 // allowing easier comparison with CaseVals.
1513 for (auto *EDI
: ED
->enumerators()) {
1514 llvm::APSInt Val
= EDI
->getInitVal();
1515 AdjustAPSInt(Val
, CondWidth
, CondIsSigned
);
1516 EnumVals
.push_back(std::make_pair(Val
, EDI
));
1518 llvm::stable_sort(EnumVals
, CmpEnumVals
);
1519 auto EI
= EnumVals
.begin(), EIEnd
=
1520 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
1522 // See which case values aren't in enum.
1523 for (CaseValsTy::const_iterator CI
= CaseVals
.begin();
1524 CI
!= CaseVals
.end(); CI
++) {
1525 Expr
*CaseExpr
= CI
->second
->getLHS();
1526 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1528 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1529 << CondTypeBeforePromotion
;
1532 // See which of case ranges aren't in enum
1533 EI
= EnumVals
.begin();
1534 for (CaseRangesTy::const_iterator RI
= CaseRanges
.begin();
1535 RI
!= CaseRanges
.end(); RI
++) {
1536 Expr
*CaseExpr
= RI
->second
->getLHS();
1537 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1539 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1540 << CondTypeBeforePromotion
;
1543 RI
->second
->getRHS()->EvaluateKnownConstInt(Context
);
1544 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
1546 CaseExpr
= RI
->second
->getRHS();
1547 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1549 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1550 << CondTypeBeforePromotion
;
1553 // Check which enum vals aren't in switch
1554 auto CI
= CaseVals
.begin();
1555 auto RI
= CaseRanges
.begin();
1556 bool hasCasesNotInSwitch
= false;
1558 SmallVector
<DeclarationName
,8> UnhandledNames
;
1560 for (EI
= EnumVals
.begin(); EI
!= EIEnd
; EI
++) {
1561 // Don't warn about omitted unavailable EnumConstantDecls.
1562 switch (EI
->second
->getAvailability()) {
1564 // Omitting a deprecated constant is ok; it should never materialize.
1565 case AR_Unavailable
:
1568 case AR_NotYetIntroduced
:
1569 // Partially available enum constants should be present. Note that we
1570 // suppress -Wunguarded-availability diagnostics for such uses.
1575 if (EI
->second
->hasAttr
<UnusedAttr
>())
1578 // Drop unneeded case values
1579 while (CI
!= CaseVals
.end() && CI
->first
< EI
->first
)
1582 if (CI
!= CaseVals
.end() && CI
->first
== EI
->first
)
1585 // Drop unneeded case ranges
1586 for (; RI
!= CaseRanges
.end(); RI
++) {
1588 RI
->second
->getRHS()->EvaluateKnownConstInt(Context
);
1589 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
1590 if (EI
->first
<= Hi
)
1594 if (RI
== CaseRanges
.end() || EI
->first
< RI
->first
) {
1595 hasCasesNotInSwitch
= true;
1596 UnhandledNames
.push_back(EI
->second
->getDeclName());
1600 if (TheDefaultStmt
&& UnhandledNames
.empty() && ED
->isClosedNonFlag())
1601 Diag(TheDefaultStmt
->getDefaultLoc(), diag::warn_unreachable_default
);
1603 // Produce a nice diagnostic if multiple values aren't handled.
1604 if (!UnhandledNames
.empty()) {
1605 auto DB
= Diag(CondExpr
->getExprLoc(), TheDefaultStmt
1606 ? diag::warn_def_missing_case
1607 : diag::warn_missing_case
)
1608 << CondExpr
->getSourceRange() << (int)UnhandledNames
.size();
1610 for (size_t I
= 0, E
= std::min(UnhandledNames
.size(), (size_t)3);
1612 DB
<< UnhandledNames
[I
];
1615 if (!hasCasesNotInSwitch
)
1616 SS
->setAllEnumCasesCovered();
1621 DiagnoseEmptyStmtBody(CondExpr
->getEndLoc(), BodyStmt
,
1622 diag::warn_empty_switch_body
);
1624 // FIXME: If the case list was broken is some way, we don't have a good system
1625 // to patch it up. Instead, just return the whole substmt as broken.
1626 if (CaseListIsErroneous
)
1633 Sema::DiagnoseAssignmentEnum(QualType DstType
, QualType SrcType
,
1635 if (Diags
.isIgnored(diag::warn_not_in_enum_assignment
, SrcExpr
->getExprLoc()))
1638 if (const EnumType
*ET
= DstType
->getAs
<EnumType
>())
1639 if (!Context
.hasSameUnqualifiedType(SrcType
, DstType
) &&
1640 SrcType
->isIntegerType()) {
1641 if (!SrcExpr
->isTypeDependent() && !SrcExpr
->isValueDependent() &&
1642 SrcExpr
->isIntegerConstantExpr(Context
)) {
1643 // Get the bitwidth of the enum value before promotions.
1644 unsigned DstWidth
= Context
.getIntWidth(DstType
);
1645 bool DstIsSigned
= DstType
->isSignedIntegerOrEnumerationType();
1647 llvm::APSInt RhsVal
= SrcExpr
->EvaluateKnownConstInt(Context
);
1648 AdjustAPSInt(RhsVal
, DstWidth
, DstIsSigned
);
1649 const EnumDecl
*ED
= ET
->getDecl();
1651 if (!ED
->isClosed())
1654 if (ED
->hasAttr
<FlagEnumAttr
>()) {
1655 if (!IsValueInFlagEnum(ED
, RhsVal
, true))
1656 Diag(SrcExpr
->getExprLoc(), diag::warn_not_in_enum_assignment
)
1657 << DstType
.getUnqualifiedType();
1659 typedef SmallVector
<std::pair
<llvm::APSInt
, EnumConstantDecl
*>, 64>
1661 EnumValsTy EnumVals
;
1663 // Gather all enum values, set their type and sort them,
1664 // allowing easier comparison with rhs constant.
1665 for (auto *EDI
: ED
->enumerators()) {
1666 llvm::APSInt Val
= EDI
->getInitVal();
1667 AdjustAPSInt(Val
, DstWidth
, DstIsSigned
);
1668 EnumVals
.push_back(std::make_pair(Val
, EDI
));
1670 if (EnumVals
.empty())
1672 llvm::stable_sort(EnumVals
, CmpEnumVals
);
1673 EnumValsTy::iterator EIend
=
1674 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
1676 // See which values aren't in the enum.
1677 EnumValsTy::const_iterator EI
= EnumVals
.begin();
1678 while (EI
!= EIend
&& EI
->first
< RhsVal
)
1680 if (EI
== EIend
|| EI
->first
!= RhsVal
) {
1681 Diag(SrcExpr
->getExprLoc(), diag::warn_not_in_enum_assignment
)
1682 << DstType
.getUnqualifiedType();
1689 StmtResult
Sema::ActOnWhileStmt(SourceLocation WhileLoc
,
1690 SourceLocation LParenLoc
, ConditionResult Cond
,
1691 SourceLocation RParenLoc
, Stmt
*Body
) {
1692 if (Cond
.isInvalid())
1695 auto CondVal
= Cond
.get();
1696 CheckBreakContinueBinding(CondVal
.second
);
1698 if (CondVal
.second
&&
1699 !Diags
.isIgnored(diag::warn_comma_operator
, CondVal
.second
->getExprLoc()))
1700 CommaVisitor(*this).Visit(CondVal
.second
);
1702 if (isa
<NullStmt
>(Body
))
1703 getCurCompoundScope().setHasEmptyLoopBodies();
1705 return WhileStmt::Create(Context
, CondVal
.first
, CondVal
.second
, Body
,
1706 WhileLoc
, LParenLoc
, RParenLoc
);
1710 Sema::ActOnDoStmt(SourceLocation DoLoc
, Stmt
*Body
,
1711 SourceLocation WhileLoc
, SourceLocation CondLParen
,
1712 Expr
*Cond
, SourceLocation CondRParen
) {
1713 assert(Cond
&& "ActOnDoStmt(): missing expression");
1715 CheckBreakContinueBinding(Cond
);
1716 ExprResult CondResult
= CheckBooleanCondition(DoLoc
, Cond
);
1717 if (CondResult
.isInvalid())
1719 Cond
= CondResult
.get();
1721 CondResult
= ActOnFinishFullExpr(Cond
, DoLoc
, /*DiscardedValue*/ false);
1722 if (CondResult
.isInvalid())
1724 Cond
= CondResult
.get();
1726 // Only call the CommaVisitor for C89 due to differences in scope flags.
1727 if (Cond
&& !getLangOpts().C99
&& !getLangOpts().CPlusPlus
&&
1728 !Diags
.isIgnored(diag::warn_comma_operator
, Cond
->getExprLoc()))
1729 CommaVisitor(*this).Visit(Cond
);
1731 return new (Context
) DoStmt(Body
, Cond
, DoLoc
, WhileLoc
, CondRParen
);
1735 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1736 using DeclSetVector
= llvm::SmallSetVector
<VarDecl
*, 8>;
1738 // This visitor will traverse a conditional statement and store all
1739 // the evaluated decls into a vector. Simple is set to true if none
1740 // of the excluded constructs are used.
1741 class DeclExtractor
: public EvaluatedExprVisitor
<DeclExtractor
> {
1742 DeclSetVector
&Decls
;
1743 SmallVectorImpl
<SourceRange
> &Ranges
;
1746 typedef EvaluatedExprVisitor
<DeclExtractor
> Inherited
;
1748 DeclExtractor(Sema
&S
, DeclSetVector
&Decls
,
1749 SmallVectorImpl
<SourceRange
> &Ranges
) :
1750 Inherited(S
.Context
),
1755 bool isSimple() { return Simple
; }
1757 // Replaces the method in EvaluatedExprVisitor.
1758 void VisitMemberExpr(MemberExpr
* E
) {
1762 // Any Stmt not explicitly listed will cause the condition to be marked
1764 void VisitStmt(Stmt
*S
) { Simple
= false; }
1766 void VisitBinaryOperator(BinaryOperator
*E
) {
1771 void VisitCastExpr(CastExpr
*E
) {
1772 Visit(E
->getSubExpr());
1775 void VisitUnaryOperator(UnaryOperator
*E
) {
1776 // Skip checking conditionals with derefernces.
1777 if (E
->getOpcode() == UO_Deref
)
1780 Visit(E
->getSubExpr());
1783 void VisitConditionalOperator(ConditionalOperator
*E
) {
1784 Visit(E
->getCond());
1785 Visit(E
->getTrueExpr());
1786 Visit(E
->getFalseExpr());
1789 void VisitParenExpr(ParenExpr
*E
) {
1790 Visit(E
->getSubExpr());
1793 void VisitBinaryConditionalOperator(BinaryConditionalOperator
*E
) {
1794 Visit(E
->getOpaqueValue()->getSourceExpr());
1795 Visit(E
->getFalseExpr());
1798 void VisitIntegerLiteral(IntegerLiteral
*E
) { }
1799 void VisitFloatingLiteral(FloatingLiteral
*E
) { }
1800 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr
*E
) { }
1801 void VisitCharacterLiteral(CharacterLiteral
*E
) { }
1802 void VisitGNUNullExpr(GNUNullExpr
*E
) { }
1803 void VisitImaginaryLiteral(ImaginaryLiteral
*E
) { }
1805 void VisitDeclRefExpr(DeclRefExpr
*E
) {
1806 VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl());
1808 // Don't allow unhandled Decl types.
1813 Ranges
.push_back(E
->getSourceRange());
1818 }; // end class DeclExtractor
1820 // DeclMatcher checks to see if the decls are used in a non-evaluated
1822 class DeclMatcher
: public EvaluatedExprVisitor
<DeclMatcher
> {
1823 DeclSetVector
&Decls
;
1827 typedef EvaluatedExprVisitor
<DeclMatcher
> Inherited
;
1829 DeclMatcher(Sema
&S
, DeclSetVector
&Decls
, Stmt
*Statement
) :
1830 Inherited(S
.Context
), Decls(Decls
), FoundDecl(false) {
1831 if (!Statement
) return;
1836 void VisitReturnStmt(ReturnStmt
*S
) {
1840 void VisitBreakStmt(BreakStmt
*S
) {
1844 void VisitGotoStmt(GotoStmt
*S
) {
1848 void VisitCastExpr(CastExpr
*E
) {
1849 if (E
->getCastKind() == CK_LValueToRValue
)
1850 CheckLValueToRValueCast(E
->getSubExpr());
1852 Visit(E
->getSubExpr());
1855 void CheckLValueToRValueCast(Expr
*E
) {
1856 E
= E
->IgnoreParenImpCasts();
1858 if (isa
<DeclRefExpr
>(E
)) {
1862 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
1863 Visit(CO
->getCond());
1864 CheckLValueToRValueCast(CO
->getTrueExpr());
1865 CheckLValueToRValueCast(CO
->getFalseExpr());
1869 if (BinaryConditionalOperator
*BCO
=
1870 dyn_cast
<BinaryConditionalOperator
>(E
)) {
1871 CheckLValueToRValueCast(BCO
->getOpaqueValue()->getSourceExpr());
1872 CheckLValueToRValueCast(BCO
->getFalseExpr());
1879 void VisitDeclRefExpr(DeclRefExpr
*E
) {
1880 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl()))
1881 if (Decls
.count(VD
))
1885 void VisitPseudoObjectExpr(PseudoObjectExpr
*POE
) {
1886 // Only need to visit the semantics for POE.
1887 // SyntaticForm doesn't really use the Decal.
1888 for (auto *S
: POE
->semantics()) {
1889 if (auto *OVE
= dyn_cast
<OpaqueValueExpr
>(S
))
1890 // Look past the OVE into the expression it binds.
1891 Visit(OVE
->getSourceExpr());
1897 bool FoundDeclInUse() { return FoundDecl
; }
1899 }; // end class DeclMatcher
1901 void CheckForLoopConditionalStatement(Sema
&S
, Expr
*Second
,
1902 Expr
*Third
, Stmt
*Body
) {
1903 // Condition is empty
1904 if (!Second
) return;
1906 if (S
.Diags
.isIgnored(diag::warn_variables_not_in_loop_body
,
1907 Second
->getBeginLoc()))
1910 PartialDiagnostic PDiag
= S
.PDiag(diag::warn_variables_not_in_loop_body
);
1911 DeclSetVector Decls
;
1912 SmallVector
<SourceRange
, 10> Ranges
;
1913 DeclExtractor
DE(S
, Decls
, Ranges
);
1916 // Don't analyze complex conditionals.
1917 if (!DE
.isSimple()) return;
1920 if (Decls
.size() == 0) return;
1922 // Don't warn on volatile, static, or global variables.
1923 for (auto *VD
: Decls
)
1924 if (VD
->getType().isVolatileQualified() || VD
->hasGlobalStorage())
1927 if (DeclMatcher(S
, Decls
, Second
).FoundDeclInUse() ||
1928 DeclMatcher(S
, Decls
, Third
).FoundDeclInUse() ||
1929 DeclMatcher(S
, Decls
, Body
).FoundDeclInUse())
1932 // Load decl names into diagnostic.
1933 if (Decls
.size() > 4) {
1936 PDiag
<< (unsigned)Decls
.size();
1937 for (auto *VD
: Decls
)
1938 PDiag
<< VD
->getDeclName();
1941 for (auto Range
: Ranges
)
1944 S
.Diag(Ranges
.begin()->getBegin(), PDiag
);
1947 // If Statement is an incemement or decrement, return true and sets the
1948 // variables Increment and DRE.
1949 bool ProcessIterationStmt(Sema
&S
, Stmt
* Statement
, bool &Increment
,
1950 DeclRefExpr
*&DRE
) {
1951 if (auto Cleanups
= dyn_cast
<ExprWithCleanups
>(Statement
))
1952 if (!Cleanups
->cleanupsHaveSideEffects())
1953 Statement
= Cleanups
->getSubExpr();
1955 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(Statement
)) {
1956 switch (UO
->getOpcode()) {
1957 default: return false;
1967 DRE
= dyn_cast
<DeclRefExpr
>(UO
->getSubExpr());
1971 if (CXXOperatorCallExpr
*Call
= dyn_cast
<CXXOperatorCallExpr
>(Statement
)) {
1972 FunctionDecl
*FD
= Call
->getDirectCallee();
1973 if (!FD
|| !FD
->isOverloadedOperator()) return false;
1974 switch (FD
->getOverloadedOperator()) {
1975 default: return false;
1983 DRE
= dyn_cast
<DeclRefExpr
>(Call
->getArg(0));
1990 // A visitor to determine if a continue or break statement is a
1992 class BreakContinueFinder
: public ConstEvaluatedExprVisitor
<BreakContinueFinder
> {
1993 SourceLocation BreakLoc
;
1994 SourceLocation ContinueLoc
;
1995 bool InSwitch
= false;
1998 BreakContinueFinder(Sema
&S
, const Stmt
* Body
) :
1999 Inherited(S
.Context
) {
2003 typedef ConstEvaluatedExprVisitor
<BreakContinueFinder
> Inherited
;
2005 void VisitContinueStmt(const ContinueStmt
* E
) {
2006 ContinueLoc
= E
->getContinueLoc();
2009 void VisitBreakStmt(const BreakStmt
* E
) {
2011 BreakLoc
= E
->getBreakLoc();
2014 void VisitSwitchStmt(const SwitchStmt
* S
) {
2015 if (const Stmt
*Init
= S
->getInit())
2017 if (const Stmt
*CondVar
= S
->getConditionVariableDeclStmt())
2019 if (const Stmt
*Cond
= S
->getCond())
2022 // Don't return break statements from the body of a switch.
2024 if (const Stmt
*Body
= S
->getBody())
2029 void VisitForStmt(const ForStmt
*S
) {
2030 // Only visit the init statement of a for loop; the body
2031 // has a different break/continue scope.
2032 if (const Stmt
*Init
= S
->getInit())
2036 void VisitWhileStmt(const WhileStmt
*) {
2037 // Do nothing; the children of a while loop have a different
2038 // break/continue scope.
2041 void VisitDoStmt(const DoStmt
*) {
2042 // Do nothing; the children of a while loop have a different
2043 // break/continue scope.
2046 void VisitCXXForRangeStmt(const CXXForRangeStmt
*S
) {
2047 // Only visit the initialization of a for loop; the body
2048 // has a different break/continue scope.
2049 if (const Stmt
*Init
= S
->getInit())
2051 if (const Stmt
*Range
= S
->getRangeStmt())
2053 if (const Stmt
*Begin
= S
->getBeginStmt())
2055 if (const Stmt
*End
= S
->getEndStmt())
2059 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt
*S
) {
2060 // Only visit the initialization of a for loop; the body
2061 // has a different break/continue scope.
2062 if (const Stmt
*Element
= S
->getElement())
2064 if (const Stmt
*Collection
= S
->getCollection())
2068 bool ContinueFound() { return ContinueLoc
.isValid(); }
2069 bool BreakFound() { return BreakLoc
.isValid(); }
2070 SourceLocation
GetContinueLoc() { return ContinueLoc
; }
2071 SourceLocation
GetBreakLoc() { return BreakLoc
; }
2073 }; // end class BreakContinueFinder
2075 // Emit a warning when a loop increment/decrement appears twice per loop
2076 // iteration. The conditions which trigger this warning are:
2077 // 1) The last statement in the loop body and the third expression in the
2078 // for loop are both increment or both decrement of the same variable
2079 // 2) No continue statements in the loop body.
2080 void CheckForRedundantIteration(Sema
&S
, Expr
*Third
, Stmt
*Body
) {
2081 // Return when there is nothing to check.
2082 if (!Body
|| !Third
) return;
2084 if (S
.Diags
.isIgnored(diag::warn_redundant_loop_iteration
,
2085 Third
->getBeginLoc()))
2088 // Get the last statement from the loop body.
2089 CompoundStmt
*CS
= dyn_cast
<CompoundStmt
>(Body
);
2090 if (!CS
|| CS
->body_empty()) return;
2091 Stmt
*LastStmt
= CS
->body_back();
2092 if (!LastStmt
) return;
2094 bool LoopIncrement
, LastIncrement
;
2095 DeclRefExpr
*LoopDRE
, *LastDRE
;
2097 if (!ProcessIterationStmt(S
, Third
, LoopIncrement
, LoopDRE
)) return;
2098 if (!ProcessIterationStmt(S
, LastStmt
, LastIncrement
, LastDRE
)) return;
2100 // Check that the two statements are both increments or both decrements
2101 // on the same variable.
2102 if (LoopIncrement
!= LastIncrement
||
2103 LoopDRE
->getDecl() != LastDRE
->getDecl()) return;
2105 if (BreakContinueFinder(S
, Body
).ContinueFound()) return;
2107 S
.Diag(LastDRE
->getLocation(), diag::warn_redundant_loop_iteration
)
2108 << LastDRE
->getDecl() << LastIncrement
;
2109 S
.Diag(LoopDRE
->getLocation(), diag::note_loop_iteration_here
)
2116 void Sema::CheckBreakContinueBinding(Expr
*E
) {
2117 if (!E
|| getLangOpts().CPlusPlus
)
2119 BreakContinueFinder
BCFinder(*this, E
);
2120 Scope
*BreakParent
= CurScope
->getBreakParent();
2121 if (BCFinder
.BreakFound() && BreakParent
) {
2122 if (BreakParent
->getFlags() & Scope::SwitchScope
) {
2123 Diag(BCFinder
.GetBreakLoc(), diag::warn_break_binds_to_switch
);
2125 Diag(BCFinder
.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner
)
2128 } else if (BCFinder
.ContinueFound() && CurScope
->getContinueParent()) {
2129 Diag(BCFinder
.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner
)
2134 StmtResult
Sema::ActOnForStmt(SourceLocation ForLoc
, SourceLocation LParenLoc
,
2135 Stmt
*First
, ConditionResult Second
,
2136 FullExprArg third
, SourceLocation RParenLoc
,
2138 if (Second
.isInvalid())
2141 if (!getLangOpts().CPlusPlus
) {
2142 if (DeclStmt
*DS
= dyn_cast_or_null
<DeclStmt
>(First
)) {
2143 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2144 // declare identifiers for objects having storage class 'auto' or
2146 const Decl
*NonVarSeen
= nullptr;
2147 bool VarDeclSeen
= false;
2148 for (auto *DI
: DS
->decls()) {
2149 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(DI
)) {
2151 if (VD
->isLocalVarDecl() && !VD
->hasLocalStorage()) {
2152 Diag(DI
->getLocation(), diag::err_non_local_variable_decl_in_for
);
2153 DI
->setInvalidDecl();
2155 } else if (!NonVarSeen
) {
2156 // Keep track of the first non-variable declaration we saw so that
2157 // we can diagnose if we don't see any variable declarations. This
2158 // covers a case like declaring a typedef, function, or structure
2159 // type rather than a variable.
2163 // Diagnose if we saw a non-variable declaration but no variable
2165 if (NonVarSeen
&& !VarDeclSeen
)
2166 Diag(NonVarSeen
->getLocation(), diag::err_non_variable_decl_in_for
);
2170 CheckBreakContinueBinding(Second
.get().second
);
2171 CheckBreakContinueBinding(third
.get());
2173 if (!Second
.get().first
)
2174 CheckForLoopConditionalStatement(*this, Second
.get().second
, third
.get(),
2176 CheckForRedundantIteration(*this, third
.get(), Body
);
2178 if (Second
.get().second
&&
2179 !Diags
.isIgnored(diag::warn_comma_operator
,
2180 Second
.get().second
->getExprLoc()))
2181 CommaVisitor(*this).Visit(Second
.get().second
);
2183 Expr
*Third
= third
.release().getAs
<Expr
>();
2184 if (isa
<NullStmt
>(Body
))
2185 getCurCompoundScope().setHasEmptyLoopBodies();
2187 return new (Context
)
2188 ForStmt(Context
, First
, Second
.get().second
, Second
.get().first
, Third
,
2189 Body
, ForLoc
, LParenLoc
, RParenLoc
);
2192 /// In an Objective C collection iteration statement:
2194 /// x can be an arbitrary l-value expression. Bind it up as a
2195 /// full-expression.
2196 StmtResult
Sema::ActOnForEachLValueExpr(Expr
*E
) {
2197 // Reduce placeholder expressions here. Note that this rejects the
2198 // use of pseudo-object l-values in this position.
2199 ExprResult result
= CheckPlaceholderExpr(E
);
2200 if (result
.isInvalid()) return StmtError();
2203 ExprResult FullExpr
= ActOnFinishFullExpr(E
, /*DiscardedValue*/ false);
2204 if (FullExpr
.isInvalid())
2206 return StmtResult(static_cast<Stmt
*>(FullExpr
.get()));
2210 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc
, Expr
*collection
) {
2214 ExprResult result
= CorrectDelayedTyposInExpr(collection
);
2215 if (!result
.isUsable())
2217 collection
= result
.get();
2219 // Bail out early if we've got a type-dependent expression.
2220 if (collection
->isTypeDependent()) return collection
;
2222 // Perform normal l-value conversion.
2223 result
= DefaultFunctionArrayLvalueConversion(collection
);
2224 if (result
.isInvalid())
2226 collection
= result
.get();
2228 // The operand needs to have object-pointer type.
2229 // TODO: should we do a contextual conversion?
2230 const ObjCObjectPointerType
*pointerType
=
2231 collection
->getType()->getAs
<ObjCObjectPointerType
>();
2233 return Diag(forLoc
, diag::err_collection_expr_type
)
2234 << collection
->getType() << collection
->getSourceRange();
2236 // Check that the operand provides
2237 // - countByEnumeratingWithState:objects:count:
2238 const ObjCObjectType
*objectType
= pointerType
->getObjectType();
2239 ObjCInterfaceDecl
*iface
= objectType
->getInterface();
2241 // If we have a forward-declared type, we can't do this check.
2242 // Under ARC, it is an error not to have a forward-declared class.
2244 (getLangOpts().ObjCAutoRefCount
2245 ? RequireCompleteType(forLoc
, QualType(objectType
, 0),
2246 diag::err_arc_collection_forward
, collection
)
2247 : !isCompleteType(forLoc
, QualType(objectType
, 0)))) {
2248 // Otherwise, if we have any useful type information, check that
2249 // the type declares the appropriate method.
2250 } else if (iface
|| !objectType
->qual_empty()) {
2251 IdentifierInfo
*selectorIdents
[] = {
2252 &Context
.Idents
.get("countByEnumeratingWithState"),
2253 &Context
.Idents
.get("objects"),
2254 &Context
.Idents
.get("count")
2256 Selector selector
= Context
.Selectors
.getSelector(3, &selectorIdents
[0]);
2258 ObjCMethodDecl
*method
= nullptr;
2260 // If there's an interface, look in both the public and private APIs.
2262 method
= iface
->lookupInstanceMethod(selector
);
2263 if (!method
) method
= iface
->lookupPrivateMethod(selector
);
2266 // Also check protocol qualifiers.
2268 method
= LookupMethodInQualifiedType(selector
, pointerType
,
2271 // If we didn't find it anywhere, give up.
2273 Diag(forLoc
, diag::warn_collection_expr_type
)
2274 << collection
->getType() << selector
<< collection
->getSourceRange();
2277 // TODO: check for an incompatible signature?
2280 // Wrap up any cleanups in the expression.
2285 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc
,
2286 Stmt
*First
, Expr
*collection
,
2287 SourceLocation RParenLoc
) {
2288 setFunctionHasBranchProtectedScope();
2290 ExprResult CollectionExprResult
=
2291 CheckObjCForCollectionOperand(ForLoc
, collection
);
2295 if (DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
)) {
2296 if (!DS
->isSingleDecl())
2297 return StmtError(Diag((*DS
->decl_begin())->getLocation(),
2298 diag::err_toomany_element_decls
));
2300 VarDecl
*D
= dyn_cast
<VarDecl
>(DS
->getSingleDecl());
2301 if (!D
|| D
->isInvalidDecl())
2304 FirstType
= D
->getType();
2305 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2306 // declare identifiers for objects having storage class 'auto' or
2308 if (!D
->hasLocalStorage())
2309 return StmtError(Diag(D
->getLocation(),
2310 diag::err_non_local_variable_decl_in_for
));
2312 // If the type contained 'auto', deduce the 'auto' to 'id'.
2313 if (FirstType
->getContainedAutoType()) {
2314 SourceLocation Loc
= D
->getLocation();
2315 OpaqueValueExpr
OpaqueId(Loc
, Context
.getObjCIdType(), VK_PRValue
);
2316 Expr
*DeducedInit
= &OpaqueId
;
2317 TemplateDeductionInfo
Info(Loc
);
2318 FirstType
= QualType();
2319 TemplateDeductionResult Result
= DeduceAutoType(
2320 D
->getTypeSourceInfo()->getTypeLoc(), DeducedInit
, FirstType
, Info
);
2321 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
)
2322 DiagnoseAutoDeductionFailure(D
, DeducedInit
);
2323 if (FirstType
.isNull()) {
2324 D
->setInvalidDecl();
2328 D
->setType(FirstType
);
2330 if (!inTemplateInstantiation()) {
2331 SourceLocation Loc
=
2332 D
->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
2333 Diag(Loc
, diag::warn_auto_var_is_id
)
2334 << D
->getDeclName();
2339 Expr
*FirstE
= cast
<Expr
>(First
);
2340 if (!FirstE
->isTypeDependent() && !FirstE
->isLValue())
2342 Diag(First
->getBeginLoc(), diag::err_selector_element_not_lvalue
)
2343 << First
->getSourceRange());
2345 FirstType
= static_cast<Expr
*>(First
)->getType();
2346 if (FirstType
.isConstQualified())
2347 Diag(ForLoc
, diag::err_selector_element_const_type
)
2348 << FirstType
<< First
->getSourceRange();
2350 if (!FirstType
->isDependentType() &&
2351 !FirstType
->isObjCObjectPointerType() &&
2352 !FirstType
->isBlockPointerType())
2353 return StmtError(Diag(ForLoc
, diag::err_selector_element_type
)
2354 << FirstType
<< First
->getSourceRange());
2357 if (CollectionExprResult
.isInvalid())
2360 CollectionExprResult
=
2361 ActOnFinishFullExpr(CollectionExprResult
.get(), /*DiscardedValue*/ false);
2362 if (CollectionExprResult
.isInvalid())
2365 return new (Context
) ObjCForCollectionStmt(First
, CollectionExprResult
.get(),
2366 nullptr, ForLoc
, RParenLoc
);
2369 /// Finish building a variable declaration for a for-range statement.
2370 /// \return true if an error occurs.
2371 static bool FinishForRangeVarDecl(Sema
&SemaRef
, VarDecl
*Decl
, Expr
*Init
,
2372 SourceLocation Loc
, int DiagID
) {
2373 if (Decl
->getType()->isUndeducedType()) {
2374 ExprResult Res
= SemaRef
.CorrectDelayedTyposInExpr(Init
);
2375 if (!Res
.isUsable()) {
2376 Decl
->setInvalidDecl();
2382 // Deduce the type for the iterator variable now rather than leaving it to
2383 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2385 if (!isa
<InitListExpr
>(Init
) && Init
->getType()->isVoidType()) {
2386 SemaRef
.Diag(Loc
, DiagID
) << Init
->getType();
2388 TemplateDeductionInfo
Info(Init
->getExprLoc());
2389 Sema::TemplateDeductionResult Result
= SemaRef
.DeduceAutoType(
2390 Decl
->getTypeSourceInfo()->getTypeLoc(), Init
, InitType
, Info
);
2391 if (Result
!= Sema::TDK_Success
&& Result
!= Sema::TDK_AlreadyDiagnosed
)
2392 SemaRef
.Diag(Loc
, DiagID
) << Init
->getType();
2395 if (InitType
.isNull()) {
2396 Decl
->setInvalidDecl();
2399 Decl
->setType(InitType
);
2401 // In ARC, infer lifetime.
2402 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2403 // we're doing the equivalent of fast iteration.
2404 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
2405 SemaRef
.inferObjCARCLifetime(Decl
))
2406 Decl
->setInvalidDecl();
2408 SemaRef
.AddInitializerToDecl(Decl
, Init
, /*DirectInit=*/false);
2409 SemaRef
.FinalizeDeclaration(Decl
);
2410 SemaRef
.CurContext
->addHiddenDecl(Decl
);
2415 // An enum to represent whether something is dealing with a call to begin()
2416 // or a call to end() in a range-based for loop.
2417 enum BeginEndFunction
{
2422 /// Produce a note indicating which begin/end function was implicitly called
2423 /// by a C++11 for-range statement. This is often not obvious from the code,
2424 /// nor from the diagnostics produced when analysing the implicit expressions
2425 /// required in a for-range statement.
2426 void NoteForRangeBeginEndFunction(Sema
&SemaRef
, Expr
*E
,
2427 BeginEndFunction BEF
) {
2428 CallExpr
*CE
= dyn_cast
<CallExpr
>(E
);
2431 FunctionDecl
*D
= dyn_cast
<FunctionDecl
>(CE
->getCalleeDecl());
2434 SourceLocation Loc
= D
->getLocation();
2436 std::string Description
;
2437 bool IsTemplate
= false;
2438 if (FunctionTemplateDecl
*FunTmpl
= D
->getPrimaryTemplate()) {
2439 Description
= SemaRef
.getTemplateArgumentBindingsText(
2440 FunTmpl
->getTemplateParameters(), *D
->getTemplateSpecializationArgs());
2444 SemaRef
.Diag(Loc
, diag::note_for_range_begin_end
)
2445 << BEF
<< IsTemplate
<< Description
<< E
->getType();
2448 /// Build a variable declaration for a for-range statement.
2449 VarDecl
*BuildForRangeVarDecl(Sema
&SemaRef
, SourceLocation Loc
,
2450 QualType Type
, StringRef Name
) {
2451 DeclContext
*DC
= SemaRef
.CurContext
;
2452 IdentifierInfo
*II
= &SemaRef
.PP
.getIdentifierTable().get(Name
);
2453 TypeSourceInfo
*TInfo
= SemaRef
.Context
.getTrivialTypeSourceInfo(Type
, Loc
);
2454 VarDecl
*Decl
= VarDecl::Create(SemaRef
.Context
, DC
, Loc
, Loc
, II
, Type
,
2456 Decl
->setImplicit();
2462 static bool ObjCEnumerationCollection(Expr
*Collection
) {
2463 return !Collection
->isTypeDependent()
2464 && Collection
->getType()->getAs
<ObjCObjectPointerType
>() != nullptr;
2467 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2469 /// C++11 [stmt.ranged]:
2470 /// A range-based for statement is equivalent to
2473 /// auto && __range = range-init;
2474 /// for ( auto __begin = begin-expr,
2475 /// __end = end-expr;
2476 /// __begin != __end;
2478 /// for-range-declaration = *__begin;
2483 /// The body of the loop is not available yet, since it cannot be analysed until
2484 /// we have determined the type of the for-range-declaration.
2485 StmtResult
Sema::ActOnCXXForRangeStmt(Scope
*S
, SourceLocation ForLoc
,
2486 SourceLocation CoawaitLoc
, Stmt
*InitStmt
,
2487 Stmt
*First
, SourceLocation ColonLoc
,
2488 Expr
*Range
, SourceLocation RParenLoc
,
2489 BuildForRangeKind Kind
) {
2490 // FIXME: recover in order to allow the body to be parsed.
2494 if (Range
&& ObjCEnumerationCollection(Range
)) {
2495 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2497 return Diag(InitStmt
->getBeginLoc(), diag::err_objc_for_range_init_stmt
)
2498 << InitStmt
->getSourceRange();
2499 return ActOnObjCForCollectionStmt(ForLoc
, First
, Range
, RParenLoc
);
2502 DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
);
2503 assert(DS
&& "first part of for range not a decl stmt");
2505 if (!DS
->isSingleDecl()) {
2506 Diag(DS
->getBeginLoc(), diag::err_type_defined_in_for_range
);
2510 // This function is responsible for attaching an initializer to LoopVar. We
2511 // must call ActOnInitializerError if we fail to do so.
2512 Decl
*LoopVar
= DS
->getSingleDecl();
2513 if (LoopVar
->isInvalidDecl() || !Range
||
2514 DiagnoseUnexpandedParameterPack(Range
, UPPC_Expression
)) {
2515 ActOnInitializerError(LoopVar
);
2519 // Build the coroutine state immediately and not later during template
2521 if (!CoawaitLoc
.isInvalid()) {
2522 if (!ActOnCoroutineBodyStart(S
, CoawaitLoc
, "co_await")) {
2523 ActOnInitializerError(LoopVar
);
2528 // Build auto && __range = range-init
2529 // Divide by 2, since the variables are in the inner scope (loop body).
2530 const auto DepthStr
= std::to_string(S
->getDepth() / 2);
2531 SourceLocation RangeLoc
= Range
->getBeginLoc();
2532 VarDecl
*RangeVar
= BuildForRangeVarDecl(*this, RangeLoc
,
2533 Context
.getAutoRRefDeductType(),
2534 std::string("__range") + DepthStr
);
2535 if (FinishForRangeVarDecl(*this, RangeVar
, Range
, RangeLoc
,
2536 diag::err_for_range_deduction_failure
)) {
2537 ActOnInitializerError(LoopVar
);
2541 // Claim the type doesn't contain auto: we've already done the checking.
2542 DeclGroupPtrTy RangeGroup
=
2543 BuildDeclaratorGroup(MutableArrayRef
<Decl
*>((Decl
**)&RangeVar
, 1));
2544 StmtResult RangeDecl
= ActOnDeclStmt(RangeGroup
, RangeLoc
, RangeLoc
);
2545 if (RangeDecl
.isInvalid()) {
2546 ActOnInitializerError(LoopVar
);
2550 StmtResult R
= BuildCXXForRangeStmt(
2551 ForLoc
, CoawaitLoc
, InitStmt
, ColonLoc
, RangeDecl
.get(),
2552 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2553 /*Cond=*/nullptr, /*Inc=*/nullptr, DS
, RParenLoc
, Kind
);
2554 if (R
.isInvalid()) {
2555 ActOnInitializerError(LoopVar
);
2562 /// Create the initialization, compare, and increment steps for
2563 /// the range-based for loop expression.
2564 /// This function does not handle array-based for loops,
2565 /// which are created in Sema::BuildCXXForRangeStmt.
2567 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2568 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2569 /// CandidateSet and BEF are set and some non-success value is returned on
2571 static Sema::ForRangeStatus
2572 BuildNonArrayForRange(Sema
&SemaRef
, Expr
*BeginRange
, Expr
*EndRange
,
2573 QualType RangeType
, VarDecl
*BeginVar
, VarDecl
*EndVar
,
2574 SourceLocation ColonLoc
, SourceLocation CoawaitLoc
,
2575 OverloadCandidateSet
*CandidateSet
, ExprResult
*BeginExpr
,
2576 ExprResult
*EndExpr
, BeginEndFunction
*BEF
) {
2577 DeclarationNameInfo
BeginNameInfo(
2578 &SemaRef
.PP
.getIdentifierTable().get("begin"), ColonLoc
);
2579 DeclarationNameInfo
EndNameInfo(&SemaRef
.PP
.getIdentifierTable().get("end"),
2582 LookupResult
BeginMemberLookup(SemaRef
, BeginNameInfo
,
2583 Sema::LookupMemberName
);
2584 LookupResult
EndMemberLookup(SemaRef
, EndNameInfo
, Sema::LookupMemberName
);
2586 auto BuildBegin
= [&] {
2588 Sema::ForRangeStatus RangeStatus
=
2589 SemaRef
.BuildForRangeBeginEndCall(ColonLoc
, ColonLoc
, BeginNameInfo
,
2590 BeginMemberLookup
, CandidateSet
,
2591 BeginRange
, BeginExpr
);
2593 if (RangeStatus
!= Sema::FRS_Success
) {
2594 if (RangeStatus
== Sema::FRS_DiagnosticIssued
)
2595 SemaRef
.Diag(BeginRange
->getBeginLoc(), diag::note_in_for_range
)
2596 << ColonLoc
<< BEF_begin
<< BeginRange
->getType();
2599 if (!CoawaitLoc
.isInvalid()) {
2600 // FIXME: getCurScope() should not be used during template instantiation.
2601 // We should pick up the set of unqualified lookup results for operator
2602 // co_await during the initial parse.
2603 *BeginExpr
= SemaRef
.ActOnCoawaitExpr(SemaRef
.getCurScope(), ColonLoc
,
2605 if (BeginExpr
->isInvalid())
2606 return Sema::FRS_DiagnosticIssued
;
2608 if (FinishForRangeVarDecl(SemaRef
, BeginVar
, BeginExpr
->get(), ColonLoc
,
2609 diag::err_for_range_iter_deduction_failure
)) {
2610 NoteForRangeBeginEndFunction(SemaRef
, BeginExpr
->get(), *BEF
);
2611 return Sema::FRS_DiagnosticIssued
;
2613 return Sema::FRS_Success
;
2616 auto BuildEnd
= [&] {
2618 Sema::ForRangeStatus RangeStatus
=
2619 SemaRef
.BuildForRangeBeginEndCall(ColonLoc
, ColonLoc
, EndNameInfo
,
2620 EndMemberLookup
, CandidateSet
,
2622 if (RangeStatus
!= Sema::FRS_Success
) {
2623 if (RangeStatus
== Sema::FRS_DiagnosticIssued
)
2624 SemaRef
.Diag(EndRange
->getBeginLoc(), diag::note_in_for_range
)
2625 << ColonLoc
<< BEF_end
<< EndRange
->getType();
2628 if (FinishForRangeVarDecl(SemaRef
, EndVar
, EndExpr
->get(), ColonLoc
,
2629 diag::err_for_range_iter_deduction_failure
)) {
2630 NoteForRangeBeginEndFunction(SemaRef
, EndExpr
->get(), *BEF
);
2631 return Sema::FRS_DiagnosticIssued
;
2633 return Sema::FRS_Success
;
2636 if (CXXRecordDecl
*D
= RangeType
->getAsCXXRecordDecl()) {
2637 // - if _RangeT is a class type, the unqualified-ids begin and end are
2638 // looked up in the scope of class _RangeT as if by class member access
2639 // lookup (3.4.5), and if either (or both) finds at least one
2640 // declaration, begin-expr and end-expr are __range.begin() and
2641 // __range.end(), respectively;
2642 SemaRef
.LookupQualifiedName(BeginMemberLookup
, D
);
2643 if (BeginMemberLookup
.isAmbiguous())
2644 return Sema::FRS_DiagnosticIssued
;
2646 SemaRef
.LookupQualifiedName(EndMemberLookup
, D
);
2647 if (EndMemberLookup
.isAmbiguous())
2648 return Sema::FRS_DiagnosticIssued
;
2650 if (BeginMemberLookup
.empty() != EndMemberLookup
.empty()) {
2651 // Look up the non-member form of the member we didn't find, first.
2652 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2653 // a 'begin' but ignored it because there was no member 'end'"
2655 auto BuildNonmember
= [&](
2656 BeginEndFunction BEFFound
, LookupResult
&Found
,
2657 llvm::function_ref
<Sema::ForRangeStatus()> BuildFound
,
2658 llvm::function_ref
<Sema::ForRangeStatus()> BuildNotFound
) {
2659 LookupResult OldFound
= std::move(Found
);
2662 if (Sema::ForRangeStatus Result
= BuildNotFound())
2665 switch (BuildFound()) {
2666 case Sema::FRS_Success
:
2667 return Sema::FRS_Success
;
2669 case Sema::FRS_NoViableFunction
:
2670 CandidateSet
->NoteCandidates(
2671 PartialDiagnosticAt(BeginRange
->getBeginLoc(),
2672 SemaRef
.PDiag(diag::err_for_range_invalid
)
2673 << BeginRange
->getType() << BEFFound
),
2674 SemaRef
, OCD_AllCandidates
, BeginRange
);
2677 case Sema::FRS_DiagnosticIssued
:
2678 for (NamedDecl
*D
: OldFound
) {
2679 SemaRef
.Diag(D
->getLocation(),
2680 diag::note_for_range_member_begin_end_ignored
)
2681 << BeginRange
->getType() << BEFFound
;
2683 return Sema::FRS_DiagnosticIssued
;
2685 llvm_unreachable("unexpected ForRangeStatus");
2687 if (BeginMemberLookup
.empty())
2688 return BuildNonmember(BEF_end
, EndMemberLookup
, BuildEnd
, BuildBegin
);
2689 return BuildNonmember(BEF_begin
, BeginMemberLookup
, BuildBegin
, BuildEnd
);
2692 // - otherwise, begin-expr and end-expr are begin(__range) and
2693 // end(__range), respectively, where begin and end are looked up with
2694 // argument-dependent lookup (3.4.2). For the purposes of this name
2695 // lookup, namespace std is an associated namespace.
2698 if (Sema::ForRangeStatus Result
= BuildBegin())
2703 /// Speculatively attempt to dereference an invalid range expression.
2704 /// If the attempt fails, this function will return a valid, null StmtResult
2705 /// and emit no diagnostics.
2706 static StmtResult
RebuildForRangeWithDereference(Sema
&SemaRef
, Scope
*S
,
2707 SourceLocation ForLoc
,
2708 SourceLocation CoawaitLoc
,
2711 SourceLocation ColonLoc
,
2713 SourceLocation RangeLoc
,
2714 SourceLocation RParenLoc
) {
2715 // Determine whether we can rebuild the for-range statement with a
2716 // dereferenced range expression.
2717 ExprResult AdjustedRange
;
2719 Sema::SFINAETrap
Trap(SemaRef
);
2721 AdjustedRange
= SemaRef
.BuildUnaryOp(S
, RangeLoc
, UO_Deref
, Range
);
2722 if (AdjustedRange
.isInvalid())
2723 return StmtResult();
2725 StmtResult SR
= SemaRef
.ActOnCXXForRangeStmt(
2726 S
, ForLoc
, CoawaitLoc
, InitStmt
, LoopVarDecl
, ColonLoc
,
2727 AdjustedRange
.get(), RParenLoc
, Sema::BFRK_Check
);
2729 return StmtResult();
2732 // The attempt to dereference worked well enough that it could produce a valid
2733 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2734 // case there are any other (non-fatal) problems with it.
2735 SemaRef
.Diag(RangeLoc
, diag::err_for_range_dereference
)
2736 << Range
->getType() << FixItHint::CreateInsertion(RangeLoc
, "*");
2737 return SemaRef
.ActOnCXXForRangeStmt(
2738 S
, ForLoc
, CoawaitLoc
, InitStmt
, LoopVarDecl
, ColonLoc
,
2739 AdjustedRange
.get(), RParenLoc
, Sema::BFRK_Rebuild
);
2742 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2743 StmtResult
Sema::BuildCXXForRangeStmt(SourceLocation ForLoc
,
2744 SourceLocation CoawaitLoc
, Stmt
*InitStmt
,
2745 SourceLocation ColonLoc
, Stmt
*RangeDecl
,
2746 Stmt
*Begin
, Stmt
*End
, Expr
*Cond
,
2747 Expr
*Inc
, Stmt
*LoopVarDecl
,
2748 SourceLocation RParenLoc
,
2749 BuildForRangeKind Kind
) {
2750 // FIXME: This should not be used during template instantiation. We should
2751 // pick up the set of unqualified lookup results for the != and + operators
2752 // in the initial parse.
2754 // Testcase (accepts-invalid):
2755 // template<typename T> void f() { for (auto x : T()) {} }
2756 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2757 // bool operator!=(N::X, N::X); void operator++(N::X);
2758 // void g() { f<N::X>(); }
2759 Scope
*S
= getCurScope();
2761 DeclStmt
*RangeDS
= cast
<DeclStmt
>(RangeDecl
);
2762 VarDecl
*RangeVar
= cast
<VarDecl
>(RangeDS
->getSingleDecl());
2763 QualType RangeVarType
= RangeVar
->getType();
2765 DeclStmt
*LoopVarDS
= cast
<DeclStmt
>(LoopVarDecl
);
2766 VarDecl
*LoopVar
= cast
<VarDecl
>(LoopVarDS
->getSingleDecl());
2768 StmtResult BeginDeclStmt
= Begin
;
2769 StmtResult EndDeclStmt
= End
;
2770 ExprResult NotEqExpr
= Cond
, IncrExpr
= Inc
;
2772 if (RangeVarType
->isDependentType()) {
2773 // The range is implicitly used as a placeholder when it is dependent.
2774 RangeVar
->markUsed(Context
);
2776 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2777 // them in properly when we instantiate the loop.
2778 if (!LoopVar
->isInvalidDecl() && Kind
!= BFRK_Check
) {
2779 if (auto *DD
= dyn_cast
<DecompositionDecl
>(LoopVar
))
2780 for (auto *Binding
: DD
->bindings())
2781 Binding
->setType(Context
.DependentTy
);
2782 LoopVar
->setType(SubstAutoTypeDependent(LoopVar
->getType()));
2784 } else if (!BeginDeclStmt
.get()) {
2785 SourceLocation RangeLoc
= RangeVar
->getLocation();
2787 const QualType RangeVarNonRefType
= RangeVarType
.getNonReferenceType();
2789 ExprResult BeginRangeRef
= BuildDeclRefExpr(RangeVar
, RangeVarNonRefType
,
2790 VK_LValue
, ColonLoc
);
2791 if (BeginRangeRef
.isInvalid())
2794 ExprResult EndRangeRef
= BuildDeclRefExpr(RangeVar
, RangeVarNonRefType
,
2795 VK_LValue
, ColonLoc
);
2796 if (EndRangeRef
.isInvalid())
2799 QualType AutoType
= Context
.getAutoDeductType();
2800 Expr
*Range
= RangeVar
->getInit();
2803 QualType RangeType
= Range
->getType();
2805 if (RequireCompleteType(RangeLoc
, RangeType
,
2806 diag::err_for_range_incomplete_type
))
2809 // Build auto __begin = begin-expr, __end = end-expr.
2810 // Divide by 2, since the variables are in the inner scope (loop body).
2811 const auto DepthStr
= std::to_string(S
->getDepth() / 2);
2812 VarDecl
*BeginVar
= BuildForRangeVarDecl(*this, ColonLoc
, AutoType
,
2813 std::string("__begin") + DepthStr
);
2814 VarDecl
*EndVar
= BuildForRangeVarDecl(*this, ColonLoc
, AutoType
,
2815 std::string("__end") + DepthStr
);
2817 // Build begin-expr and end-expr and attach to __begin and __end variables.
2818 ExprResult BeginExpr
, EndExpr
;
2819 if (const ArrayType
*UnqAT
= RangeType
->getAsArrayTypeUnsafe()) {
2820 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2821 // __range + __bound, respectively, where __bound is the array bound. If
2822 // _RangeT is an array of unknown size or an array of incomplete type,
2823 // the program is ill-formed;
2825 // begin-expr is __range.
2826 BeginExpr
= BeginRangeRef
;
2827 if (!CoawaitLoc
.isInvalid()) {
2828 BeginExpr
= ActOnCoawaitExpr(S
, ColonLoc
, BeginExpr
.get());
2829 if (BeginExpr
.isInvalid())
2832 if (FinishForRangeVarDecl(*this, BeginVar
, BeginRangeRef
.get(), ColonLoc
,
2833 diag::err_for_range_iter_deduction_failure
)) {
2834 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
2838 // Find the array bound.
2839 ExprResult BoundExpr
;
2840 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(UnqAT
))
2841 BoundExpr
= IntegerLiteral::Create(
2842 Context
, CAT
->getSize(), Context
.getPointerDiffType(), RangeLoc
);
2843 else if (const VariableArrayType
*VAT
=
2844 dyn_cast
<VariableArrayType
>(UnqAT
)) {
2845 // For a variably modified type we can't just use the expression within
2846 // the array bounds, since we don't want that to be re-evaluated here.
2847 // Rather, we need to determine what it was when the array was first
2848 // created - so we resort to using sizeof(vla)/sizeof(element).
2852 // b = -1; <-- This should not affect the num of iterations below
2853 // for (int &c : vla) { .. }
2856 // FIXME: This results in codegen generating IR that recalculates the
2857 // run-time number of elements (as opposed to just using the IR Value
2858 // that corresponds to the run-time value of each bound that was
2859 // generated when the array was created.) If this proves too embarrassing
2860 // even for unoptimized IR, consider passing a magic-value/cookie to
2861 // codegen that then knows to simply use that initial llvm::Value (that
2862 // corresponds to the bound at time of array creation) within
2863 // getelementptr. But be prepared to pay the price of increasing a
2864 // customized form of coupling between the two components - which could
2865 // be hard to maintain as the codebase evolves.
2867 ExprResult SizeOfVLAExprR
= ActOnUnaryExprOrTypeTraitExpr(
2868 EndVar
->getLocation(), UETT_SizeOf
,
2870 CreateParsedType(VAT
->desugar(), Context
.getTrivialTypeSourceInfo(
2871 VAT
->desugar(), RangeLoc
))
2873 EndVar
->getSourceRange());
2874 if (SizeOfVLAExprR
.isInvalid())
2877 ExprResult SizeOfEachElementExprR
= ActOnUnaryExprOrTypeTraitExpr(
2878 EndVar
->getLocation(), UETT_SizeOf
,
2880 CreateParsedType(VAT
->desugar(),
2881 Context
.getTrivialTypeSourceInfo(
2882 VAT
->getElementType(), RangeLoc
))
2884 EndVar
->getSourceRange());
2885 if (SizeOfEachElementExprR
.isInvalid())
2889 ActOnBinOp(S
, EndVar
->getLocation(), tok::slash
,
2890 SizeOfVLAExprR
.get(), SizeOfEachElementExprR
.get());
2891 if (BoundExpr
.isInvalid())
2895 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2896 // UnqAT is not incomplete and Range is not type-dependent.
2897 llvm_unreachable("Unexpected array type in for-range");
2900 // end-expr is __range + __bound.
2901 EndExpr
= ActOnBinOp(S
, ColonLoc
, tok::plus
, EndRangeRef
.get(),
2903 if (EndExpr
.isInvalid())
2905 if (FinishForRangeVarDecl(*this, EndVar
, EndExpr
.get(), ColonLoc
,
2906 diag::err_for_range_iter_deduction_failure
)) {
2907 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
2911 OverloadCandidateSet
CandidateSet(RangeLoc
,
2912 OverloadCandidateSet::CSK_Normal
);
2913 BeginEndFunction BEFFailure
;
2914 ForRangeStatus RangeStatus
= BuildNonArrayForRange(
2915 *this, BeginRangeRef
.get(), EndRangeRef
.get(), RangeType
, BeginVar
,
2916 EndVar
, ColonLoc
, CoawaitLoc
, &CandidateSet
, &BeginExpr
, &EndExpr
,
2919 if (Kind
== BFRK_Build
&& RangeStatus
== FRS_NoViableFunction
&&
2920 BEFFailure
== BEF_begin
) {
2921 // If the range is being built from an array parameter, emit a
2922 // a diagnostic that it is being treated as a pointer.
2923 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Range
)) {
2924 if (ParmVarDecl
*PVD
= dyn_cast
<ParmVarDecl
>(DRE
->getDecl())) {
2925 QualType ArrayTy
= PVD
->getOriginalType();
2926 QualType PointerTy
= PVD
->getType();
2927 if (PointerTy
->isPointerType() && ArrayTy
->isArrayType()) {
2928 Diag(Range
->getBeginLoc(), diag::err_range_on_array_parameter
)
2929 << RangeLoc
<< PVD
<< ArrayTy
<< PointerTy
;
2930 Diag(PVD
->getLocation(), diag::note_declared_at
);
2936 // If building the range failed, try dereferencing the range expression
2937 // unless a diagnostic was issued or the end function is problematic.
2938 StmtResult SR
= RebuildForRangeWithDereference(*this, S
, ForLoc
,
2939 CoawaitLoc
, InitStmt
,
2940 LoopVarDecl
, ColonLoc
,
2943 if (SR
.isInvalid() || SR
.isUsable())
2947 // Otherwise, emit diagnostics if we haven't already.
2948 if (RangeStatus
== FRS_NoViableFunction
) {
2949 Expr
*Range
= BEFFailure
? EndRangeRef
.get() : BeginRangeRef
.get();
2950 CandidateSet
.NoteCandidates(
2951 PartialDiagnosticAt(Range
->getBeginLoc(),
2952 PDiag(diag::err_for_range_invalid
)
2953 << RangeLoc
<< Range
->getType()
2955 *this, OCD_AllCandidates
, Range
);
2957 // Return an error if no fix was discovered.
2958 if (RangeStatus
!= FRS_Success
)
2962 assert(!BeginExpr
.isInvalid() && !EndExpr
.isInvalid() &&
2963 "invalid range expression in for loop");
2965 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2966 // C++1z removes this restriction.
2967 QualType BeginType
= BeginVar
->getType(), EndType
= EndVar
->getType();
2968 if (!Context
.hasSameType(BeginType
, EndType
)) {
2969 Diag(RangeLoc
, getLangOpts().CPlusPlus17
2970 ? diag::warn_for_range_begin_end_types_differ
2971 : diag::ext_for_range_begin_end_types_differ
)
2972 << BeginType
<< EndType
;
2973 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
2974 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
2978 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar
), ColonLoc
, ColonLoc
);
2980 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar
), ColonLoc
, ColonLoc
);
2982 const QualType BeginRefNonRefType
= BeginType
.getNonReferenceType();
2983 ExprResult BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
2984 VK_LValue
, ColonLoc
);
2985 if (BeginRef
.isInvalid())
2988 ExprResult EndRef
= BuildDeclRefExpr(EndVar
, EndType
.getNonReferenceType(),
2989 VK_LValue
, ColonLoc
);
2990 if (EndRef
.isInvalid())
2993 // Build and check __begin != __end expression.
2994 NotEqExpr
= ActOnBinOp(S
, ColonLoc
, tok::exclaimequal
,
2995 BeginRef
.get(), EndRef
.get());
2996 if (!NotEqExpr
.isInvalid())
2997 NotEqExpr
= CheckBooleanCondition(ColonLoc
, NotEqExpr
.get());
2998 if (!NotEqExpr
.isInvalid())
3000 ActOnFinishFullExpr(NotEqExpr
.get(), /*DiscardedValue*/ false);
3001 if (NotEqExpr
.isInvalid()) {
3002 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3003 << RangeLoc
<< 0 << BeginRangeRef
.get()->getType();
3004 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3005 if (!Context
.hasSameType(BeginType
, EndType
))
3006 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
3010 // Build and check ++__begin expression.
3011 BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3012 VK_LValue
, ColonLoc
);
3013 if (BeginRef
.isInvalid())
3016 IncrExpr
= ActOnUnaryOp(S
, ColonLoc
, tok::plusplus
, BeginRef
.get());
3017 if (!IncrExpr
.isInvalid() && CoawaitLoc
.isValid())
3018 // FIXME: getCurScope() should not be used during template instantiation.
3019 // We should pick up the set of unqualified lookup results for operator
3020 // co_await during the initial parse.
3021 IncrExpr
= ActOnCoawaitExpr(S
, CoawaitLoc
, IncrExpr
.get());
3022 if (!IncrExpr
.isInvalid())
3023 IncrExpr
= ActOnFinishFullExpr(IncrExpr
.get(), /*DiscardedValue*/ false);
3024 if (IncrExpr
.isInvalid()) {
3025 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3026 << RangeLoc
<< 2 << BeginRangeRef
.get()->getType() ;
3027 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3031 // Build and check *__begin expression.
3032 BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3033 VK_LValue
, ColonLoc
);
3034 if (BeginRef
.isInvalid())
3037 ExprResult DerefExpr
= ActOnUnaryOp(S
, ColonLoc
, tok::star
, BeginRef
.get());
3038 if (DerefExpr
.isInvalid()) {
3039 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3040 << RangeLoc
<< 1 << BeginRangeRef
.get()->getType();
3041 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3045 // Attach *__begin as initializer for VD. Don't touch it if we're just
3046 // trying to determine whether this would be a valid range.
3047 if (!LoopVar
->isInvalidDecl() && Kind
!= BFRK_Check
) {
3048 AddInitializerToDecl(LoopVar
, DerefExpr
.get(), /*DirectInit=*/false);
3049 if (LoopVar
->isInvalidDecl() ||
3050 (LoopVar
->getInit() && LoopVar
->getInit()->containsErrors()))
3051 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3055 // Don't bother to actually allocate the result if we're just trying to
3056 // determine whether it would be valid.
3057 if (Kind
== BFRK_Check
)
3058 return StmtResult();
3060 // In OpenMP loop region loop control variable must be private. Perform
3061 // analysis of first part (if any).
3062 if (getLangOpts().OpenMP
>= 50 && BeginDeclStmt
.isUsable())
3063 ActOnOpenMPLoopInitialization(ForLoc
, BeginDeclStmt
.get());
3065 return new (Context
) CXXForRangeStmt(
3066 InitStmt
, RangeDS
, cast_or_null
<DeclStmt
>(BeginDeclStmt
.get()),
3067 cast_or_null
<DeclStmt
>(EndDeclStmt
.get()), NotEqExpr
.get(),
3068 IncrExpr
.get(), LoopVarDS
, /*Body=*/nullptr, ForLoc
, CoawaitLoc
,
3069 ColonLoc
, RParenLoc
);
3072 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
3074 StmtResult
Sema::FinishObjCForCollectionStmt(Stmt
*S
, Stmt
*B
) {
3077 ObjCForCollectionStmt
* ForStmt
= cast
<ObjCForCollectionStmt
>(S
);
3079 ForStmt
->setBody(B
);
3083 // Warn when the loop variable is a const reference that creates a copy.
3084 // Suggest using the non-reference type for copies. If a copy can be prevented
3085 // suggest the const reference type that would do so.
3086 // For instance, given "for (const &Foo : Range)", suggest
3087 // "for (const Foo : Range)" to denote a copy is made for the loop. If
3088 // possible, also suggest "for (const &Bar : Range)" if this type prevents
3089 // the copy altogether.
3090 static void DiagnoseForRangeReferenceVariableCopies(Sema
&SemaRef
,
3092 QualType RangeInitType
) {
3093 const Expr
*InitExpr
= VD
->getInit();
3097 QualType VariableType
= VD
->getType();
3099 if (auto Cleanups
= dyn_cast
<ExprWithCleanups
>(InitExpr
))
3100 if (!Cleanups
->cleanupsHaveSideEffects())
3101 InitExpr
= Cleanups
->getSubExpr();
3103 const MaterializeTemporaryExpr
*MTE
=
3104 dyn_cast
<MaterializeTemporaryExpr
>(InitExpr
);
3110 const Expr
*E
= MTE
->getSubExpr()->IgnoreImpCasts();
3112 // Searching for either UnaryOperator for dereference of a pointer or
3113 // CXXOperatorCallExpr for handling iterators.
3114 while (!isa
<CXXOperatorCallExpr
>(E
) && !isa
<UnaryOperator
>(E
)) {
3115 if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(E
)) {
3117 } else if (const CXXMemberCallExpr
*Call
= dyn_cast
<CXXMemberCallExpr
>(E
)) {
3118 const MemberExpr
*ME
= cast
<MemberExpr
>(Call
->getCallee());
3121 const MaterializeTemporaryExpr
*MTE
= cast
<MaterializeTemporaryExpr
>(E
);
3122 E
= MTE
->getSubExpr();
3124 E
= E
->IgnoreImpCasts();
3127 QualType ReferenceReturnType
;
3128 if (isa
<UnaryOperator
>(E
)) {
3129 ReferenceReturnType
= SemaRef
.Context
.getLValueReferenceType(E
->getType());
3131 const CXXOperatorCallExpr
*Call
= cast
<CXXOperatorCallExpr
>(E
);
3132 const FunctionDecl
*FD
= Call
->getDirectCallee();
3133 QualType ReturnType
= FD
->getReturnType();
3134 if (ReturnType
->isReferenceType())
3135 ReferenceReturnType
= ReturnType
;
3138 if (!ReferenceReturnType
.isNull()) {
3139 // Loop variable creates a temporary. Suggest either to go with
3140 // non-reference loop variable to indicate a copy is made, or
3141 // the correct type to bind a const reference.
3142 SemaRef
.Diag(VD
->getLocation(),
3143 diag::warn_for_range_const_ref_binds_temp_built_from_ref
)
3144 << VD
<< VariableType
<< ReferenceReturnType
;
3145 QualType NonReferenceType
= VariableType
.getNonReferenceType();
3146 NonReferenceType
.removeLocalConst();
3147 QualType NewReferenceType
=
3148 SemaRef
.Context
.getLValueReferenceType(E
->getType().withConst());
3149 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_type_or_non_reference
)
3150 << NonReferenceType
<< NewReferenceType
<< VD
->getSourceRange()
3151 << FixItHint::CreateRemoval(VD
->getTypeSpecEndLoc());
3152 } else if (!VariableType
->isRValueReferenceType()) {
3153 // The range always returns a copy, so a temporary is always created.
3154 // Suggest removing the reference from the loop variable.
3155 // If the type is a rvalue reference do not warn since that changes the
3156 // semantic of the code.
3157 SemaRef
.Diag(VD
->getLocation(), diag::warn_for_range_ref_binds_ret_temp
)
3158 << VD
<< RangeInitType
;
3159 QualType NonReferenceType
= VariableType
.getNonReferenceType();
3160 NonReferenceType
.removeLocalConst();
3161 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_non_reference_type
)
3162 << NonReferenceType
<< VD
->getSourceRange()
3163 << FixItHint::CreateRemoval(VD
->getTypeSpecEndLoc());
3167 /// Determines whether the @p VariableType's declaration is a record with the
3168 /// clang::trivial_abi attribute.
3169 static bool hasTrivialABIAttr(QualType VariableType
) {
3170 if (CXXRecordDecl
*RD
= VariableType
->getAsCXXRecordDecl())
3171 return RD
->hasAttr
<TrivialABIAttr
>();
3176 // Warns when the loop variable can be changed to a reference type to
3177 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3178 // "for (const Foo &x : Range)" if this form does not make a copy.
3179 static void DiagnoseForRangeConstVariableCopies(Sema
&SemaRef
,
3180 const VarDecl
*VD
) {
3181 const Expr
*InitExpr
= VD
->getInit();
3185 QualType VariableType
= VD
->getType();
3187 if (const CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(InitExpr
)) {
3188 if (!CE
->getConstructor()->isCopyConstructor())
3190 } else if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(InitExpr
)) {
3191 if (CE
->getCastKind() != CK_LValueToRValue
)
3197 // Small trivially copyable types are cheap to copy. Do not emit the
3198 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3199 // (The function `getTypeSize` returns the size in bits.)
3200 ASTContext
&Ctx
= SemaRef
.Context
;
3201 if (Ctx
.getTypeSize(VariableType
) <= 64 * 8 &&
3202 (VariableType
.isTriviallyCopyableType(Ctx
) ||
3203 hasTrivialABIAttr(VariableType
)))
3206 // Suggest changing from a const variable to a const reference variable
3207 // if doing so will prevent a copy.
3208 SemaRef
.Diag(VD
->getLocation(), diag::warn_for_range_copy
)
3209 << VD
<< VariableType
;
3210 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_reference_type
)
3211 << SemaRef
.Context
.getLValueReferenceType(VariableType
)
3212 << VD
->getSourceRange()
3213 << FixItHint::CreateInsertion(VD
->getLocation(), "&");
3216 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3217 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3218 /// using "const foo x" to show that a copy is made
3219 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3220 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
3221 /// prevent the copy.
3222 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
3223 /// Suggest "const foo &x" to prevent the copy.
3224 static void DiagnoseForRangeVariableCopies(Sema
&SemaRef
,
3225 const CXXForRangeStmt
*ForStmt
) {
3226 if (SemaRef
.inTemplateInstantiation())
3229 if (SemaRef
.Diags
.isIgnored(
3230 diag::warn_for_range_const_ref_binds_temp_built_from_ref
,
3231 ForStmt
->getBeginLoc()) &&
3232 SemaRef
.Diags
.isIgnored(diag::warn_for_range_ref_binds_ret_temp
,
3233 ForStmt
->getBeginLoc()) &&
3234 SemaRef
.Diags
.isIgnored(diag::warn_for_range_copy
,
3235 ForStmt
->getBeginLoc())) {
3239 const VarDecl
*VD
= ForStmt
->getLoopVariable();
3243 QualType VariableType
= VD
->getType();
3245 if (VariableType
->isIncompleteType())
3248 const Expr
*InitExpr
= VD
->getInit();
3252 if (InitExpr
->getExprLoc().isMacroID())
3255 if (VariableType
->isReferenceType()) {
3256 DiagnoseForRangeReferenceVariableCopies(SemaRef
, VD
,
3257 ForStmt
->getRangeInit()->getType());
3258 } else if (VariableType
.isConstQualified()) {
3259 DiagnoseForRangeConstVariableCopies(SemaRef
, VD
);
3263 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
3264 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
3265 /// body cannot be performed until after the type of the range variable is
3267 StmtResult
Sema::FinishCXXForRangeStmt(Stmt
*S
, Stmt
*B
) {
3271 if (isa
<ObjCForCollectionStmt
>(S
))
3272 return FinishObjCForCollectionStmt(S
, B
);
3274 CXXForRangeStmt
*ForStmt
= cast
<CXXForRangeStmt
>(S
);
3275 ForStmt
->setBody(B
);
3277 DiagnoseEmptyStmtBody(ForStmt
->getRParenLoc(), B
,
3278 diag::warn_empty_range_based_for_body
);
3280 DiagnoseForRangeVariableCopies(*this, ForStmt
);
3285 StmtResult
Sema::ActOnGotoStmt(SourceLocation GotoLoc
,
3286 SourceLocation LabelLoc
,
3287 LabelDecl
*TheDecl
) {
3288 setFunctionHasBranchIntoScope();
3289 TheDecl
->markUsed(Context
);
3290 return new (Context
) GotoStmt(TheDecl
, GotoLoc
, LabelLoc
);
3294 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc
, SourceLocation StarLoc
,
3296 // Convert operand to void*
3297 if (!E
->isTypeDependent()) {
3298 QualType ETy
= E
->getType();
3299 QualType DestTy
= Context
.getPointerType(Context
.VoidTy
.withConst());
3300 ExprResult ExprRes
= E
;
3301 AssignConvertType ConvTy
=
3302 CheckSingleAssignmentConstraints(DestTy
, ExprRes
);
3303 if (ExprRes
.isInvalid())
3306 if (DiagnoseAssignmentResult(ConvTy
, StarLoc
, DestTy
, ETy
, E
, AA_Passing
))
3310 ExprResult ExprRes
= ActOnFinishFullExpr(E
, /*DiscardedValue*/ false);
3311 if (ExprRes
.isInvalid())
3315 setFunctionHasIndirectGoto();
3317 return new (Context
) IndirectGotoStmt(GotoLoc
, StarLoc
, E
);
3320 static void CheckJumpOutOfSEHFinally(Sema
&S
, SourceLocation Loc
,
3321 const Scope
&DestScope
) {
3322 if (!S
.CurrentSEHFinally
.empty() &&
3323 DestScope
.Contains(*S
.CurrentSEHFinally
.back())) {
3324 S
.Diag(Loc
, diag::warn_jump_out_of_seh_finally
);
3329 Sema::ActOnContinueStmt(SourceLocation ContinueLoc
, Scope
*CurScope
) {
3330 Scope
*S
= CurScope
->getContinueParent();
3332 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3333 return StmtError(Diag(ContinueLoc
, diag::err_continue_not_in_loop
));
3335 if (S
->isConditionVarScope()) {
3336 // We cannot 'continue;' from within a statement expression in the
3337 // initializer of a condition variable because we would jump past the
3338 // initialization of that variable.
3339 return StmtError(Diag(ContinueLoc
, diag::err_continue_from_cond_var_init
));
3341 CheckJumpOutOfSEHFinally(*this, ContinueLoc
, *S
);
3343 return new (Context
) ContinueStmt(ContinueLoc
);
3347 Sema::ActOnBreakStmt(SourceLocation BreakLoc
, Scope
*CurScope
) {
3348 Scope
*S
= CurScope
->getBreakParent();
3350 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3351 return StmtError(Diag(BreakLoc
, diag::err_break_not_in_loop_or_switch
));
3353 if (S
->isOpenMPLoopScope())
3354 return StmtError(Diag(BreakLoc
, diag::err_omp_loop_cannot_use_stmt
)
3356 CheckJumpOutOfSEHFinally(*this, BreakLoc
, *S
);
3358 return new (Context
) BreakStmt(BreakLoc
);
3361 /// Determine whether the given expression might be move-eligible or
3362 /// copy-elidable in either a (co_)return statement or throw expression,
3363 /// without considering function return type, if applicable.
3365 /// \param E The expression being returned from the function or block,
3366 /// being thrown, or being co_returned from a coroutine. This expression
3367 /// might be modified by the implementation.
3369 /// \param Mode Overrides detection of current language mode
3370 /// and uses the rules for C++23.
3372 /// \returns An aggregate which contains the Candidate and isMoveEligible
3373 /// and isCopyElidable methods. If Candidate is non-null, it means
3374 /// isMoveEligible() would be true under the most permissive language standard.
3375 Sema::NamedReturnInfo
Sema::getNamedReturnInfo(Expr
*&E
,
3376 SimplerImplicitMoveMode Mode
) {
3378 return NamedReturnInfo();
3379 // - in a return statement in a function [where] ...
3380 // ... the expression is the name of a non-volatile automatic object ...
3381 const auto *DR
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens());
3382 if (!DR
|| DR
->refersToEnclosingVariableOrCapture())
3383 return NamedReturnInfo();
3384 const auto *VD
= dyn_cast
<VarDecl
>(DR
->getDecl());
3386 return NamedReturnInfo();
3387 NamedReturnInfo Res
= getNamedReturnInfo(VD
);
3388 if (Res
.Candidate
&& !E
->isXValue() &&
3389 (Mode
== SimplerImplicitMoveMode::ForceOn
||
3390 (Mode
!= SimplerImplicitMoveMode::ForceOff
&&
3391 getLangOpts().CPlusPlus23
))) {
3392 E
= ImplicitCastExpr::Create(Context
, VD
->getType().getNonReferenceType(),
3393 CK_NoOp
, E
, nullptr, VK_XValue
,
3394 FPOptionsOverride());
3399 /// Determine whether the given NRVO candidate variable is move-eligible or
3400 /// copy-elidable, without considering function return type.
3402 /// \param VD The NRVO candidate variable.
3404 /// \returns An aggregate which contains the Candidate and isMoveEligible
3405 /// and isCopyElidable methods. If Candidate is non-null, it means
3406 /// isMoveEligible() would be true under the most permissive language standard.
3407 Sema::NamedReturnInfo
Sema::getNamedReturnInfo(const VarDecl
*VD
) {
3408 NamedReturnInfo Info
{VD
, NamedReturnInfo::MoveEligibleAndCopyElidable
};
3410 // C++20 [class.copy.elision]p3:
3411 // - in a return statement in a function with ...
3412 // (other than a function ... parameter)
3413 if (VD
->getKind() == Decl::ParmVar
)
3414 Info
.S
= NamedReturnInfo::MoveEligible
;
3415 else if (VD
->getKind() != Decl::Var
)
3416 return NamedReturnInfo();
3418 // (other than ... a catch-clause parameter)
3419 if (VD
->isExceptionVariable())
3420 Info
.S
= NamedReturnInfo::MoveEligible
;
3423 if (!VD
->hasLocalStorage())
3424 return NamedReturnInfo();
3426 // We don't want to implicitly move out of a __block variable during a return
3427 // because we cannot assume the variable will no longer be used.
3428 if (VD
->hasAttr
<BlocksAttr
>())
3429 return NamedReturnInfo();
3431 QualType VDType
= VD
->getType();
3432 if (VDType
->isObjectType()) {
3433 // C++17 [class.copy.elision]p3:
3434 // ...non-volatile automatic object...
3435 if (VDType
.isVolatileQualified())
3436 return NamedReturnInfo();
3437 } else if (VDType
->isRValueReferenceType()) {
3438 // C++20 [class.copy.elision]p3:
3439 // ...either a non-volatile object or an rvalue reference to a non-volatile
3441 QualType VDReferencedType
= VDType
.getNonReferenceType();
3442 if (VDReferencedType
.isVolatileQualified() ||
3443 !VDReferencedType
->isObjectType())
3444 return NamedReturnInfo();
3445 Info
.S
= NamedReturnInfo::MoveEligible
;
3447 return NamedReturnInfo();
3450 // Variables with higher required alignment than their type's ABI
3451 // alignment cannot use NRVO.
3452 if (!VD
->hasDependentAlignment() &&
3453 Context
.getDeclAlign(VD
) > Context
.getTypeAlignInChars(VDType
))
3454 Info
.S
= NamedReturnInfo::MoveEligible
;
3459 /// Updates given NamedReturnInfo's move-eligible and
3460 /// copy-elidable statuses, considering the function
3461 /// return type criteria as applicable to return statements.
3463 /// \param Info The NamedReturnInfo object to update.
3465 /// \param ReturnType This is the return type of the function.
3466 /// \returns The copy elision candidate, in case the initial return expression
3467 /// was copy elidable, or nullptr otherwise.
3468 const VarDecl
*Sema::getCopyElisionCandidate(NamedReturnInfo
&Info
,
3469 QualType ReturnType
) {
3470 if (!Info
.Candidate
)
3473 auto invalidNRVO
= [&] {
3474 Info
= NamedReturnInfo();
3478 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3479 // there is no point in allowing copy elision since we won't have it deduced
3480 // by the point the VardDecl is instantiated, which is the last chance we have
3481 // of deciding if the candidate is really copy elidable.
3482 if ((ReturnType
->getTypeClass() == Type::TypeClass::Auto
&&
3483 ReturnType
->isCanonicalUnqualified()) ||
3484 ReturnType
->isSpecificBuiltinType(BuiltinType::Dependent
))
3485 return invalidNRVO();
3487 if (!ReturnType
->isDependentType()) {
3488 // - in a return statement in a function with ...
3489 // ... a class return type ...
3490 if (!ReturnType
->isRecordType())
3491 return invalidNRVO();
3493 QualType VDType
= Info
.Candidate
->getType();
3494 // ... the same cv-unqualified type as the function return type ...
3495 // When considering moving this expression out, allow dissimilar types.
3496 if (!VDType
->isDependentType() &&
3497 !Context
.hasSameUnqualifiedType(ReturnType
, VDType
))
3498 Info
.S
= NamedReturnInfo::MoveEligible
;
3500 return Info
.isCopyElidable() ? Info
.Candidate
: nullptr;
3503 /// Verify that the initialization sequence that was picked for the
3504 /// first overload resolution is permissible under C++98.
3506 /// Reject (possibly converting) constructors not taking an rvalue reference,
3507 /// or user conversion operators which are not ref-qualified.
3509 VerifyInitializationSequenceCXX98(const Sema
&S
,
3510 const InitializationSequence
&Seq
) {
3511 const auto *Step
= llvm::find_if(Seq
.steps(), [](const auto &Step
) {
3512 return Step
.Kind
== InitializationSequence::SK_ConstructorInitialization
||
3513 Step
.Kind
== InitializationSequence::SK_UserConversion
;
3515 if (Step
!= Seq
.step_end()) {
3516 const auto *FD
= Step
->Function
.Function
;
3517 if (isa
<CXXConstructorDecl
>(FD
)
3518 ? !FD
->getParamDecl(0)->getType()->isRValueReferenceType()
3519 : cast
<CXXMethodDecl
>(FD
)->getRefQualifier() == RQ_None
)
3525 /// Perform the initialization of a potentially-movable value, which
3526 /// is the result of return value.
3528 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
3529 /// treat returned lvalues as rvalues in certain cases (to prefer move
3530 /// construction), then falls back to treating them as lvalues if that failed.
3531 ExprResult
Sema::PerformMoveOrCopyInitialization(
3532 const InitializedEntity
&Entity
, const NamedReturnInfo
&NRInfo
, Expr
*Value
,
3533 bool SupressSimplerImplicitMoves
) {
3534 if (getLangOpts().CPlusPlus
&&
3535 (!getLangOpts().CPlusPlus23
|| SupressSimplerImplicitMoves
) &&
3536 NRInfo
.isMoveEligible()) {
3537 ImplicitCastExpr
AsRvalue(ImplicitCastExpr::OnStack
, Value
->getType(),
3538 CK_NoOp
, Value
, VK_XValue
, FPOptionsOverride());
3539 Expr
*InitExpr
= &AsRvalue
;
3540 auto Kind
= InitializationKind::CreateCopy(Value
->getBeginLoc(),
3541 Value
->getBeginLoc());
3542 InitializationSequence
Seq(*this, Entity
, Kind
, InitExpr
);
3543 auto Res
= Seq
.getFailedOverloadResult();
3544 if ((Res
== OR_Success
|| Res
== OR_Deleted
) &&
3545 (getLangOpts().CPlusPlus11
||
3546 VerifyInitializationSequenceCXX98(*this, Seq
))) {
3547 // Promote "AsRvalue" to the heap, since we now need this
3548 // expression node to persist.
3550 ImplicitCastExpr::Create(Context
, Value
->getType(), CK_NoOp
, Value
,
3551 nullptr, VK_XValue
, FPOptionsOverride());
3552 // Complete type-checking the initialization of the return type
3553 // using the constructor we found.
3554 return Seq
.Perform(*this, Entity
, Kind
, Value
);
3557 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3558 // above, or overload resolution failed. Either way, we need to try
3559 // (again) now with the return value expression as written.
3560 return PerformCopyInitialization(Entity
, SourceLocation(), Value
);
3563 /// Determine whether the declared return type of the specified function
3564 /// contains 'auto'.
3565 static bool hasDeducedReturnType(FunctionDecl
*FD
) {
3566 const FunctionProtoType
*FPT
=
3567 FD
->getTypeSourceInfo()->getType()->castAs
<FunctionProtoType
>();
3568 return FPT
->getReturnType()->isUndeducedType();
3571 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3572 /// for capturing scopes.
3574 StmtResult
Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc
,
3576 NamedReturnInfo
&NRInfo
,
3577 bool SupressSimplerImplicitMoves
) {
3578 // If this is the first return we've seen, infer the return type.
3579 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3580 CapturingScopeInfo
*CurCap
= cast
<CapturingScopeInfo
>(getCurFunction());
3581 QualType FnRetType
= CurCap
->ReturnType
;
3582 LambdaScopeInfo
*CurLambda
= dyn_cast
<LambdaScopeInfo
>(CurCap
);
3583 if (CurLambda
&& CurLambda
->CallOperator
->getType().isNull())
3585 bool HasDeducedReturnType
=
3586 CurLambda
&& hasDeducedReturnType(CurLambda
->CallOperator
);
3588 if (ExprEvalContexts
.back().isDiscardedStatementContext() &&
3589 (HasDeducedReturnType
|| CurCap
->HasImplicitReturnType
)) {
3592 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
3595 RetValExp
= ER
.get();
3597 return ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
3598 /* NRVOCandidate=*/nullptr);
3601 if (HasDeducedReturnType
) {
3602 FunctionDecl
*FD
= CurLambda
->CallOperator
;
3603 // If we've already decided this lambda is invalid, e.g. because
3604 // we saw a `return` whose expression had an error, don't keep
3605 // trying to deduce its return type.
3606 if (FD
->isInvalidDecl())
3608 // In C++1y, the return type may involve 'auto'.
3609 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3610 if (CurCap
->ReturnType
.isNull())
3611 CurCap
->ReturnType
= FD
->getReturnType();
3613 AutoType
*AT
= CurCap
->ReturnType
->getContainedAutoType();
3614 assert(AT
&& "lost auto type from lambda return type");
3615 if (DeduceFunctionTypeFromReturnExpr(FD
, ReturnLoc
, RetValExp
, AT
)) {
3616 FD
->setInvalidDecl();
3617 // FIXME: preserve the ill-formed return expression.
3620 CurCap
->ReturnType
= FnRetType
= FD
->getReturnType();
3621 } else if (CurCap
->HasImplicitReturnType
) {
3622 // For blocks/lambdas with implicit return types, we check each return
3623 // statement individually, and deduce the common return type when the block
3624 // or lambda is completed.
3625 // FIXME: Fold this into the 'auto' codepath above.
3626 if (RetValExp
&& !isa
<InitListExpr
>(RetValExp
)) {
3627 ExprResult Result
= DefaultFunctionArrayLvalueConversion(RetValExp
);
3628 if (Result
.isInvalid())
3630 RetValExp
= Result
.get();
3632 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3633 // when deducing a return type for a lambda-expression (or by extension
3634 // for a block). These rules differ from the stated C++11 rules only in
3635 // that they remove top-level cv-qualifiers.
3636 if (!CurContext
->isDependentContext())
3637 FnRetType
= RetValExp
->getType().getUnqualifiedType();
3639 FnRetType
= CurCap
->ReturnType
= Context
.DependentTy
;
3642 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3643 // initializer list, because it is not an expression (even
3644 // though we represent it as one). We still deduce 'void'.
3645 Diag(ReturnLoc
, diag::err_lambda_return_init_list
)
3646 << RetValExp
->getSourceRange();
3649 FnRetType
= Context
.VoidTy
;
3652 // Although we'll properly infer the type of the block once it's completed,
3653 // make sure we provide a return type now for better error recovery.
3654 if (CurCap
->ReturnType
.isNull())
3655 CurCap
->ReturnType
= FnRetType
;
3657 const VarDecl
*NRVOCandidate
= getCopyElisionCandidate(NRInfo
, FnRetType
);
3659 if (auto *CurBlock
= dyn_cast
<BlockScopeInfo
>(CurCap
)) {
3660 if (CurBlock
->FunctionType
->castAs
<FunctionType
>()->getNoReturnAttr()) {
3661 Diag(ReturnLoc
, diag::err_noreturn_block_has_return_expr
);
3664 } else if (auto *CurRegion
= dyn_cast
<CapturedRegionScopeInfo
>(CurCap
)) {
3665 Diag(ReturnLoc
, diag::err_return_in_captured_stmt
) << CurRegion
->getRegionName();
3668 assert(CurLambda
&& "unknown kind of captured scope");
3669 if (CurLambda
->CallOperator
->getType()
3670 ->castAs
<FunctionType
>()
3671 ->getNoReturnAttr()) {
3672 Diag(ReturnLoc
, diag::err_noreturn_lambda_has_return_expr
);
3677 // Otherwise, verify that this result type matches the previous one. We are
3678 // pickier with blocks than for normal functions because we don't have GCC
3679 // compatibility to worry about here.
3680 if (FnRetType
->isDependentType()) {
3681 // Delay processing for now. TODO: there are lots of dependent
3682 // types we can conclusively prove aren't void.
3683 } else if (FnRetType
->isVoidType()) {
3684 if (RetValExp
&& !isa
<InitListExpr
>(RetValExp
) &&
3685 !(getLangOpts().CPlusPlus
&&
3686 (RetValExp
->isTypeDependent() ||
3687 RetValExp
->getType()->isVoidType()))) {
3688 if (!getLangOpts().CPlusPlus
&&
3689 RetValExp
->getType()->isVoidType())
3690 Diag(ReturnLoc
, diag::ext_return_has_void_expr
) << "literal" << 2;
3692 Diag(ReturnLoc
, diag::err_return_block_has_expr
);
3693 RetValExp
= nullptr;
3696 } else if (!RetValExp
) {
3697 return StmtError(Diag(ReturnLoc
, diag::err_block_return_missing_expr
));
3698 } else if (!RetValExp
->isTypeDependent()) {
3699 // we have a non-void block with an expression, continue checking
3701 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3702 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3705 // In C++ the return statement is handled via a copy initialization.
3706 // the C version of which boils down to CheckSingleAssignmentConstraints.
3707 InitializedEntity Entity
=
3708 InitializedEntity::InitializeResult(ReturnLoc
, FnRetType
);
3709 ExprResult Res
= PerformMoveOrCopyInitialization(
3710 Entity
, NRInfo
, RetValExp
, SupressSimplerImplicitMoves
);
3711 if (Res
.isInvalid()) {
3712 // FIXME: Cleanup temporaries here, anyway?
3715 RetValExp
= Res
.get();
3716 CheckReturnValExpr(RetValExp
, FnRetType
, ReturnLoc
);
3721 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
3724 RetValExp
= ER
.get();
3727 ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
, NRVOCandidate
);
3729 // If we need to check for the named return value optimization,
3730 // or if we need to infer the return type,
3731 // save the return statement in our scope for later processing.
3732 if (CurCap
->HasImplicitReturnType
|| NRVOCandidate
)
3733 FunctionScopes
.back()->Returns
.push_back(Result
);
3735 if (FunctionScopes
.back()->FirstReturnLoc
.isInvalid())
3736 FunctionScopes
.back()->FirstReturnLoc
= ReturnLoc
;
3738 if (auto *CurBlock
= dyn_cast
<BlockScopeInfo
>(CurCap
);
3739 CurBlock
&& CurCap
->HasImplicitReturnType
&& RetValExp
&&
3740 RetValExp
->containsErrors())
3741 CurBlock
->TheDecl
->setInvalidDecl();
3747 /// Marks all typedefs in all local classes in a type referenced.
3749 /// In a function like
3751 /// struct S { typedef int a; };
3755 /// the local type escapes and could be referenced in some TUs but not in
3756 /// others. Pretend that all local typedefs are always referenced, to not warn
3757 /// on this. This isn't necessary if f has internal linkage, or the typedef
3759 class LocalTypedefNameReferencer
3760 : public RecursiveASTVisitor
<LocalTypedefNameReferencer
> {
3762 LocalTypedefNameReferencer(Sema
&S
) : S(S
) {}
3763 bool VisitRecordType(const RecordType
*RT
);
3767 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType
*RT
) {
3768 auto *R
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl());
3769 if (!R
|| !R
->isLocalClass() || !R
->isLocalClass()->isExternallyVisible() ||
3770 R
->isDependentType())
3772 for (auto *TmpD
: R
->decls())
3773 if (auto *T
= dyn_cast
<TypedefNameDecl
>(TmpD
))
3774 if (T
->getAccess() != AS_private
|| R
->hasFriends())
3775 S
.MarkAnyDeclReferenced(T
->getLocation(), T
, /*OdrUse=*/false);
3780 TypeLoc
Sema::getReturnTypeLoc(FunctionDecl
*FD
) const {
3781 return FD
->getTypeSourceInfo()
3783 .getAsAdjusted
<FunctionProtoTypeLoc
>()
3787 /// Deduce the return type for a function from a returned expression, per
3788 /// C++1y [dcl.spec.auto]p6.
3789 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl
*FD
,
3790 SourceLocation ReturnLoc
,
3791 Expr
*RetExpr
, const AutoType
*AT
) {
3792 // If this is the conversion function for a lambda, we choose to deduce its
3793 // type from the corresponding call operator, not from the synthesized return
3794 // statement within it. See Sema::DeduceReturnType.
3795 if (isLambdaConversionOperator(FD
))
3798 if (RetExpr
&& isa
<InitListExpr
>(RetExpr
)) {
3799 // If the deduction is for a return statement and the initializer is
3800 // a braced-init-list, the program is ill-formed.
3801 Diag(RetExpr
->getExprLoc(),
3802 getCurLambda() ? diag::err_lambda_return_init_list
3803 : diag::err_auto_fn_return_init_list
)
3804 << RetExpr
->getSourceRange();
3808 if (FD
->isDependentContext()) {
3809 // C++1y [dcl.spec.auto]p12:
3810 // Return type deduction [...] occurs when the definition is
3811 // instantiated even if the function body contains a return
3812 // statement with a non-type-dependent operand.
3813 assert(AT
->isDeduced() && "should have deduced to dependent type");
3817 TypeLoc OrigResultType
= getReturnTypeLoc(FD
);
3818 // In the case of a return with no operand, the initializer is considered
3820 CXXScalarValueInitExpr
VoidVal(Context
.VoidTy
, nullptr, SourceLocation());
3822 // For a function with a deduced result type to return with omitted
3823 // expression, the result type as written must be 'auto' or
3824 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3826 if (!OrigResultType
.getType()->getAs
<AutoType
>()) {
3827 Diag(ReturnLoc
, diag::err_auto_fn_return_void_but_not_auto
)
3828 << OrigResultType
.getType();
3834 QualType Deduced
= AT
->getDeducedType();
3836 // Otherwise, [...] deduce a value for U using the rules of template
3837 // argument deduction.
3838 auto RetExprLoc
= RetExpr
->getExprLoc();
3839 TemplateDeductionInfo
Info(RetExprLoc
);
3840 SourceLocation TemplateSpecLoc
;
3841 if (RetExpr
->getType() == Context
.OverloadTy
) {
3842 auto FindResult
= OverloadExpr::find(RetExpr
);
3843 if (FindResult
.Expression
)
3844 TemplateSpecLoc
= FindResult
.Expression
->getNameLoc();
3846 TemplateSpecCandidateSet
FailedTSC(TemplateSpecLoc
);
3847 TemplateDeductionResult Res
= DeduceAutoType(
3848 OrigResultType
, RetExpr
, Deduced
, Info
, /*DependentDeduction=*/false,
3849 /*IgnoreConstraints=*/false, &FailedTSC
);
3850 if (Res
!= TDK_Success
&& FD
->isInvalidDecl())
3855 case TDK_AlreadyDiagnosed
:
3857 case TDK_Inconsistent
: {
3858 // If a function with a declared return type that contains a placeholder
3859 // type has multiple return statements, the return type is deduced for
3860 // each return statement. [...] if the type deduced is not the same in
3861 // each deduction, the program is ill-formed.
3862 const LambdaScopeInfo
*LambdaSI
= getCurLambda();
3863 if (LambdaSI
&& LambdaSI
->HasImplicitReturnType
)
3864 Diag(ReturnLoc
, diag::err_typecheck_missing_return_type_incompatible
)
3865 << Info
.SecondArg
<< Info
.FirstArg
<< true /*IsLambda*/;
3867 Diag(ReturnLoc
, diag::err_auto_fn_different_deductions
)
3868 << (AT
->isDecltypeAuto() ? 1 : 0) << Info
.SecondArg
3873 Diag(RetExpr
->getExprLoc(), diag::err_auto_fn_deduction_failure
)
3874 << OrigResultType
.getType() << RetExpr
->getType();
3875 FailedTSC
.NoteCandidates(*this, RetExprLoc
);
3880 // If a local type is part of the returned type, mark its fields as
3882 LocalTypedefNameReferencer(*this).TraverseType(RetExpr
->getType());
3884 // CUDA: Kernel function must have 'void' return type.
3885 if (getLangOpts().CUDA
&& FD
->hasAttr
<CUDAGlobalAttr
>() &&
3886 !Deduced
->isVoidType()) {
3887 Diag(FD
->getLocation(), diag::err_kern_type_not_void_return
)
3888 << FD
->getType() << FD
->getSourceRange();
3892 if (!FD
->isInvalidDecl() && AT
->getDeducedType() != Deduced
)
3893 // Update all declarations of the function to have the deduced return type.
3894 Context
.adjustDeducedFunctionResultType(FD
, Deduced
);
3900 Sema::ActOnReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
,
3902 // Correct typos, in case the containing function returns 'auto' and
3903 // RetValExp should determine the deduced type.
3904 ExprResult RetVal
= CorrectDelayedTyposInExpr(
3905 RetValExp
, nullptr, /*RecoverUncorrectedTypos=*/true);
3906 if (RetVal
.isInvalid())
3909 BuildReturnStmt(ReturnLoc
, RetVal
.get(), /*AllowRecovery=*/true);
3910 if (R
.isInvalid() || ExprEvalContexts
.back().isDiscardedStatementContext())
3914 const_cast<VarDecl
*>(cast
<ReturnStmt
>(R
.get())->getNRVOCandidate());
3916 CurScope
->updateNRVOCandidate(VD
);
3918 CheckJumpOutOfSEHFinally(*this, ReturnLoc
, *CurScope
->getFnParent());
3923 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema
&S
,
3925 if (!E
|| !S
.getLangOpts().CPlusPlus23
|| !S
.getLangOpts().MSVCCompat
)
3927 const Decl
*D
= E
->getReferencedDeclOfCallee();
3928 if (!D
|| !S
.SourceMgr
.isInSystemHeader(D
->getLocation()))
3930 for (const DeclContext
*DC
= D
->getDeclContext(); DC
; DC
= DC
->getParent()) {
3931 if (DC
->isStdNamespace())
3937 StmtResult
Sema::BuildReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
,
3938 bool AllowRecovery
) {
3939 // Check for unexpanded parameter packs.
3940 if (RetValExp
&& DiagnoseUnexpandedParameterPack(RetValExp
))
3943 // HACK: We suppress simpler implicit move here in msvc compatibility mode
3944 // just as a temporary work around, as the MSVC STL has issues with
3946 bool SupressSimplerImplicitMoves
=
3947 CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp
);
3948 NamedReturnInfo NRInfo
= getNamedReturnInfo(
3949 RetValExp
, SupressSimplerImplicitMoves
? SimplerImplicitMoveMode::ForceOff
3950 : SimplerImplicitMoveMode::Normal
);
3952 if (isa
<CapturingScopeInfo
>(getCurFunction()))
3953 return ActOnCapScopeReturnStmt(ReturnLoc
, RetValExp
, NRInfo
,
3954 SupressSimplerImplicitMoves
);
3957 QualType RelatedRetType
;
3958 const AttrVec
*Attrs
= nullptr;
3959 bool isObjCMethod
= false;
3961 if (const FunctionDecl
*FD
= getCurFunctionDecl()) {
3962 FnRetType
= FD
->getReturnType();
3964 Attrs
= &FD
->getAttrs();
3965 if (FD
->isNoReturn())
3966 Diag(ReturnLoc
, diag::warn_noreturn_function_has_return_expr
) << FD
;
3967 if (FD
->isMain() && RetValExp
)
3968 if (isa
<CXXBoolLiteralExpr
>(RetValExp
))
3969 Diag(ReturnLoc
, diag::warn_main_returns_bool_literal
)
3970 << RetValExp
->getSourceRange();
3971 if (FD
->hasAttr
<CmseNSEntryAttr
>() && RetValExp
) {
3972 if (const auto *RT
= dyn_cast
<RecordType
>(FnRetType
.getCanonicalType())) {
3973 if (RT
->getDecl()->isOrContainsUnion())
3974 Diag(RetValExp
->getBeginLoc(), diag::warn_cmse_nonsecure_union
) << 1;
3977 } else if (ObjCMethodDecl
*MD
= getCurMethodDecl()) {
3978 FnRetType
= MD
->getReturnType();
3979 isObjCMethod
= true;
3981 Attrs
= &MD
->getAttrs();
3982 if (MD
->hasRelatedResultType() && MD
->getClassInterface()) {
3983 // In the implementation of a method with a related return type, the
3984 // type used to type-check the validity of return statements within the
3985 // method body is a pointer to the type of the class being implemented.
3986 RelatedRetType
= Context
.getObjCInterfaceType(MD
->getClassInterface());
3987 RelatedRetType
= Context
.getObjCObjectPointerType(RelatedRetType
);
3989 } else // If we don't have a function/method context, bail.
3993 const auto *ATy
= dyn_cast
<ArrayType
>(RetValExp
->getType());
3994 if (ATy
&& ATy
->getElementType().isWebAssemblyReferenceType()) {
3995 Diag(ReturnLoc
, diag::err_wasm_table_art
) << 1;
4000 // C++1z: discarded return statements are not considered when deducing a
4002 if (ExprEvalContexts
.back().isDiscardedStatementContext() &&
4003 FnRetType
->getContainedAutoType()) {
4006 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4009 RetValExp
= ER
.get();
4011 return ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
4012 /* NRVOCandidate=*/nullptr);
4015 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
4017 if (getLangOpts().CPlusPlus14
) {
4018 if (AutoType
*AT
= FnRetType
->getContainedAutoType()) {
4019 FunctionDecl
*FD
= cast
<FunctionDecl
>(CurContext
);
4020 // If we've already decided this function is invalid, e.g. because
4021 // we saw a `return` whose expression had an error, don't keep
4022 // trying to deduce its return type.
4023 // (Some return values may be needlessly wrapped in RecoveryExpr).
4024 if (FD
->isInvalidDecl() ||
4025 DeduceFunctionTypeFromReturnExpr(FD
, ReturnLoc
, RetValExp
, AT
)) {
4026 FD
->setInvalidDecl();
4029 // The deduction failure is diagnosed and marked, try to recover.
4031 // Wrap return value with a recovery expression of the previous type.
4032 // If no deduction yet, use DependentTy.
4033 auto Recovery
= CreateRecoveryExpr(
4034 RetValExp
->getBeginLoc(), RetValExp
->getEndLoc(), RetValExp
,
4035 AT
->isDeduced() ? FnRetType
: QualType());
4036 if (Recovery
.isInvalid())
4038 RetValExp
= Recovery
.get();
4040 // Nothing to do: a ReturnStmt with no value is fine recovery.
4043 FnRetType
= FD
->getReturnType();
4047 const VarDecl
*NRVOCandidate
= getCopyElisionCandidate(NRInfo
, FnRetType
);
4049 bool HasDependentReturnType
= FnRetType
->isDependentType();
4051 ReturnStmt
*Result
= nullptr;
4052 if (FnRetType
->isVoidType()) {
4054 if (auto *ILE
= dyn_cast
<InitListExpr
>(RetValExp
)) {
4055 // We simply never allow init lists as the return value of void
4056 // functions. This is compatible because this was never allowed before,
4057 // so there's no legacy code to deal with.
4058 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4059 int FunctionKind
= 0;
4060 if (isa
<ObjCMethodDecl
>(CurDecl
))
4062 else if (isa
<CXXConstructorDecl
>(CurDecl
))
4064 else if (isa
<CXXDestructorDecl
>(CurDecl
))
4067 Diag(ReturnLoc
, diag::err_return_init_list
)
4068 << CurDecl
<< FunctionKind
<< RetValExp
->getSourceRange();
4070 // Preserve the initializers in the AST.
4071 RetValExp
= AllowRecovery
4072 ? CreateRecoveryExpr(ILE
->getLBraceLoc(),
4073 ILE
->getRBraceLoc(), ILE
->inits())
4076 } else if (!RetValExp
->isTypeDependent()) {
4077 // C99 6.8.6.4p1 (ext_ since GCC warns)
4078 unsigned D
= diag::ext_return_has_expr
;
4079 if (RetValExp
->getType()->isVoidType()) {
4080 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4081 if (isa
<CXXConstructorDecl
>(CurDecl
) ||
4082 isa
<CXXDestructorDecl
>(CurDecl
))
4083 D
= diag::err_ctor_dtor_returns_void
;
4085 D
= diag::ext_return_has_void_expr
;
4088 ExprResult Result
= RetValExp
;
4089 Result
= IgnoredValueConversions(Result
.get());
4090 if (Result
.isInvalid())
4092 RetValExp
= Result
.get();
4093 RetValExp
= ImpCastExprToType(RetValExp
,
4094 Context
.VoidTy
, CK_ToVoid
).get();
4096 // return of void in constructor/destructor is illegal in C++.
4097 if (D
== diag::err_ctor_dtor_returns_void
) {
4098 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4099 Diag(ReturnLoc
, D
) << CurDecl
<< isa
<CXXDestructorDecl
>(CurDecl
)
4100 << RetValExp
->getSourceRange();
4102 // return (some void expression); is legal in C++.
4103 else if (D
!= diag::ext_return_has_void_expr
||
4104 !getLangOpts().CPlusPlus
) {
4105 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4107 int FunctionKind
= 0;
4108 if (isa
<ObjCMethodDecl
>(CurDecl
))
4110 else if (isa
<CXXConstructorDecl
>(CurDecl
))
4112 else if (isa
<CXXDestructorDecl
>(CurDecl
))
4116 << CurDecl
<< FunctionKind
<< RetValExp
->getSourceRange();
4122 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4125 RetValExp
= ER
.get();
4129 Result
= ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
4130 /* NRVOCandidate=*/nullptr);
4131 } else if (!RetValExp
&& !HasDependentReturnType
) {
4132 FunctionDecl
*FD
= getCurFunctionDecl();
4134 if ((FD
&& FD
->isInvalidDecl()) || FnRetType
->containsErrors()) {
4135 // The intended return type might have been "void", so don't warn.
4136 } else if (getLangOpts().CPlusPlus11
&& FD
&& FD
->isConstexpr()) {
4137 // C++11 [stmt.return]p2
4138 Diag(ReturnLoc
, diag::err_constexpr_return_missing_expr
)
4139 << FD
<< FD
->isConsteval();
4140 FD
->setInvalidDecl();
4142 // C99 6.8.6.4p1 (ext_ since GCC warns)
4144 unsigned DiagID
= getLangOpts().C99
? diag::ext_return_missing_expr
4145 : diag::warn_return_missing_expr
;
4146 // Note that at this point one of getCurFunctionDecl() or
4147 // getCurMethodDecl() must be non-null (see above).
4148 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4149 "Not in a FunctionDecl or ObjCMethodDecl?");
4150 bool IsMethod
= FD
== nullptr;
4151 const NamedDecl
*ND
=
4152 IsMethod
? cast
<NamedDecl
>(getCurMethodDecl()) : cast
<NamedDecl
>(FD
);
4153 Diag(ReturnLoc
, DiagID
) << ND
<< IsMethod
;
4156 Result
= ReturnStmt::Create(Context
, ReturnLoc
, /* RetExpr=*/nullptr,
4157 /* NRVOCandidate=*/nullptr);
4159 assert(RetValExp
|| HasDependentReturnType
);
4160 QualType RetType
= RelatedRetType
.isNull() ? FnRetType
: RelatedRetType
;
4162 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4163 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4166 // In C++ the return statement is handled via a copy initialization,
4167 // the C version of which boils down to CheckSingleAssignmentConstraints.
4168 if (!HasDependentReturnType
&& !RetValExp
->isTypeDependent()) {
4169 // we have a non-void function with an expression, continue checking
4170 InitializedEntity Entity
=
4171 InitializedEntity::InitializeResult(ReturnLoc
, RetType
);
4172 ExprResult Res
= PerformMoveOrCopyInitialization(
4173 Entity
, NRInfo
, RetValExp
, SupressSimplerImplicitMoves
);
4174 if (Res
.isInvalid() && AllowRecovery
)
4175 Res
= CreateRecoveryExpr(RetValExp
->getBeginLoc(),
4176 RetValExp
->getEndLoc(), RetValExp
, RetType
);
4177 if (Res
.isInvalid()) {
4178 // FIXME: Clean up temporaries here anyway?
4181 RetValExp
= Res
.getAs
<Expr
>();
4183 // If we have a related result type, we need to implicitly
4184 // convert back to the formal result type. We can't pretend to
4185 // initialize the result again --- we might end double-retaining
4186 // --- so instead we initialize a notional temporary.
4187 if (!RelatedRetType
.isNull()) {
4188 Entity
= InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
4190 Res
= PerformCopyInitialization(Entity
, ReturnLoc
, RetValExp
);
4191 if (Res
.isInvalid()) {
4192 // FIXME: Clean up temporaries here anyway?
4195 RetValExp
= Res
.getAs
<Expr
>();
4198 CheckReturnValExpr(RetValExp
, FnRetType
, ReturnLoc
, isObjCMethod
, Attrs
,
4199 getCurFunctionDecl());
4204 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4207 RetValExp
= ER
.get();
4209 Result
= ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
, NRVOCandidate
);
4212 // If we need to check for the named return value optimization, save the
4213 // return statement in our scope for later processing.
4214 if (Result
->getNRVOCandidate())
4215 FunctionScopes
.back()->Returns
.push_back(Result
);
4217 if (FunctionScopes
.back()->FirstReturnLoc
.isInvalid())
4218 FunctionScopes
.back()->FirstReturnLoc
= ReturnLoc
;
4224 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc
,
4225 SourceLocation RParen
, Decl
*Parm
,
4227 VarDecl
*Var
= cast_or_null
<VarDecl
>(Parm
);
4228 if (Var
&& Var
->isInvalidDecl())
4231 return new (Context
) ObjCAtCatchStmt(AtLoc
, RParen
, Var
, Body
);
4235 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc
, Stmt
*Body
) {
4236 return new (Context
) ObjCAtFinallyStmt(AtLoc
, Body
);
4240 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc
, Stmt
*Try
,
4241 MultiStmtArg CatchStmts
, Stmt
*Finally
) {
4242 if (!getLangOpts().ObjCExceptions
)
4243 Diag(AtLoc
, diag::err_objc_exceptions_disabled
) << "@try";
4245 // Objective-C try is incompatible with SEH __try.
4246 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4247 if (FSI
->FirstSEHTryLoc
.isValid()) {
4248 Diag(AtLoc
, diag::err_mixing_cxx_try_seh_try
) << 1;
4249 Diag(FSI
->FirstSEHTryLoc
, diag::note_conflicting_try_here
) << "'__try'";
4252 FSI
->setHasObjCTry(AtLoc
);
4253 unsigned NumCatchStmts
= CatchStmts
.size();
4254 return ObjCAtTryStmt::Create(Context
, AtLoc
, Try
, CatchStmts
.data(),
4255 NumCatchStmts
, Finally
);
4258 StmtResult
Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
) {
4260 ExprResult Result
= DefaultLvalueConversion(Throw
);
4261 if (Result
.isInvalid())
4264 Result
= ActOnFinishFullExpr(Result
.get(), /*DiscardedValue*/ false);
4265 if (Result
.isInvalid())
4267 Throw
= Result
.get();
4269 QualType ThrowType
= Throw
->getType();
4270 // Make sure the expression type is an ObjC pointer or "void *".
4271 if (!ThrowType
->isDependentType() &&
4272 !ThrowType
->isObjCObjectPointerType()) {
4273 const PointerType
*PT
= ThrowType
->getAs
<PointerType
>();
4274 if (!PT
|| !PT
->getPointeeType()->isVoidType())
4275 return StmtError(Diag(AtLoc
, diag::err_objc_throw_expects_object
)
4276 << Throw
->getType() << Throw
->getSourceRange());
4280 return new (Context
) ObjCAtThrowStmt(AtLoc
, Throw
);
4284 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
,
4286 if (!getLangOpts().ObjCExceptions
)
4287 Diag(AtLoc
, diag::err_objc_exceptions_disabled
) << "@throw";
4290 // @throw without an expression designates a rethrow (which must occur
4291 // in the context of an @catch clause).
4292 Scope
*AtCatchParent
= CurScope
;
4293 while (AtCatchParent
&& !AtCatchParent
->isAtCatchScope())
4294 AtCatchParent
= AtCatchParent
->getParent();
4296 return StmtError(Diag(AtLoc
, diag::err_rethrow_used_outside_catch
));
4298 return BuildObjCAtThrowStmt(AtLoc
, Throw
);
4302 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc
, Expr
*operand
) {
4303 ExprResult result
= DefaultLvalueConversion(operand
);
4304 if (result
.isInvalid())
4306 operand
= result
.get();
4308 // Make sure the expression type is an ObjC pointer or "void *".
4309 QualType type
= operand
->getType();
4310 if (!type
->isDependentType() &&
4311 !type
->isObjCObjectPointerType()) {
4312 const PointerType
*pointerType
= type
->getAs
<PointerType
>();
4313 if (!pointerType
|| !pointerType
->getPointeeType()->isVoidType()) {
4314 if (getLangOpts().CPlusPlus
) {
4315 if (RequireCompleteType(atLoc
, type
,
4316 diag::err_incomplete_receiver_type
))
4317 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4318 << type
<< operand
->getSourceRange();
4320 ExprResult result
= PerformContextuallyConvertToObjCPointer(operand
);
4321 if (result
.isInvalid())
4323 if (!result
.isUsable())
4324 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4325 << type
<< operand
->getSourceRange();
4327 operand
= result
.get();
4329 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4330 << type
<< operand
->getSourceRange();
4335 // The operand to @synchronized is a full-expression.
4336 return ActOnFinishFullExpr(operand
, /*DiscardedValue*/ false);
4340 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc
, Expr
*SyncExpr
,
4342 // We can't jump into or indirect-jump out of a @synchronized block.
4343 setFunctionHasBranchProtectedScope();
4344 return new (Context
) ObjCAtSynchronizedStmt(AtLoc
, SyncExpr
, SyncBody
);
4347 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
4348 /// and creates a proper catch handler from them.
4350 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc
, Decl
*ExDecl
,
4351 Stmt
*HandlerBlock
) {
4352 // There's nothing to test that ActOnExceptionDecl didn't already test.
4353 return new (Context
)
4354 CXXCatchStmt(CatchLoc
, cast_or_null
<VarDecl
>(ExDecl
), HandlerBlock
);
4358 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc
, Stmt
*Body
) {
4359 setFunctionHasBranchProtectedScope();
4360 return new (Context
) ObjCAutoreleasePoolStmt(AtLoc
, Body
);
4364 class CatchHandlerType
{
4366 unsigned IsPointer
: 1;
4368 // This is a special constructor to be used only with DenseMapInfo's
4369 // getEmptyKey() and getTombstoneKey() functions.
4370 friend struct llvm::DenseMapInfo
<CatchHandlerType
>;
4371 enum Unique
{ ForDenseMap
};
4372 CatchHandlerType(QualType QT
, Unique
) : QT(QT
), IsPointer(false) {}
4375 /// Used when creating a CatchHandlerType from a handler type; will determine
4376 /// whether the type is a pointer or reference and will strip off the top
4377 /// level pointer and cv-qualifiers.
4378 CatchHandlerType(QualType Q
) : QT(Q
), IsPointer(false) {
4379 if (QT
->isPointerType())
4382 QT
= QT
.getUnqualifiedType();
4383 if (IsPointer
|| QT
->isReferenceType())
4384 QT
= QT
->getPointeeType();
4387 /// Used when creating a CatchHandlerType from a base class type; pretends the
4388 /// type passed in had the pointer qualifier, does not need to get an
4389 /// unqualified type.
4390 CatchHandlerType(QualType QT
, bool IsPointer
)
4391 : QT(QT
), IsPointer(IsPointer
) {}
4393 QualType
underlying() const { return QT
; }
4394 bool isPointer() const { return IsPointer
; }
4396 friend bool operator==(const CatchHandlerType
&LHS
,
4397 const CatchHandlerType
&RHS
) {
4398 // If the pointer qualification does not match, we can return early.
4399 if (LHS
.IsPointer
!= RHS
.IsPointer
)
4401 // Otherwise, check the underlying type without cv-qualifiers.
4402 return LHS
.QT
== RHS
.QT
;
4408 template <> struct DenseMapInfo
<CatchHandlerType
> {
4409 static CatchHandlerType
getEmptyKey() {
4410 return CatchHandlerType(DenseMapInfo
<QualType
>::getEmptyKey(),
4411 CatchHandlerType::ForDenseMap
);
4414 static CatchHandlerType
getTombstoneKey() {
4415 return CatchHandlerType(DenseMapInfo
<QualType
>::getTombstoneKey(),
4416 CatchHandlerType::ForDenseMap
);
4419 static unsigned getHashValue(const CatchHandlerType
&Base
) {
4420 return DenseMapInfo
<QualType
>::getHashValue(Base
.underlying());
4423 static bool isEqual(const CatchHandlerType
&LHS
,
4424 const CatchHandlerType
&RHS
) {
4431 class CatchTypePublicBases
{
4432 const llvm::DenseMap
<QualType
, CXXCatchStmt
*> &TypesToCheck
;
4434 CXXCatchStmt
*FoundHandler
;
4435 QualType FoundHandlerType
;
4436 QualType TestAgainstType
;
4439 CatchTypePublicBases(const llvm::DenseMap
<QualType
, CXXCatchStmt
*> &T
,
4441 : TypesToCheck(T
), FoundHandler(nullptr), TestAgainstType(QT
) {}
4443 CXXCatchStmt
*getFoundHandler() const { return FoundHandler
; }
4444 QualType
getFoundHandlerType() const { return FoundHandlerType
; }
4446 bool operator()(const CXXBaseSpecifier
*S
, CXXBasePath
&) {
4447 if (S
->getAccessSpecifier() == AccessSpecifier::AS_public
) {
4448 QualType Check
= S
->getType().getCanonicalType();
4449 const auto &M
= TypesToCheck
;
4450 auto I
= M
.find(Check
);
4452 // We're pretty sure we found what we need to find. However, we still
4453 // need to make sure that we properly compare for pointers and
4454 // references, to handle cases like:
4456 // } catch (Base *b) {
4457 // } catch (Derived &d) {
4460 // where there is a qualification mismatch that disqualifies this
4461 // handler as a potential problem.
4462 if (I
->second
->getCaughtType()->isPointerType() ==
4463 TestAgainstType
->isPointerType()) {
4464 FoundHandler
= I
->second
;
4465 FoundHandlerType
= Check
;
4475 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4476 /// handlers and creates a try statement from them.
4477 StmtResult
Sema::ActOnCXXTryBlock(SourceLocation TryLoc
, Stmt
*TryBlock
,
4478 ArrayRef
<Stmt
*> Handlers
) {
4479 const llvm::Triple
&T
= Context
.getTargetInfo().getTriple();
4480 const bool IsOpenMPGPUTarget
=
4481 getLangOpts().OpenMPIsTargetDevice
&& (T
.isNVPTX() || T
.isAMDGCN());
4482 // Don't report an error if 'try' is used in system headers or in an OpenMP
4483 // target region compiled for a GPU architecture.
4484 if (!IsOpenMPGPUTarget
&& !getLangOpts().CXXExceptions
&&
4485 !getSourceManager().isInSystemHeader(TryLoc
) && !getLangOpts().CUDA
) {
4486 // Delay error emission for the OpenMP device code.
4487 targetDiag(TryLoc
, diag::err_exceptions_disabled
) << "try";
4490 // In OpenMP target regions, we assume that catch is never reached on GPU
4492 if (IsOpenMPGPUTarget
)
4493 targetDiag(TryLoc
, diag::warn_try_not_valid_on_target
) << T
.str();
4495 // Exceptions aren't allowed in CUDA device code.
4496 if (getLangOpts().CUDA
)
4497 CUDADiagIfDeviceCode(TryLoc
, diag::err_cuda_device_exceptions
)
4498 << "try" << CurrentCUDATarget();
4500 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4501 Diag(TryLoc
, diag::err_omp_simd_region_cannot_use_stmt
) << "try";
4503 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4505 // C++ try is incompatible with SEH __try.
4506 if (!getLangOpts().Borland
&& FSI
->FirstSEHTryLoc
.isValid()) {
4507 Diag(TryLoc
, diag::err_mixing_cxx_try_seh_try
) << 0;
4508 Diag(FSI
->FirstSEHTryLoc
, diag::note_conflicting_try_here
) << "'__try'";
4511 const unsigned NumHandlers
= Handlers
.size();
4512 assert(!Handlers
.empty() &&
4513 "The parser shouldn't call this if there are no handlers.");
4515 llvm::DenseMap
<QualType
, CXXCatchStmt
*> HandledBaseTypes
;
4516 llvm::DenseMap
<CatchHandlerType
, CXXCatchStmt
*> HandledTypes
;
4517 for (unsigned i
= 0; i
< NumHandlers
; ++i
) {
4518 CXXCatchStmt
*H
= cast
<CXXCatchStmt
>(Handlers
[i
]);
4520 // Diagnose when the handler is a catch-all handler, but it isn't the last
4521 // handler for the try block. [except.handle]p5. Also, skip exception
4522 // declarations that are invalid, since we can't usefully report on them.
4523 if (!H
->getExceptionDecl()) {
4524 if (i
< NumHandlers
- 1)
4525 return StmtError(Diag(H
->getBeginLoc(), diag::err_early_catch_all
));
4527 } else if (H
->getExceptionDecl()->isInvalidDecl())
4530 // Walk the type hierarchy to diagnose when this type has already been
4531 // handled (duplication), or cannot be handled (derivation inversion). We
4532 // ignore top-level cv-qualifiers, per [except.handle]p3
4533 CatchHandlerType HandlerCHT
= H
->getCaughtType().getCanonicalType();
4535 // We can ignore whether the type is a reference or a pointer; we need the
4536 // underlying declaration type in order to get at the underlying record
4537 // decl, if there is one.
4538 QualType Underlying
= HandlerCHT
.underlying();
4539 if (auto *RD
= Underlying
->getAsCXXRecordDecl()) {
4540 if (!RD
->hasDefinition())
4542 // Check that none of the public, unambiguous base classes are in the
4543 // map ([except.handle]p1). Give the base classes the same pointer
4544 // qualification as the original type we are basing off of. This allows
4545 // comparison against the handler type using the same top-level pointer
4546 // as the original type.
4548 Paths
.setOrigin(RD
);
4549 CatchTypePublicBases
CTPB(HandledBaseTypes
,
4550 H
->getCaughtType().getCanonicalType());
4551 if (RD
->lookupInBases(CTPB
, Paths
)) {
4552 const CXXCatchStmt
*Problem
= CTPB
.getFoundHandler();
4553 if (!Paths
.isAmbiguous(
4554 CanQualType::CreateUnsafe(CTPB
.getFoundHandlerType()))) {
4555 Diag(H
->getExceptionDecl()->getTypeSpecStartLoc(),
4556 diag::warn_exception_caught_by_earlier_handler
)
4557 << H
->getCaughtType();
4558 Diag(Problem
->getExceptionDecl()->getTypeSpecStartLoc(),
4559 diag::note_previous_exception_handler
)
4560 << Problem
->getCaughtType();
4563 // Strip the qualifiers here because we're going to be comparing this
4564 // type to the base type specifiers of a class, which are ignored in a
4565 // base specifier per [class.derived.general]p2.
4566 HandledBaseTypes
[Underlying
.getUnqualifiedType()] = H
;
4569 // Add the type the list of ones we have handled; diagnose if we've already
4571 auto R
= HandledTypes
.insert(
4572 std::make_pair(H
->getCaughtType().getCanonicalType(), H
));
4574 const CXXCatchStmt
*Problem
= R
.first
->second
;
4575 Diag(H
->getExceptionDecl()->getTypeSpecStartLoc(),
4576 diag::warn_exception_caught_by_earlier_handler
)
4577 << H
->getCaughtType();
4578 Diag(Problem
->getExceptionDecl()->getTypeSpecStartLoc(),
4579 diag::note_previous_exception_handler
)
4580 << Problem
->getCaughtType();
4584 FSI
->setHasCXXTry(TryLoc
);
4586 return CXXTryStmt::Create(Context
, TryLoc
, cast
<CompoundStmt
>(TryBlock
),
4590 StmtResult
Sema::ActOnSEHTryBlock(bool IsCXXTry
, SourceLocation TryLoc
,
4591 Stmt
*TryBlock
, Stmt
*Handler
) {
4592 assert(TryBlock
&& Handler
);
4594 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4596 // SEH __try is incompatible with C++ try. Borland appears to support this,
4598 if (!getLangOpts().Borland
) {
4599 if (FSI
->FirstCXXOrObjCTryLoc
.isValid()) {
4600 Diag(TryLoc
, diag::err_mixing_cxx_try_seh_try
) << FSI
->FirstTryType
;
4601 Diag(FSI
->FirstCXXOrObjCTryLoc
, diag::note_conflicting_try_here
)
4602 << (FSI
->FirstTryType
== sema::FunctionScopeInfo::TryLocIsCXX
4608 FSI
->setHasSEHTry(TryLoc
);
4610 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4611 // track if they use SEH.
4612 DeclContext
*DC
= CurContext
;
4613 while (DC
&& !DC
->isFunctionOrMethod())
4614 DC
= DC
->getParent();
4615 FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(DC
);
4617 FD
->setUsesSEHTry(true);
4619 Diag(TryLoc
, diag::err_seh_try_outside_functions
);
4621 // Reject __try on unsupported targets.
4622 if (!Context
.getTargetInfo().isSEHTrySupported())
4623 Diag(TryLoc
, diag::err_seh_try_unsupported
);
4625 return SEHTryStmt::Create(Context
, IsCXXTry
, TryLoc
, TryBlock
, Handler
);
4628 StmtResult
Sema::ActOnSEHExceptBlock(SourceLocation Loc
, Expr
*FilterExpr
,
4630 assert(FilterExpr
&& Block
);
4631 QualType FTy
= FilterExpr
->getType();
4632 if (!FTy
->isIntegerType() && !FTy
->isDependentType()) {
4634 Diag(FilterExpr
->getExprLoc(), diag::err_filter_expression_integral
)
4637 return SEHExceptStmt::Create(Context
, Loc
, FilterExpr
, Block
);
4640 void Sema::ActOnStartSEHFinallyBlock() {
4641 CurrentSEHFinally
.push_back(CurScope
);
4644 void Sema::ActOnAbortSEHFinallyBlock() {
4645 CurrentSEHFinally
.pop_back();
4648 StmtResult
Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc
, Stmt
*Block
) {
4650 CurrentSEHFinally
.pop_back();
4651 return SEHFinallyStmt::Create(Context
, Loc
, Block
);
4655 Sema::ActOnSEHLeaveStmt(SourceLocation Loc
, Scope
*CurScope
) {
4656 Scope
*SEHTryParent
= CurScope
;
4657 while (SEHTryParent
&& !SEHTryParent
->isSEHTryScope())
4658 SEHTryParent
= SEHTryParent
->getParent();
4660 return StmtError(Diag(Loc
, diag::err_ms___leave_not_in___try
));
4661 CheckJumpOutOfSEHFinally(*this, Loc
, *SEHTryParent
);
4663 return new (Context
) SEHLeaveStmt(Loc
);
4666 StmtResult
Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc
,
4668 NestedNameSpecifierLoc QualifierLoc
,
4669 DeclarationNameInfo NameInfo
,
4672 return new (Context
) MSDependentExistsStmt(KeywordLoc
, IsIfExists
,
4673 QualifierLoc
, NameInfo
,
4674 cast
<CompoundStmt
>(Nested
));
4678 StmtResult
Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc
,
4681 UnqualifiedId
&Name
,
4683 return BuildMSDependentExistsStmt(KeywordLoc
, IsIfExists
,
4684 SS
.getWithLocInContext(Context
),
4685 GetNameFromUnqualifiedId(Name
),
4690 Sema::CreateCapturedStmtRecordDecl(CapturedDecl
*&CD
, SourceLocation Loc
,
4691 unsigned NumParams
) {
4692 DeclContext
*DC
= CurContext
;
4693 while (!(DC
->isFunctionOrMethod() || DC
->isRecord() || DC
->isFileContext()))
4694 DC
= DC
->getParent();
4696 RecordDecl
*RD
= nullptr;
4697 if (getLangOpts().CPlusPlus
)
4698 RD
= CXXRecordDecl::Create(Context
, TagTypeKind::Struct
, DC
, Loc
, Loc
,
4701 RD
= RecordDecl::Create(Context
, TagTypeKind::Struct
, DC
, Loc
, Loc
,
4704 RD
->setCapturedRecord();
4707 RD
->startDefinition();
4709 assert(NumParams
> 0 && "CapturedStmt requires context parameter");
4710 CD
= CapturedDecl::Create(Context
, CurContext
, NumParams
);
4716 buildCapturedStmtCaptureList(Sema
&S
, CapturedRegionScopeInfo
*RSI
,
4717 SmallVectorImpl
<CapturedStmt::Capture
> &Captures
,
4718 SmallVectorImpl
<Expr
*> &CaptureInits
) {
4719 for (const sema::Capture
&Cap
: RSI
->Captures
) {
4720 if (Cap
.isInvalid())
4723 // Form the initializer for the capture.
4724 ExprResult Init
= S
.BuildCaptureInit(Cap
, Cap
.getLocation(),
4725 RSI
->CapRegionKind
== CR_OpenMP
);
4727 // FIXME: Bail out now if the capture is not used and the initializer has
4730 // Create a field for this capture.
4731 FieldDecl
*Field
= S
.BuildCaptureField(RSI
->TheRecordDecl
, Cap
);
4733 // Add the capture to our list of captures.
4734 if (Cap
.isThisCapture()) {
4735 Captures
.push_back(CapturedStmt::Capture(Cap
.getLocation(),
4736 CapturedStmt::VCK_This
));
4737 } else if (Cap
.isVLATypeCapture()) {
4739 CapturedStmt::Capture(Cap
.getLocation(), CapturedStmt::VCK_VLAType
));
4741 assert(Cap
.isVariableCapture() && "unknown kind of capture");
4743 if (S
.getLangOpts().OpenMP
&& RSI
->CapRegionKind
== CR_OpenMP
)
4744 S
.setOpenMPCaptureKind(Field
, Cap
.getVariable(), RSI
->OpenMPLevel
);
4746 Captures
.push_back(CapturedStmt::Capture(
4748 Cap
.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4749 : CapturedStmt::VCK_ByCopy
,
4750 cast
<VarDecl
>(Cap
.getVariable())));
4752 CaptureInits
.push_back(Init
.get());
4757 void Sema::ActOnCapturedRegionStart(SourceLocation Loc
, Scope
*CurScope
,
4758 CapturedRegionKind Kind
,
4759 unsigned NumParams
) {
4760 CapturedDecl
*CD
= nullptr;
4761 RecordDecl
*RD
= CreateCapturedStmtRecordDecl(CD
, Loc
, NumParams
);
4763 // Build the context parameter
4764 DeclContext
*DC
= CapturedDecl::castToDeclContext(CD
);
4765 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4766 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
));
4768 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4769 ImplicitParamKind::CapturedContext
);
4772 CD
->setContextParam(0, Param
);
4774 // Enter the capturing scope for this captured region.
4775 PushCapturedRegionScope(CurScope
, CD
, RD
, Kind
);
4778 PushDeclContext(CurScope
, CD
);
4782 PushExpressionEvaluationContext(
4783 ExpressionEvaluationContext::PotentiallyEvaluated
);
4784 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
= false;
4787 void Sema::ActOnCapturedRegionStart(SourceLocation Loc
, Scope
*CurScope
,
4788 CapturedRegionKind Kind
,
4789 ArrayRef
<CapturedParamNameType
> Params
,
4790 unsigned OpenMPCaptureLevel
) {
4791 CapturedDecl
*CD
= nullptr;
4792 RecordDecl
*RD
= CreateCapturedStmtRecordDecl(CD
, Loc
, Params
.size());
4794 // Build the context parameter
4795 DeclContext
*DC
= CapturedDecl::castToDeclContext(CD
);
4796 bool ContextIsFound
= false;
4797 unsigned ParamNum
= 0;
4798 for (ArrayRef
<CapturedParamNameType
>::iterator I
= Params
.begin(),
4800 I
!= E
; ++I
, ++ParamNum
) {
4801 if (I
->second
.isNull()) {
4802 assert(!ContextIsFound
&&
4803 "null type has been found already for '__context' parameter");
4804 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4805 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
))
4809 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4810 ImplicitParamKind::CapturedContext
);
4812 CD
->setContextParam(ParamNum
, Param
);
4813 ContextIsFound
= true;
4815 IdentifierInfo
*ParamName
= &Context
.Idents
.get(I
->first
);
4817 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, I
->second
,
4818 ImplicitParamKind::CapturedContext
);
4820 CD
->setParam(ParamNum
, Param
);
4823 assert(ContextIsFound
&& "no null type for '__context' parameter");
4824 if (!ContextIsFound
) {
4825 // Add __context implicitly if it is not specified.
4826 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4827 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
));
4829 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4830 ImplicitParamKind::CapturedContext
);
4832 CD
->setContextParam(ParamNum
, Param
);
4834 // Enter the capturing scope for this captured region.
4835 PushCapturedRegionScope(CurScope
, CD
, RD
, Kind
, OpenMPCaptureLevel
);
4838 PushDeclContext(CurScope
, CD
);
4842 PushExpressionEvaluationContext(
4843 ExpressionEvaluationContext::PotentiallyEvaluated
);
4846 void Sema::ActOnCapturedRegionError() {
4847 DiscardCleanupsInEvaluationContext();
4848 PopExpressionEvaluationContext();
4850 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo();
4851 CapturedRegionScopeInfo
*RSI
= cast
<CapturedRegionScopeInfo
>(ScopeRAII
.get());
4853 RecordDecl
*Record
= RSI
->TheRecordDecl
;
4854 Record
->setInvalidDecl();
4856 SmallVector
<Decl
*, 4> Fields(Record
->fields());
4857 ActOnFields(/*Scope=*/nullptr, Record
->getLocation(), Record
, Fields
,
4858 SourceLocation(), SourceLocation(), ParsedAttributesView());
4861 StmtResult
Sema::ActOnCapturedRegionEnd(Stmt
*S
) {
4862 // Leave the captured scope before we start creating captures in the
4864 DiscardCleanupsInEvaluationContext();
4865 PopExpressionEvaluationContext();
4867 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo();
4868 CapturedRegionScopeInfo
*RSI
= cast
<CapturedRegionScopeInfo
>(ScopeRAII
.get());
4870 SmallVector
<CapturedStmt::Capture
, 4> Captures
;
4871 SmallVector
<Expr
*, 4> CaptureInits
;
4872 if (buildCapturedStmtCaptureList(*this, RSI
, Captures
, CaptureInits
))
4875 CapturedDecl
*CD
= RSI
->TheCapturedDecl
;
4876 RecordDecl
*RD
= RSI
->TheRecordDecl
;
4878 CapturedStmt
*Res
= CapturedStmt::Create(
4879 getASTContext(), S
, static_cast<CapturedRegionKind
>(RSI
->CapRegionKind
),
4880 Captures
, CaptureInits
, CD
, RD
);
4882 CD
->setBody(Res
->getCapturedStmt());
4883 RD
->completeDefinition();