1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/SmallVector.h"
42 using namespace clang;
45 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
50 /*DiscardedValue*/ true);
54 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
55 // void expression for its side effects. Conversion to void allows any
56 // operand, even incomplete types.
58 // Same thing in for stmt first clause (when expr) and third clause.
59 return StmtResult(FE.getAs<Stmt>());
63 StmtResult Sema::ActOnExprStmtError() {
64 DiscardCleanupsInEvaluationContext();
68 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
69 bool HasLeadingEmptyMacro) {
70 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
73 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
74 SourceLocation EndLoc) {
75 DeclGroupRef DG = dg.get();
77 // If we have an invalid decl, just return an error.
78 if (DG.isNull()) return StmtError();
80 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
83 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
84 DeclGroupRef DG = dg.get();
86 // If we don't have a declaration, or we have an invalid declaration,
88 if (DG.isNull() || !DG.isSingleDecl())
91 Decl *decl = DG.getSingleDecl();
92 if (!decl || decl->isInvalidDecl())
95 // Only variable declarations are permitted.
96 VarDecl *var = dyn_cast<VarDecl>(decl);
98 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
99 decl->setInvalidDecl();
103 // foreach variables are never actually initialized in the way that
104 // the parser came up with.
105 var->setInit(nullptr);
107 // In ARC, we don't need to retain the iteration variable of a fast
108 // enumeration loop. Rather than actually trying to catch that
109 // during declaration processing, we remove the consequences here.
110 if (getLangOpts().ObjCAutoRefCount) {
111 QualType type = var->getType();
113 // Only do this if we inferred the lifetime. Inferred lifetime
114 // will show up as a local qualifier because explicit lifetime
115 // should have shown up as an AttributedType instead.
116 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
117 // Add 'const' and mark the variable as pseudo-strong.
118 var->setType(type.withConst());
119 var->setARCPseudoStrong(true);
124 /// Diagnose unused comparisons, both builtin and overloaded operators.
125 /// For '==' and '!=', suggest fixits for '=' or '|='.
127 /// Adding a cast to void (or other expression wrappers) will prevent the
128 /// warning from firing.
129 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
132 enum { Equality, Inequality, Relational, ThreeWay } Kind;
134 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
135 if (!Op->isComparisonOp())
138 if (Op->getOpcode() == BO_EQ)
140 else if (Op->getOpcode() == BO_NE)
142 else if (Op->getOpcode() == BO_Cmp)
145 assert(Op->isRelationalOp());
148 Loc = Op->getOperatorLoc();
149 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
150 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
151 switch (Op->getOperator()) {
155 case OO_ExclaimEqual:
160 case OO_GreaterEqual:
171 Loc = Op->getOperatorLoc();
172 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
174 // Not a typo-prone comparison.
178 // Suppress warnings when the operator, suspicious as it may be, comes from
179 // a macro expansion.
180 if (S.SourceMgr.isMacroBodyExpansion(Loc))
183 S.Diag(Loc, diag::warn_unused_comparison)
184 << (unsigned)Kind << E->getSourceRange();
186 // If the LHS is a plausible entity to assign to, provide a fixit hint to
187 // correct common typos.
189 if (Kind == Inequality)
190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191 << FixItHint::CreateReplacement(Loc, "|=");
192 else if (Kind == Equality)
193 S.Diag(Loc, diag::note_equality_comparison_to_assign)
194 << FixItHint::CreateReplacement(Loc, "=");
200 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
201 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
202 return DiagnoseUnusedExprResult(Label->getSubStmt());
204 const Expr *E = dyn_cast_or_null<Expr>(S);
208 // If we are in an unevaluated expression context, then there can be no unused
209 // results because the results aren't expected to be used in the first place.
210 if (isUnevaluatedContext())
213 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
214 // In most cases, we don't want to warn if the expression is written in a
215 // macro body, or if the macro comes from a system header. If the offending
216 // expression is a call to a function with the warn_unused_result attribute,
217 // we warn no matter the location. Because of the order in which the various
218 // checks need to happen, we factor out the macro-related test here.
219 bool ShouldSuppress =
220 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
221 SourceMgr.isInSystemMacro(ExprLoc);
223 const Expr *WarnExpr;
226 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
229 // If this is a GNU statement expression expanded from a macro, it is probably
230 // unused because it is a function-like macro that can be used as either an
231 // expression or statement. Don't warn, because it is almost certainly a
233 if (isa<StmtExpr>(E) && Loc.isMacroID())
236 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
237 // That macro is frequently used to suppress "unused parameter" warnings,
238 // but its implementation makes clang's -Wunused-value fire. Prevent this.
239 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
240 SourceLocation SpellLoc = Loc;
241 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
245 // Okay, we have an unused result. Depending on what the base expression is,
246 // we might want to make a more specific diagnostic. Check for one of these
248 unsigned DiagID = diag::warn_unused_expr;
249 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
250 E = Temps->getSubExpr();
251 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
252 E = TempExpr->getSubExpr();
254 if (DiagnoseUnusedComparison(*this, E))
258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
259 if (E->getType()->isVoidType())
262 // If the callee has attribute pure, const, or warn_unused_result, warn with
263 // a more specific message to make it clear what is happening. If the call
264 // is written in a macro body, only warn if it has the warn_unused_result
266 if (const Decl *FD = CE->getCalleeDecl()) {
267 if (const Attr *A = isa<FunctionDecl>(FD)
268 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
269 : FD->getAttr<WarnUnusedResultAttr>()) {
270 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
275 if (FD->hasAttr<PureAttr>()) {
276 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
279 if (FD->hasAttr<ConstAttr>()) {
280 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
284 } else if (ShouldSuppress)
287 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
288 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
289 Diag(Loc, diag::err_arc_unused_init_message) << R1;
292 const ObjCMethodDecl *MD = ME->getMethodDecl();
294 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
295 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
299 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
300 const Expr *Source = POE->getSyntacticForm();
301 if (isa<ObjCSubscriptRefExpr>(Source))
302 DiagID = diag::warn_unused_container_subscript_expr;
304 DiagID = diag::warn_unused_property_expr;
305 } else if (const CXXFunctionalCastExpr *FC
306 = dyn_cast<CXXFunctionalCastExpr>(E)) {
307 const Expr *E = FC->getSubExpr();
308 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
309 E = TE->getSubExpr();
310 if (isa<CXXTemporaryObjectExpr>(E))
312 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
313 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
314 if (!RD->getAttr<WarnUnusedAttr>())
317 // Diagnose "(void*) blah" as a typo for "(void) blah".
318 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
319 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
320 QualType T = TI->getType();
322 // We really do want to use the non-canonical type here.
323 if (T == Context.VoidPtrTy) {
324 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
326 Diag(Loc, diag::warn_unused_voidptr)
327 << FixItHint::CreateRemoval(TL.getStarLoc());
332 if (E->isGLValue() && E->getType().isVolatileQualified()) {
333 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
337 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
340 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
341 PushCompoundScope(IsStmtExpr);
344 void Sema::ActOnFinishOfCompoundStmt() {
348 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
349 return getCurFunction()->CompoundScopes.back();
352 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
353 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
354 const unsigned NumElts = Elts.size();
356 // If we're in C89 mode, check that we don't have any decls after stmts. If
357 // so, emit an extension diagnostic.
358 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
359 // Note that __extension__ can be around a decl.
361 // Skip over all declarations.
362 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
365 // We found the end of the list or a statement. Scan for another declstmt.
366 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
370 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
371 Diag(D->getLocation(), diag::ext_mixed_decls_code);
374 // Warn about unused expressions in statements.
375 for (unsigned i = 0; i != NumElts; ++i) {
376 // Ignore statements that are last in a statement expression.
377 if (isStmtExpr && i == NumElts - 1)
380 DiagnoseUnusedExprResult(Elts[i]);
383 // Check for suspicious empty body (null statement) in `for' and `while'
384 // statements. Don't do anything for template instantiations, this just adds
386 if (NumElts != 0 && !CurrentInstantiationScope &&
387 getCurCompoundScope().HasEmptyLoopBodies) {
388 for (unsigned i = 0; i != NumElts - 1; ++i)
389 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
392 return CompoundStmt::Create(Context, Elts, L, R);
396 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
400 if (DiagnoseUnexpandedParameterPack(Val.get()))
403 // If we're not inside a switch, let the 'case' statement handling diagnose
404 // this. Just clean up after the expression as best we can.
405 if (!getCurFunction()->SwitchStack.empty()) {
407 getCurFunction()->SwitchStack.back().getPointer()->getCond();
410 QualType CondType = CondExpr->getType();
412 auto CheckAndFinish = [&](Expr *E) {
413 if (CondType->isDependentType() || E->isTypeDependent())
414 return ExprResult(E);
416 if (getLangOpts().CPlusPlus11) {
417 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
418 // constant expression of the promoted type of the switch condition.
419 llvm::APSInt TempVal;
420 return CheckConvertedConstantExpression(E, CondType, TempVal,
425 if (!E->isValueDependent())
426 ER = VerifyIntegerConstantExpression(E);
428 ER = DefaultLvalueConversion(ER.get());
430 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
434 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
435 if (Converted.get() == Val.get())
436 Converted = CheckAndFinish(Val.get());
437 if (Converted.isInvalid())
442 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
443 getLangOpts().CPlusPlus11);
447 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
448 SourceLocation DotDotDotLoc, ExprResult RHSVal,
449 SourceLocation ColonLoc) {
450 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
451 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
452 : RHSVal.isInvalid() || RHSVal.get()) &&
453 "missing RHS value");
455 if (getCurFunction()->SwitchStack.empty()) {
456 Diag(CaseLoc, diag::err_case_not_in_switch);
460 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
461 getCurFunction()->SwitchStack.back().setInt(true);
465 CaseStmt *CS = new (Context)
466 CaseStmt(LHSVal.get(), RHSVal.get(), CaseLoc, DotDotDotLoc, ColonLoc);
467 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
471 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
472 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
473 DiagnoseUnusedExprResult(SubStmt);
475 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
476 CS->setSubStmt(SubStmt);
480 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
481 Stmt *SubStmt, Scope *CurScope) {
482 DiagnoseUnusedExprResult(SubStmt);
484 if (getCurFunction()->SwitchStack.empty()) {
485 Diag(DefaultLoc, diag::err_default_not_in_switch);
489 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
490 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
495 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
496 SourceLocation ColonLoc, Stmt *SubStmt) {
497 // If the label was multiply defined, reject it now.
498 if (TheDecl->getStmt()) {
499 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
500 Diag(TheDecl->getLocation(), diag::note_previous_definition);
504 // Otherwise, things are good. Fill in the declaration and return it.
505 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
506 TheDecl->setStmt(LS);
507 if (!TheDecl->isGnuLocal()) {
508 TheDecl->setLocStart(IdentLoc);
509 if (!TheDecl->isMSAsmLabel()) {
510 // Don't update the location of MS ASM labels. These will result in
511 // a diagnostic, and changing the location here will mess that up.
512 TheDecl->setLocation(IdentLoc);
518 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
519 ArrayRef<const Attr*> Attrs,
521 // Fill in the declaration and return it.
522 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
527 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
528 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
531 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
532 void VisitBinaryOperator(BinaryOperator *E) {
533 if (E->getOpcode() == BO_Comma)
534 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
535 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
541 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
542 ConditionResult Cond,
543 Stmt *thenStmt, SourceLocation ElseLoc,
545 if (Cond.isInvalid())
546 Cond = ConditionResult(
548 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
549 Context.BoolTy, VK_RValue),
553 Expr *CondExpr = Cond.get().second;
554 if (!Diags.isIgnored(diag::warn_comma_operator,
555 CondExpr->getExprLoc()))
556 CommaVisitor(*this).Visit(CondExpr);
559 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
560 diag::warn_empty_if_body);
562 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
566 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
567 Stmt *InitStmt, ConditionResult Cond,
568 Stmt *thenStmt, SourceLocation ElseLoc,
570 if (Cond.isInvalid())
573 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
574 setFunctionHasBranchProtectedScope();
576 DiagnoseUnusedExprResult(thenStmt);
577 DiagnoseUnusedExprResult(elseStmt);
580 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
581 Cond.get().second, thenStmt, ElseLoc, elseStmt);
585 struct CaseCompareFunctor {
586 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
587 const llvm::APSInt &RHS) {
588 return LHS.first < RHS;
590 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
591 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
592 return LHS.first < RHS.first;
594 bool operator()(const llvm::APSInt &LHS,
595 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
596 return LHS < RHS.first;
601 /// CmpCaseVals - Comparison predicate for sorting case values.
603 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
604 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
605 if (lhs.first < rhs.first)
608 if (lhs.first == rhs.first &&
609 lhs.second->getCaseLoc().getRawEncoding()
610 < rhs.second->getCaseLoc().getRawEncoding())
615 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
617 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
618 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
620 return lhs.first < rhs.first;
623 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
625 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
626 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
628 return lhs.first == rhs.first;
631 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
632 /// potentially integral-promoted expression @p expr.
633 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
634 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
635 E = CleanUps->getSubExpr();
636 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
637 if (ImpCast->getCastKind() != CK_IntegralCast) break;
638 E = ImpCast->getSubExpr();
643 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
644 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
648 SwitchConvertDiagnoser(Expr *Cond)
649 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
652 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
653 QualType T) override {
654 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
657 SemaDiagnosticBuilder diagnoseIncomplete(
658 Sema &S, SourceLocation Loc, QualType T) override {
659 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
660 << T << Cond->getSourceRange();
663 SemaDiagnosticBuilder diagnoseExplicitConv(
664 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
665 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
668 SemaDiagnosticBuilder noteExplicitConv(
669 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
670 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
671 << ConvTy->isEnumeralType() << ConvTy;
674 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
675 QualType T) override {
676 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
679 SemaDiagnosticBuilder noteAmbiguous(
680 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
681 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
682 << ConvTy->isEnumeralType() << ConvTy;
685 SemaDiagnosticBuilder diagnoseConversion(
686 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
687 llvm_unreachable("conversion functions are permitted");
689 } SwitchDiagnoser(Cond);
691 ExprResult CondResult =
692 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
693 if (CondResult.isInvalid())
696 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
697 // failed and produced a diagnostic.
698 Cond = CondResult.get();
699 if (!Cond->isTypeDependent() &&
700 !Cond->getType()->isIntegralOrEnumerationType())
703 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
704 return UsualUnaryConversions(Cond);
707 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
708 Stmt *InitStmt, ConditionResult Cond) {
709 Expr *CondExpr = Cond.get().second;
710 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
712 if (CondExpr && !CondExpr->isTypeDependent()) {
713 // We have already converted the expression to an integral or enumeration
714 // type, when we parsed the switch condition. If we don't have an
715 // appropriate type now, enter the switch scope but remember that it's
717 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
718 "invalid condition type");
719 if (CondExpr->isKnownToHaveBooleanValue()) {
720 // switch(bool_expr) {...} is often a programmer error, e.g.
721 // switch(n && mask) { ... } // Doh - should be "n & mask".
722 // One can always use an if statement instead of switch(bool_expr).
723 Diag(SwitchLoc, diag::warn_bool_switch_condition)
724 << CondExpr->getSourceRange();
728 setFunctionHasBranchIntoScope();
730 SwitchStmt *SS = new (Context)
731 SwitchStmt(Context, InitStmt, Cond.get().first, CondExpr);
732 getCurFunction()->SwitchStack.push_back(
733 FunctionScopeInfo::SwitchInfo(SS, false));
737 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
738 Val = Val.extOrTrunc(BitWidth);
739 Val.setIsSigned(IsSigned);
742 /// Check the specified case value is in range for the given unpromoted switch
744 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
745 unsigned UnpromotedWidth, bool UnpromotedSign) {
746 // In C++11 onwards, this is checked by the language rules.
747 if (S.getLangOpts().CPlusPlus11)
750 // If the case value was signed and negative and the switch expression is
751 // unsigned, don't bother to warn: this is implementation-defined behavior.
752 // FIXME: Introduce a second, default-ignored warning for this case?
753 if (UnpromotedWidth < Val.getBitWidth()) {
754 llvm::APSInt ConvVal(Val);
755 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
756 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
757 // FIXME: Use different diagnostics for overflow in conversion to promoted
758 // type versus "switch expression cannot have this value". Use proper
759 // IntRange checking rather than just looking at the unpromoted type here.
761 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
762 << ConvVal.toString(10);
766 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
768 /// Returns true if we should emit a diagnostic about this case expression not
769 /// being a part of the enum used in the switch controlling expression.
770 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
772 const Expr *CaseExpr,
773 EnumValsTy::iterator &EI,
774 EnumValsTy::iterator &EIEnd,
775 const llvm::APSInt &Val) {
779 if (const DeclRefExpr *DRE =
780 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
781 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
782 QualType VarType = VD->getType();
783 QualType EnumType = S.Context.getTypeDeclType(ED);
784 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
785 S.Context.hasSameUnqualifiedType(EnumType, VarType))
790 if (ED->hasAttr<FlagEnumAttr>())
791 return !S.IsValueInFlagEnum(ED, Val, false);
793 while (EI != EIEnd && EI->first < Val)
796 if (EI != EIEnd && EI->first == Val)
802 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
804 QualType CondType = Cond->getType();
805 QualType CaseType = Case->getType();
807 const EnumType *CondEnumType = CondType->getAs<EnumType>();
808 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
809 if (!CondEnumType || !CaseEnumType)
812 // Ignore anonymous enums.
813 if (!CondEnumType->getDecl()->getIdentifier() &&
814 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
816 if (!CaseEnumType->getDecl()->getIdentifier() &&
817 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
820 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
823 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
824 << CondType << CaseType << Cond->getSourceRange()
825 << Case->getSourceRange();
829 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
831 SwitchStmt *SS = cast<SwitchStmt>(Switch);
832 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
833 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
834 "switch stack missing push/pop!");
836 getCurFunction()->SwitchStack.pop_back();
838 if (!BodyStmt) return StmtError();
839 SS->setBody(BodyStmt, SwitchLoc);
841 Expr *CondExpr = SS->getCond();
842 if (!CondExpr) return StmtError();
844 QualType CondType = CondExpr->getType();
847 // Integral promotions are performed (on the switch condition).
849 // A case value unrepresentable by the original switch condition
850 // type (before the promotion) doesn't make sense, even when it can
851 // be represented by the promoted type. Therefore we need to find
852 // the pre-promotion type of the switch condition.
853 const Expr *CondExprBeforePromotion = CondExpr;
854 QualType CondTypeBeforePromotion =
855 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
857 // Get the bitwidth of the switched-on value after promotions. We must
858 // convert the integer case values to this width before comparison.
859 bool HasDependentValue
860 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
861 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
862 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
864 // Get the width and signedness that the condition might actually have, for
866 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
868 unsigned CondWidthBeforePromotion
869 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
870 bool CondIsSignedBeforePromotion
871 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
873 // Accumulate all of the case values in a vector so that we can sort them
874 // and detect duplicates. This vector contains the APInt for the case after
875 // it has been converted to the condition type.
876 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
879 // Keep track of any GNU case ranges we see. The APSInt is the low value.
880 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
881 CaseRangesTy CaseRanges;
883 DefaultStmt *TheDefaultStmt = nullptr;
885 bool CaseListIsErroneous = false;
887 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
888 SC = SC->getNextSwitchCase()) {
890 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
891 if (TheDefaultStmt) {
892 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
893 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
895 // FIXME: Remove the default statement from the switch block so that
896 // we'll return a valid AST. This requires recursing down the AST and
897 // finding it, not something we are set up to do right now. For now,
898 // just lop the entire switch stmt out of the AST.
899 CaseListIsErroneous = true;
904 CaseStmt *CS = cast<CaseStmt>(SC);
906 Expr *Lo = CS->getLHS();
908 if (Lo->isValueDependent()) {
909 HasDependentValue = true;
913 // We already verified that the expression has a constant value;
914 // get that value (prior to conversions).
915 const Expr *LoBeforePromotion = Lo;
916 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
917 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
919 // Check the unconverted value is within the range of possible values of
920 // the switch expression.
921 checkCaseValue(*this, Lo->getLocStart(), LoVal,
922 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
924 // FIXME: This duplicates the check performed for warn_not_in_enum below.
925 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
928 // Convert the value to the same width/sign as the condition.
929 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
931 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
933 if (CS->getRHS()->isValueDependent()) {
934 HasDependentValue = true;
937 CaseRanges.push_back(std::make_pair(LoVal, CS));
939 CaseVals.push_back(std::make_pair(LoVal, CS));
943 if (!HasDependentValue) {
944 // If we don't have a default statement, check whether the
945 // condition is constant.
946 llvm::APSInt ConstantCondValue;
947 bool HasConstantCond = false;
948 if (!HasDependentValue && !TheDefaultStmt) {
949 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
950 Expr::SE_AllowSideEffects);
951 assert(!HasConstantCond ||
952 (ConstantCondValue.getBitWidth() == CondWidth &&
953 ConstantCondValue.isSigned() == CondIsSigned));
955 bool ShouldCheckConstantCond = HasConstantCond;
957 // Sort all the scalar case values so we can easily detect duplicates.
958 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
960 if (!CaseVals.empty()) {
961 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
962 if (ShouldCheckConstantCond &&
963 CaseVals[i].first == ConstantCondValue)
964 ShouldCheckConstantCond = false;
966 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
967 // If we have a duplicate, report it.
968 // First, determine if either case value has a name
969 StringRef PrevString, CurrString;
970 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
971 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
972 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
973 PrevString = DeclRef->getDecl()->getName();
975 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
976 CurrString = DeclRef->getDecl()->getName();
978 SmallString<16> CaseValStr;
979 CaseVals[i-1].first.toString(CaseValStr);
981 if (PrevString == CurrString)
982 Diag(CaseVals[i].second->getLHS()->getLocStart(),
983 diag::err_duplicate_case) <<
984 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
986 Diag(CaseVals[i].second->getLHS()->getLocStart(),
987 diag::err_duplicate_case_differing_expr) <<
988 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
989 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
992 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
993 diag::note_duplicate_case_prev);
994 // FIXME: We really want to remove the bogus case stmt from the
995 // substmt, but we have no way to do this right now.
996 CaseListIsErroneous = true;
1001 // Detect duplicate case ranges, which usually don't exist at all in
1003 if (!CaseRanges.empty()) {
1004 // Sort all the case ranges by their low value so we can easily detect
1005 // overlaps between ranges.
1006 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
1008 // Scan the ranges, computing the high values and removing empty ranges.
1009 std::vector<llvm::APSInt> HiVals;
1010 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1011 llvm::APSInt &LoVal = CaseRanges[i].first;
1012 CaseStmt *CR = CaseRanges[i].second;
1013 Expr *Hi = CR->getRHS();
1015 const Expr *HiBeforePromotion = Hi;
1016 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1017 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1019 // Check the unconverted value is within the range of possible values of
1020 // the switch expression.
1021 checkCaseValue(*this, Hi->getLocStart(), HiVal,
1022 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1024 // Convert the value to the same width/sign as the condition.
1025 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1027 // If the low value is bigger than the high value, the case is empty.
1028 if (LoVal > HiVal) {
1029 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1030 << SourceRange(CR->getLHS()->getLocStart(),
1032 CaseRanges.erase(CaseRanges.begin()+i);
1038 if (ShouldCheckConstantCond &&
1039 LoVal <= ConstantCondValue &&
1040 ConstantCondValue <= HiVal)
1041 ShouldCheckConstantCond = false;
1043 HiVals.push_back(HiVal);
1046 // Rescan the ranges, looking for overlap with singleton values and other
1047 // ranges. Since the range list is sorted, we only need to compare case
1048 // ranges with their neighbors.
1049 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1050 llvm::APSInt &CRLo = CaseRanges[i].first;
1051 llvm::APSInt &CRHi = HiVals[i];
1052 CaseStmt *CR = CaseRanges[i].second;
1054 // Check to see whether the case range overlaps with any
1056 CaseStmt *OverlapStmt = nullptr;
1057 llvm::APSInt OverlapVal(32);
1059 // Find the smallest value >= the lower bound. If I is in the
1060 // case range, then we have overlap.
1061 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1062 CaseVals.end(), CRLo,
1063 CaseCompareFunctor());
1064 if (I != CaseVals.end() && I->first < CRHi) {
1065 OverlapVal = I->first; // Found overlap with scalar.
1066 OverlapStmt = I->second;
1069 // Find the smallest value bigger than the upper bound.
1070 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1071 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1072 OverlapVal = (I-1)->first; // Found overlap with scalar.
1073 OverlapStmt = (I-1)->second;
1076 // Check to see if this case stmt overlaps with the subsequent
1078 if (i && CRLo <= HiVals[i-1]) {
1079 OverlapVal = HiVals[i-1]; // Found overlap with range.
1080 OverlapStmt = CaseRanges[i-1].second;
1084 // If we have a duplicate, report it.
1085 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1086 << OverlapVal.toString(10);
1087 Diag(OverlapStmt->getLHS()->getLocStart(),
1088 diag::note_duplicate_case_prev);
1089 // FIXME: We really want to remove the bogus case stmt from the
1090 // substmt, but we have no way to do this right now.
1091 CaseListIsErroneous = true;
1096 // Complain if we have a constant condition and we didn't find a match.
1097 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1098 ShouldCheckConstantCond) {
1099 // TODO: it would be nice if we printed enums as enums, chars as
1101 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1102 << ConstantCondValue.toString(10)
1103 << CondExpr->getSourceRange();
1106 // Check to see if switch is over an Enum and handles all of its
1107 // values. We only issue a warning if there is not 'default:', but
1108 // we still do the analysis to preserve this information in the AST
1109 // (which can be used by flow-based analyes).
1111 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1113 // If switch has default case, then ignore it.
1114 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1115 ET && ET->getDecl()->isCompleteDefinition()) {
1116 const EnumDecl *ED = ET->getDecl();
1117 EnumValsTy EnumVals;
1119 // Gather all enum values, set their type and sort them,
1120 // allowing easier comparison with CaseVals.
1121 for (auto *EDI : ED->enumerators()) {
1122 llvm::APSInt Val = EDI->getInitVal();
1123 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1124 EnumVals.push_back(std::make_pair(Val, EDI));
1126 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1127 auto EI = EnumVals.begin(), EIEnd =
1128 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1130 // See which case values aren't in enum.
1131 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1132 CI != CaseVals.end(); CI++) {
1133 Expr *CaseExpr = CI->second->getLHS();
1134 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1136 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1137 << CondTypeBeforePromotion;
1140 // See which of case ranges aren't in enum
1141 EI = EnumVals.begin();
1142 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1143 RI != CaseRanges.end(); RI++) {
1144 Expr *CaseExpr = RI->second->getLHS();
1145 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1147 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1148 << CondTypeBeforePromotion;
1151 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1152 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1154 CaseExpr = RI->second->getRHS();
1155 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1157 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1158 << CondTypeBeforePromotion;
1161 // Check which enum vals aren't in switch
1162 auto CI = CaseVals.begin();
1163 auto RI = CaseRanges.begin();
1164 bool hasCasesNotInSwitch = false;
1166 SmallVector<DeclarationName,8> UnhandledNames;
1168 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1169 // Drop unneeded case values
1170 while (CI != CaseVals.end() && CI->first < EI->first)
1173 if (CI != CaseVals.end() && CI->first == EI->first)
1176 // Drop unneeded case ranges
1177 for (; RI != CaseRanges.end(); RI++) {
1179 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1180 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1181 if (EI->first <= Hi)
1185 if (RI == CaseRanges.end() || EI->first < RI->first) {
1186 hasCasesNotInSwitch = true;
1187 UnhandledNames.push_back(EI->second->getDeclName());
1191 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1192 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1194 // Produce a nice diagnostic if multiple values aren't handled.
1195 if (!UnhandledNames.empty()) {
1196 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1197 TheDefaultStmt ? diag::warn_def_missing_case
1198 : diag::warn_missing_case)
1199 << (int)UnhandledNames.size();
1201 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1203 DB << UnhandledNames[I];
1206 if (!hasCasesNotInSwitch)
1207 SS->setAllEnumCasesCovered();
1212 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1213 diag::warn_empty_switch_body);
1215 // FIXME: If the case list was broken is some way, we don't have a good system
1216 // to patch it up. Instead, just return the whole substmt as broken.
1217 if (CaseListIsErroneous)
1224 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1226 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1229 if (const EnumType *ET = DstType->getAs<EnumType>())
1230 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1231 SrcType->isIntegerType()) {
1232 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1233 SrcExpr->isIntegerConstantExpr(Context)) {
1234 // Get the bitwidth of the enum value before promotions.
1235 unsigned DstWidth = Context.getIntWidth(DstType);
1236 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1238 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1239 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1240 const EnumDecl *ED = ET->getDecl();
1242 if (!ED->isClosed())
1245 if (ED->hasAttr<FlagEnumAttr>()) {
1246 if (!IsValueInFlagEnum(ED, RhsVal, true))
1247 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1248 << DstType.getUnqualifiedType();
1250 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1252 EnumValsTy EnumVals;
1254 // Gather all enum values, set their type and sort them,
1255 // allowing easier comparison with rhs constant.
1256 for (auto *EDI : ED->enumerators()) {
1257 llvm::APSInt Val = EDI->getInitVal();
1258 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1259 EnumVals.push_back(std::make_pair(Val, EDI));
1261 if (EnumVals.empty())
1263 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1264 EnumValsTy::iterator EIend =
1265 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1267 // See which values aren't in the enum.
1268 EnumValsTy::const_iterator EI = EnumVals.begin();
1269 while (EI != EIend && EI->first < RhsVal)
1271 if (EI == EIend || EI->first != RhsVal) {
1272 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1273 << DstType.getUnqualifiedType();
1280 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1282 if (Cond.isInvalid())
1285 auto CondVal = Cond.get();
1286 CheckBreakContinueBinding(CondVal.second);
1288 if (CondVal.second &&
1289 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1290 CommaVisitor(*this).Visit(CondVal.second);
1292 DiagnoseUnusedExprResult(Body);
1294 if (isa<NullStmt>(Body))
1295 getCurCompoundScope().setHasEmptyLoopBodies();
1297 return new (Context)
1298 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
1302 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1303 SourceLocation WhileLoc, SourceLocation CondLParen,
1304 Expr *Cond, SourceLocation CondRParen) {
1305 assert(Cond && "ActOnDoStmt(): missing expression");
1307 CheckBreakContinueBinding(Cond);
1308 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1309 if (CondResult.isInvalid())
1311 Cond = CondResult.get();
1313 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1314 if (CondResult.isInvalid())
1316 Cond = CondResult.get();
1318 DiagnoseUnusedExprResult(Body);
1320 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1324 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1325 using DeclSetVector =
1326 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1327 llvm::SmallPtrSet<VarDecl *, 8>>;
1329 // This visitor will traverse a conditional statement and store all
1330 // the evaluated decls into a vector. Simple is set to true if none
1331 // of the excluded constructs are used.
1332 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1333 DeclSetVector &Decls;
1334 SmallVectorImpl<SourceRange> &Ranges;
1337 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1339 DeclExtractor(Sema &S, DeclSetVector &Decls,
1340 SmallVectorImpl<SourceRange> &Ranges) :
1341 Inherited(S.Context),
1346 bool isSimple() { return Simple; }
1348 // Replaces the method in EvaluatedExprVisitor.
1349 void VisitMemberExpr(MemberExpr* E) {
1353 // Any Stmt not whitelisted will cause the condition to be marked complex.
1354 void VisitStmt(Stmt *S) {
1358 void VisitBinaryOperator(BinaryOperator *E) {
1363 void VisitCastExpr(CastExpr *E) {
1364 Visit(E->getSubExpr());
1367 void VisitUnaryOperator(UnaryOperator *E) {
1368 // Skip checking conditionals with derefernces.
1369 if (E->getOpcode() == UO_Deref)
1372 Visit(E->getSubExpr());
1375 void VisitConditionalOperator(ConditionalOperator *E) {
1376 Visit(E->getCond());
1377 Visit(E->getTrueExpr());
1378 Visit(E->getFalseExpr());
1381 void VisitParenExpr(ParenExpr *E) {
1382 Visit(E->getSubExpr());
1385 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1386 Visit(E->getOpaqueValue()->getSourceExpr());
1387 Visit(E->getFalseExpr());
1390 void VisitIntegerLiteral(IntegerLiteral *E) { }
1391 void VisitFloatingLiteral(FloatingLiteral *E) { }
1392 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1393 void VisitCharacterLiteral(CharacterLiteral *E) { }
1394 void VisitGNUNullExpr(GNUNullExpr *E) { }
1395 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1397 void VisitDeclRefExpr(DeclRefExpr *E) {
1398 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1401 Ranges.push_back(E->getSourceRange());
1406 }; // end class DeclExtractor
1408 // DeclMatcher checks to see if the decls are used in a non-evaluated
1410 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1411 DeclSetVector &Decls;
1415 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1417 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1418 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1419 if (!Statement) return;
1424 void VisitReturnStmt(ReturnStmt *S) {
1428 void VisitBreakStmt(BreakStmt *S) {
1432 void VisitGotoStmt(GotoStmt *S) {
1436 void VisitCastExpr(CastExpr *E) {
1437 if (E->getCastKind() == CK_LValueToRValue)
1438 CheckLValueToRValueCast(E->getSubExpr());
1440 Visit(E->getSubExpr());
1443 void CheckLValueToRValueCast(Expr *E) {
1444 E = E->IgnoreParenImpCasts();
1446 if (isa<DeclRefExpr>(E)) {
1450 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1451 Visit(CO->getCond());
1452 CheckLValueToRValueCast(CO->getTrueExpr());
1453 CheckLValueToRValueCast(CO->getFalseExpr());
1457 if (BinaryConditionalOperator *BCO =
1458 dyn_cast<BinaryConditionalOperator>(E)) {
1459 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1460 CheckLValueToRValueCast(BCO->getFalseExpr());
1467 void VisitDeclRefExpr(DeclRefExpr *E) {
1468 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1469 if (Decls.count(VD))
1473 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1474 // Only need to visit the semantics for POE.
1475 // SyntaticForm doesn't really use the Decal.
1476 for (auto *S : POE->semantics()) {
1477 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1478 // Look past the OVE into the expression it binds.
1479 Visit(OVE->getSourceExpr());
1485 bool FoundDeclInUse() { return FoundDecl; }
1487 }; // end class DeclMatcher
1489 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1490 Expr *Third, Stmt *Body) {
1491 // Condition is empty
1492 if (!Second) return;
1494 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1495 Second->getLocStart()))
1498 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1499 DeclSetVector Decls;
1500 SmallVector<SourceRange, 10> Ranges;
1501 DeclExtractor DE(S, Decls, Ranges);
1504 // Don't analyze complex conditionals.
1505 if (!DE.isSimple()) return;
1508 if (Decls.size() == 0) return;
1510 // Don't warn on volatile, static, or global variables.
1511 for (auto *VD : Decls)
1512 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1515 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1516 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1517 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1520 // Load decl names into diagnostic.
1521 if (Decls.size() > 4) {
1524 PDiag << (unsigned)Decls.size();
1525 for (auto *VD : Decls)
1526 PDiag << VD->getDeclName();
1529 for (auto Range : Ranges)
1532 S.Diag(Ranges.begin()->getBegin(), PDiag);
1535 // If Statement is an incemement or decrement, return true and sets the
1536 // variables Increment and DRE.
1537 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1538 DeclRefExpr *&DRE) {
1539 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1540 if (!Cleanups->cleanupsHaveSideEffects())
1541 Statement = Cleanups->getSubExpr();
1543 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1544 switch (UO->getOpcode()) {
1545 default: return false;
1555 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1559 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1560 FunctionDecl *FD = Call->getDirectCallee();
1561 if (!FD || !FD->isOverloadedOperator()) return false;
1562 switch (FD->getOverloadedOperator()) {
1563 default: return false;
1571 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1578 // A visitor to determine if a continue or break statement is a
1580 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1581 SourceLocation BreakLoc;
1582 SourceLocation ContinueLoc;
1583 bool InSwitch = false;
1586 BreakContinueFinder(Sema &S, const Stmt* Body) :
1587 Inherited(S.Context) {
1591 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1593 void VisitContinueStmt(const ContinueStmt* E) {
1594 ContinueLoc = E->getContinueLoc();
1597 void VisitBreakStmt(const BreakStmt* E) {
1599 BreakLoc = E->getBreakLoc();
1602 void VisitSwitchStmt(const SwitchStmt* S) {
1603 if (const Stmt *Init = S->getInit())
1605 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1607 if (const Stmt *Cond = S->getCond())
1610 // Don't return break statements from the body of a switch.
1612 if (const Stmt *Body = S->getBody())
1617 void VisitForStmt(const ForStmt *S) {
1618 // Only visit the init statement of a for loop; the body
1619 // has a different break/continue scope.
1620 if (const Stmt *Init = S->getInit())
1624 void VisitWhileStmt(const WhileStmt *) {
1625 // Do nothing; the children of a while loop have a different
1626 // break/continue scope.
1629 void VisitDoStmt(const DoStmt *) {
1630 // Do nothing; the children of a while loop have a different
1631 // break/continue scope.
1634 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1635 // Only visit the initialization of a for loop; the body
1636 // has a different break/continue scope.
1637 if (const Stmt *Range = S->getRangeStmt())
1639 if (const Stmt *Begin = S->getBeginStmt())
1641 if (const Stmt *End = S->getEndStmt())
1645 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1646 // Only visit the initialization of a for loop; the body
1647 // has a different break/continue scope.
1648 if (const Stmt *Element = S->getElement())
1650 if (const Stmt *Collection = S->getCollection())
1654 bool ContinueFound() { return ContinueLoc.isValid(); }
1655 bool BreakFound() { return BreakLoc.isValid(); }
1656 SourceLocation GetContinueLoc() { return ContinueLoc; }
1657 SourceLocation GetBreakLoc() { return BreakLoc; }
1659 }; // end class BreakContinueFinder
1661 // Emit a warning when a loop increment/decrement appears twice per loop
1662 // iteration. The conditions which trigger this warning are:
1663 // 1) The last statement in the loop body and the third expression in the
1664 // for loop are both increment or both decrement of the same variable
1665 // 2) No continue statements in the loop body.
1666 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1667 // Return when there is nothing to check.
1668 if (!Body || !Third) return;
1670 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1671 Third->getLocStart()))
1674 // Get the last statement from the loop body.
1675 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1676 if (!CS || CS->body_empty()) return;
1677 Stmt *LastStmt = CS->body_back();
1678 if (!LastStmt) return;
1680 bool LoopIncrement, LastIncrement;
1681 DeclRefExpr *LoopDRE, *LastDRE;
1683 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1684 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1686 // Check that the two statements are both increments or both decrements
1687 // on the same variable.
1688 if (LoopIncrement != LastIncrement ||
1689 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1691 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1693 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1694 << LastDRE->getDecl() << LastIncrement;
1695 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1702 void Sema::CheckBreakContinueBinding(Expr *E) {
1703 if (!E || getLangOpts().CPlusPlus)
1705 BreakContinueFinder BCFinder(*this, E);
1706 Scope *BreakParent = CurScope->getBreakParent();
1707 if (BCFinder.BreakFound() && BreakParent) {
1708 if (BreakParent->getFlags() & Scope::SwitchScope) {
1709 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1711 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1714 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1715 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1720 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1721 Stmt *First, ConditionResult Second,
1722 FullExprArg third, SourceLocation RParenLoc,
1724 if (Second.isInvalid())
1727 if (!getLangOpts().CPlusPlus) {
1728 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1729 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1730 // declare identifiers for objects having storage class 'auto' or
1732 for (auto *DI : DS->decls()) {
1733 VarDecl *VD = dyn_cast<VarDecl>(DI);
1734 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1737 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1738 DI->setInvalidDecl();
1744 CheckBreakContinueBinding(Second.get().second);
1745 CheckBreakContinueBinding(third.get());
1747 if (!Second.get().first)
1748 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1750 CheckForRedundantIteration(*this, third.get(), Body);
1752 if (Second.get().second &&
1753 !Diags.isIgnored(diag::warn_comma_operator,
1754 Second.get().second->getExprLoc()))
1755 CommaVisitor(*this).Visit(Second.get().second);
1757 Expr *Third = third.release().getAs<Expr>();
1759 DiagnoseUnusedExprResult(First);
1760 DiagnoseUnusedExprResult(Third);
1761 DiagnoseUnusedExprResult(Body);
1763 if (isa<NullStmt>(Body))
1764 getCurCompoundScope().setHasEmptyLoopBodies();
1766 return new (Context)
1767 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1768 Body, ForLoc, LParenLoc, RParenLoc);
1771 /// In an Objective C collection iteration statement:
1773 /// x can be an arbitrary l-value expression. Bind it up as a
1774 /// full-expression.
1775 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1776 // Reduce placeholder expressions here. Note that this rejects the
1777 // use of pseudo-object l-values in this position.
1778 ExprResult result = CheckPlaceholderExpr(E);
1779 if (result.isInvalid()) return StmtError();
1782 ExprResult FullExpr = ActOnFinishFullExpr(E);
1783 if (FullExpr.isInvalid())
1785 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1789 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1793 ExprResult result = CorrectDelayedTyposInExpr(collection);
1794 if (!result.isUsable())
1796 collection = result.get();
1798 // Bail out early if we've got a type-dependent expression.
1799 if (collection->isTypeDependent()) return collection;
1801 // Perform normal l-value conversion.
1802 result = DefaultFunctionArrayLvalueConversion(collection);
1803 if (result.isInvalid())
1805 collection = result.get();
1807 // The operand needs to have object-pointer type.
1808 // TODO: should we do a contextual conversion?
1809 const ObjCObjectPointerType *pointerType =
1810 collection->getType()->getAs<ObjCObjectPointerType>();
1812 return Diag(forLoc, diag::err_collection_expr_type)
1813 << collection->getType() << collection->getSourceRange();
1815 // Check that the operand provides
1816 // - countByEnumeratingWithState:objects:count:
1817 const ObjCObjectType *objectType = pointerType->getObjectType();
1818 ObjCInterfaceDecl *iface = objectType->getInterface();
1820 // If we have a forward-declared type, we can't do this check.
1821 // Under ARC, it is an error not to have a forward-declared class.
1823 (getLangOpts().ObjCAutoRefCount
1824 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1825 diag::err_arc_collection_forward, collection)
1826 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1827 // Otherwise, if we have any useful type information, check that
1828 // the type declares the appropriate method.
1829 } else if (iface || !objectType->qual_empty()) {
1830 IdentifierInfo *selectorIdents[] = {
1831 &Context.Idents.get("countByEnumeratingWithState"),
1832 &Context.Idents.get("objects"),
1833 &Context.Idents.get("count")
1835 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1837 ObjCMethodDecl *method = nullptr;
1839 // If there's an interface, look in both the public and private APIs.
1841 method = iface->lookupInstanceMethod(selector);
1842 if (!method) method = iface->lookupPrivateMethod(selector);
1845 // Also check protocol qualifiers.
1847 method = LookupMethodInQualifiedType(selector, pointerType,
1850 // If we didn't find it anywhere, give up.
1852 Diag(forLoc, diag::warn_collection_expr_type)
1853 << collection->getType() << selector << collection->getSourceRange();
1856 // TODO: check for an incompatible signature?
1859 // Wrap up any cleanups in the expression.
1864 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1865 Stmt *First, Expr *collection,
1866 SourceLocation RParenLoc) {
1867 setFunctionHasBranchProtectedScope();
1869 ExprResult CollectionExprResult =
1870 CheckObjCForCollectionOperand(ForLoc, collection);
1874 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1875 if (!DS->isSingleDecl())
1876 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1877 diag::err_toomany_element_decls));
1879 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1880 if (!D || D->isInvalidDecl())
1883 FirstType = D->getType();
1884 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1885 // declare identifiers for objects having storage class 'auto' or
1887 if (!D->hasLocalStorage())
1888 return StmtError(Diag(D->getLocation(),
1889 diag::err_non_local_variable_decl_in_for));
1891 // If the type contained 'auto', deduce the 'auto' to 'id'.
1892 if (FirstType->getContainedAutoType()) {
1893 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1895 Expr *DeducedInit = &OpaqueId;
1896 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1898 DiagnoseAutoDeductionFailure(D, DeducedInit);
1899 if (FirstType.isNull()) {
1900 D->setInvalidDecl();
1904 D->setType(FirstType);
1906 if (!inTemplateInstantiation()) {
1907 SourceLocation Loc =
1908 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1909 Diag(Loc, diag::warn_auto_var_is_id)
1910 << D->getDeclName();
1915 Expr *FirstE = cast<Expr>(First);
1916 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1917 return StmtError(Diag(First->getLocStart(),
1918 diag::err_selector_element_not_lvalue)
1919 << First->getSourceRange());
1921 FirstType = static_cast<Expr*>(First)->getType();
1922 if (FirstType.isConstQualified())
1923 Diag(ForLoc, diag::err_selector_element_const_type)
1924 << FirstType << First->getSourceRange();
1926 if (!FirstType->isDependentType() &&
1927 !FirstType->isObjCObjectPointerType() &&
1928 !FirstType->isBlockPointerType())
1929 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1930 << FirstType << First->getSourceRange());
1933 if (CollectionExprResult.isInvalid())
1936 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1937 if (CollectionExprResult.isInvalid())
1940 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1941 nullptr, ForLoc, RParenLoc);
1944 /// Finish building a variable declaration for a for-range statement.
1945 /// \return true if an error occurs.
1946 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1947 SourceLocation Loc, int DiagID) {
1948 if (Decl->getType()->isUndeducedType()) {
1949 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1950 if (!Res.isUsable()) {
1951 Decl->setInvalidDecl();
1957 // Deduce the type for the iterator variable now rather than leaving it to
1958 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1960 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1961 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1963 SemaRef.Diag(Loc, DiagID) << Init->getType();
1964 if (InitType.isNull()) {
1965 Decl->setInvalidDecl();
1968 Decl->setType(InitType);
1970 // In ARC, infer lifetime.
1971 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1972 // we're doing the equivalent of fast iteration.
1973 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1974 SemaRef.inferObjCARCLifetime(Decl))
1975 Decl->setInvalidDecl();
1977 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1978 SemaRef.FinalizeDeclaration(Decl);
1979 SemaRef.CurContext->addHiddenDecl(Decl);
1984 // An enum to represent whether something is dealing with a call to begin()
1985 // or a call to end() in a range-based for loop.
1986 enum BeginEndFunction {
1991 /// Produce a note indicating which begin/end function was implicitly called
1992 /// by a C++11 for-range statement. This is often not obvious from the code,
1993 /// nor from the diagnostics produced when analysing the implicit expressions
1994 /// required in a for-range statement.
1995 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1996 BeginEndFunction BEF) {
1997 CallExpr *CE = dyn_cast<CallExpr>(E);
2000 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2003 SourceLocation Loc = D->getLocation();
2005 std::string Description;
2006 bool IsTemplate = false;
2007 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2008 Description = SemaRef.getTemplateArgumentBindingsText(
2009 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2013 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2014 << BEF << IsTemplate << Description << E->getType();
2017 /// Build a variable declaration for a for-range statement.
2018 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2019 QualType Type, StringRef Name) {
2020 DeclContext *DC = SemaRef.CurContext;
2021 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2022 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2023 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2025 Decl->setImplicit();
2031 static bool ObjCEnumerationCollection(Expr *Collection) {
2032 return !Collection->isTypeDependent()
2033 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2036 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2038 /// C++11 [stmt.ranged]:
2039 /// A range-based for statement is equivalent to
2042 /// auto && __range = range-init;
2043 /// for ( auto __begin = begin-expr,
2044 /// __end = end-expr;
2045 /// __begin != __end;
2047 /// for-range-declaration = *__begin;
2052 /// The body of the loop is not available yet, since it cannot be analysed until
2053 /// we have determined the type of the for-range-declaration.
2054 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2055 SourceLocation CoawaitLoc, Stmt *First,
2056 SourceLocation ColonLoc, Expr *Range,
2057 SourceLocation RParenLoc,
2058 BuildForRangeKind Kind) {
2062 if (Range && ObjCEnumerationCollection(Range))
2063 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2065 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2066 assert(DS && "first part of for range not a decl stmt");
2068 if (!DS->isSingleDecl()) {
2069 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
2073 Decl *LoopVar = DS->getSingleDecl();
2074 if (LoopVar->isInvalidDecl() || !Range ||
2075 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2076 LoopVar->setInvalidDecl();
2080 // Build the coroutine state immediately and not later during template
2082 if (!CoawaitLoc.isInvalid()) {
2083 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2087 // Build auto && __range = range-init
2088 // Divide by 2, since the variables are in the inner scope (loop body).
2089 const auto DepthStr = std::to_string(S->getDepth() / 2);
2090 SourceLocation RangeLoc = Range->getLocStart();
2091 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2092 Context.getAutoRRefDeductType(),
2093 std::string("__range") + DepthStr);
2094 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2095 diag::err_for_range_deduction_failure)) {
2096 LoopVar->setInvalidDecl();
2100 // Claim the type doesn't contain auto: we've already done the checking.
2101 DeclGroupPtrTy RangeGroup =
2102 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2103 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2104 if (RangeDecl.isInvalid()) {
2105 LoopVar->setInvalidDecl();
2109 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
2110 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2111 /*Cond=*/nullptr, /*Inc=*/nullptr,
2112 DS, RParenLoc, Kind);
2115 /// Create the initialization, compare, and increment steps for
2116 /// the range-based for loop expression.
2117 /// This function does not handle array-based for loops,
2118 /// which are created in Sema::BuildCXXForRangeStmt.
2120 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2121 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2122 /// CandidateSet and BEF are set and some non-success value is returned on
2124 static Sema::ForRangeStatus
2125 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2126 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2127 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2128 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2129 ExprResult *EndExpr, BeginEndFunction *BEF) {
2130 DeclarationNameInfo BeginNameInfo(
2131 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2132 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2135 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2136 Sema::LookupMemberName);
2137 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2139 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2140 // - if _RangeT is a class type, the unqualified-ids begin and end are
2141 // looked up in the scope of class _RangeT as if by class member access
2142 // lookup (3.4.5), and if either (or both) finds at least one
2143 // declaration, begin-expr and end-expr are __range.begin() and
2144 // __range.end(), respectively;
2145 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2146 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2148 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2149 SourceLocation RangeLoc = BeginVar->getLocation();
2150 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
2152 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2153 << RangeLoc << BeginRange->getType() << *BEF;
2154 return Sema::FRS_DiagnosticIssued;
2157 // - otherwise, begin-expr and end-expr are begin(__range) and
2158 // end(__range), respectively, where begin and end are looked up with
2159 // argument-dependent lookup (3.4.2). For the purposes of this name
2160 // lookup, namespace std is an associated namespace.
2165 Sema::ForRangeStatus RangeStatus =
2166 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2167 BeginMemberLookup, CandidateSet,
2168 BeginRange, BeginExpr);
2170 if (RangeStatus != Sema::FRS_Success) {
2171 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2172 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2173 << ColonLoc << BEF_begin << BeginRange->getType();
2176 if (!CoawaitLoc.isInvalid()) {
2177 // FIXME: getCurScope() should not be used during template instantiation.
2178 // We should pick up the set of unqualified lookup results for operator
2179 // co_await during the initial parse.
2180 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2182 if (BeginExpr->isInvalid())
2183 return Sema::FRS_DiagnosticIssued;
2185 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2186 diag::err_for_range_iter_deduction_failure)) {
2187 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2188 return Sema::FRS_DiagnosticIssued;
2193 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2194 EndMemberLookup, CandidateSet,
2196 if (RangeStatus != Sema::FRS_Success) {
2197 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2198 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2199 << ColonLoc << BEF_end << EndRange->getType();
2202 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2203 diag::err_for_range_iter_deduction_failure)) {
2204 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2205 return Sema::FRS_DiagnosticIssued;
2207 return Sema::FRS_Success;
2210 /// Speculatively attempt to dereference an invalid range expression.
2211 /// If the attempt fails, this function will return a valid, null StmtResult
2212 /// and emit no diagnostics.
2213 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2214 SourceLocation ForLoc,
2215 SourceLocation CoawaitLoc,
2217 SourceLocation ColonLoc,
2219 SourceLocation RangeLoc,
2220 SourceLocation RParenLoc) {
2221 // Determine whether we can rebuild the for-range statement with a
2222 // dereferenced range expression.
2223 ExprResult AdjustedRange;
2225 Sema::SFINAETrap Trap(SemaRef);
2227 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2228 if (AdjustedRange.isInvalid())
2229 return StmtResult();
2231 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2232 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2233 RParenLoc, Sema::BFRK_Check);
2235 return StmtResult();
2238 // The attempt to dereference worked well enough that it could produce a valid
2239 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2240 // case there are any other (non-fatal) problems with it.
2241 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2242 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2243 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2244 ColonLoc, AdjustedRange.get(), RParenLoc,
2245 Sema::BFRK_Rebuild);
2249 /// RAII object to automatically invalidate a declaration if an error occurs.
2250 struct InvalidateOnErrorScope {
2251 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2252 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2253 ~InvalidateOnErrorScope() {
2254 if (Enabled && Trap.hasErrorOccurred())
2255 D->setInvalidDecl();
2258 DiagnosticErrorTrap Trap;
2264 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2266 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2267 SourceLocation ColonLoc, Stmt *RangeDecl,
2268 Stmt *Begin, Stmt *End, Expr *Cond,
2269 Expr *Inc, Stmt *LoopVarDecl,
2270 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2271 // FIXME: This should not be used during template instantiation. We should
2272 // pick up the set of unqualified lookup results for the != and + operators
2273 // in the initial parse.
2275 // Testcase (accepts-invalid):
2276 // template<typename T> void f() { for (auto x : T()) {} }
2277 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2278 // bool operator!=(N::X, N::X); void operator++(N::X);
2279 // void g() { f<N::X>(); }
2280 Scope *S = getCurScope();
2282 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2283 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2284 QualType RangeVarType = RangeVar->getType();
2286 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2287 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2289 // If we hit any errors, mark the loop variable as invalid if its type
2291 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2292 LoopVar->getType()->isUndeducedType());
2294 StmtResult BeginDeclStmt = Begin;
2295 StmtResult EndDeclStmt = End;
2296 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2298 if (RangeVarType->isDependentType()) {
2299 // The range is implicitly used as a placeholder when it is dependent.
2300 RangeVar->markUsed(Context);
2302 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2303 // them in properly when we instantiate the loop.
2304 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2305 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2306 for (auto *Binding : DD->bindings())
2307 Binding->setType(Context.DependentTy);
2308 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2310 } else if (!BeginDeclStmt.get()) {
2311 SourceLocation RangeLoc = RangeVar->getLocation();
2313 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2315 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2316 VK_LValue, ColonLoc);
2317 if (BeginRangeRef.isInvalid())
2320 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2321 VK_LValue, ColonLoc);
2322 if (EndRangeRef.isInvalid())
2325 QualType AutoType = Context.getAutoDeductType();
2326 Expr *Range = RangeVar->getInit();
2329 QualType RangeType = Range->getType();
2331 if (RequireCompleteType(RangeLoc, RangeType,
2332 diag::err_for_range_incomplete_type))
2335 // Build auto __begin = begin-expr, __end = end-expr.
2336 // Divide by 2, since the variables are in the inner scope (loop body).
2337 const auto DepthStr = std::to_string(S->getDepth() / 2);
2338 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2339 std::string("__begin") + DepthStr);
2340 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2341 std::string("__end") + DepthStr);
2343 // Build begin-expr and end-expr and attach to __begin and __end variables.
2344 ExprResult BeginExpr, EndExpr;
2345 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2346 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2347 // __range + __bound, respectively, where __bound is the array bound. If
2348 // _RangeT is an array of unknown size or an array of incomplete type,
2349 // the program is ill-formed;
2351 // begin-expr is __range.
2352 BeginExpr = BeginRangeRef;
2353 if (!CoawaitLoc.isInvalid()) {
2354 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2355 if (BeginExpr.isInvalid())
2358 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2359 diag::err_for_range_iter_deduction_failure)) {
2360 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2364 // Find the array bound.
2365 ExprResult BoundExpr;
2366 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2367 BoundExpr = IntegerLiteral::Create(
2368 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2369 else if (const VariableArrayType *VAT =
2370 dyn_cast<VariableArrayType>(UnqAT)) {
2371 // For a variably modified type we can't just use the expression within
2372 // the array bounds, since we don't want that to be re-evaluated here.
2373 // Rather, we need to determine what it was when the array was first
2374 // created - so we resort to using sizeof(vla)/sizeof(element).
2378 // b = -1; <-- This should not affect the num of iterations below
2379 // for (int &c : vla) { .. }
2382 // FIXME: This results in codegen generating IR that recalculates the
2383 // run-time number of elements (as opposed to just using the IR Value
2384 // that corresponds to the run-time value of each bound that was
2385 // generated when the array was created.) If this proves too embarrassing
2386 // even for unoptimized IR, consider passing a magic-value/cookie to
2387 // codegen that then knows to simply use that initial llvm::Value (that
2388 // corresponds to the bound at time of array creation) within
2389 // getelementptr. But be prepared to pay the price of increasing a
2390 // customized form of coupling between the two components - which could
2391 // be hard to maintain as the codebase evolves.
2393 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2394 EndVar->getLocation(), UETT_SizeOf,
2396 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2397 VAT->desugar(), RangeLoc))
2399 EndVar->getSourceRange());
2400 if (SizeOfVLAExprR.isInvalid())
2403 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2404 EndVar->getLocation(), UETT_SizeOf,
2406 CreateParsedType(VAT->desugar(),
2407 Context.getTrivialTypeSourceInfo(
2408 VAT->getElementType(), RangeLoc))
2410 EndVar->getSourceRange());
2411 if (SizeOfEachElementExprR.isInvalid())
2415 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2416 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2417 if (BoundExpr.isInvalid())
2421 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2422 // UnqAT is not incomplete and Range is not type-dependent.
2423 llvm_unreachable("Unexpected array type in for-range");
2426 // end-expr is __range + __bound.
2427 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2429 if (EndExpr.isInvalid())
2431 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2432 diag::err_for_range_iter_deduction_failure)) {
2433 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2437 OverloadCandidateSet CandidateSet(RangeLoc,
2438 OverloadCandidateSet::CSK_Normal);
2439 BeginEndFunction BEFFailure;
2440 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2441 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2442 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2445 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2446 BEFFailure == BEF_begin) {
2447 // If the range is being built from an array parameter, emit a
2448 // a diagnostic that it is being treated as a pointer.
2449 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2450 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2451 QualType ArrayTy = PVD->getOriginalType();
2452 QualType PointerTy = PVD->getType();
2453 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2454 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2455 << RangeLoc << PVD << ArrayTy << PointerTy;
2456 Diag(PVD->getLocation(), diag::note_declared_at);
2462 // If building the range failed, try dereferencing the range expression
2463 // unless a diagnostic was issued or the end function is problematic.
2464 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2466 LoopVarDecl, ColonLoc,
2469 if (SR.isInvalid() || SR.isUsable())
2473 // Otherwise, emit diagnostics if we haven't already.
2474 if (RangeStatus == FRS_NoViableFunction) {
2475 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2476 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2477 << RangeLoc << Range->getType() << BEFFailure;
2478 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2480 // Return an error if no fix was discovered.
2481 if (RangeStatus != FRS_Success)
2485 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2486 "invalid range expression in for loop");
2488 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2489 // C++1z removes this restriction.
2490 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2491 if (!Context.hasSameType(BeginType, EndType)) {
2492 Diag(RangeLoc, getLangOpts().CPlusPlus17
2493 ? diag::warn_for_range_begin_end_types_differ
2494 : diag::ext_for_range_begin_end_types_differ)
2495 << BeginType << EndType;
2496 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2497 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2501 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2503 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2505 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2506 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2507 VK_LValue, ColonLoc);
2508 if (BeginRef.isInvalid())
2511 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2512 VK_LValue, ColonLoc);
2513 if (EndRef.isInvalid())
2516 // Build and check __begin != __end expression.
2517 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2518 BeginRef.get(), EndRef.get());
2519 if (!NotEqExpr.isInvalid())
2520 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2521 if (!NotEqExpr.isInvalid())
2522 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2523 if (NotEqExpr.isInvalid()) {
2524 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2525 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2526 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2527 if (!Context.hasSameType(BeginType, EndType))
2528 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2532 // Build and check ++__begin expression.
2533 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2534 VK_LValue, ColonLoc);
2535 if (BeginRef.isInvalid())
2538 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2539 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2540 // FIXME: getCurScope() should not be used during template instantiation.
2541 // We should pick up the set of unqualified lookup results for operator
2542 // co_await during the initial parse.
2543 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2544 if (!IncrExpr.isInvalid())
2545 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2546 if (IncrExpr.isInvalid()) {
2547 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2548 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2549 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2553 // Build and check *__begin expression.
2554 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2555 VK_LValue, ColonLoc);
2556 if (BeginRef.isInvalid())
2559 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2560 if (DerefExpr.isInvalid()) {
2561 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2562 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2563 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2567 // Attach *__begin as initializer for VD. Don't touch it if we're just
2568 // trying to determine whether this would be a valid range.
2569 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2570 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2571 if (LoopVar->isInvalidDecl())
2572 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2576 // Don't bother to actually allocate the result if we're just trying to
2577 // determine whether it would be valid.
2578 if (Kind == BFRK_Check)
2579 return StmtResult();
2581 return new (Context) CXXForRangeStmt(
2582 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2583 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2584 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2585 ColonLoc, RParenLoc);
2588 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2590 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2593 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2595 ForStmt->setBody(B);
2599 // Warn when the loop variable is a const reference that creates a copy.
2600 // Suggest using the non-reference type for copies. If a copy can be prevented
2601 // suggest the const reference type that would do so.
2602 // For instance, given "for (const &Foo : Range)", suggest
2603 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2604 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2605 // the copy altogether.
2606 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2608 QualType RangeInitType) {
2609 const Expr *InitExpr = VD->getInit();
2613 QualType VariableType = VD->getType();
2615 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2616 if (!Cleanups->cleanupsHaveSideEffects())
2617 InitExpr = Cleanups->getSubExpr();
2619 const MaterializeTemporaryExpr *MTE =
2620 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2626 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2628 // Searching for either UnaryOperator for dereference of a pointer or
2629 // CXXOperatorCallExpr for handling iterators.
2630 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2631 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2633 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2634 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2637 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2638 E = MTE->GetTemporaryExpr();
2640 E = E->IgnoreImpCasts();
2643 bool ReturnsReference = false;
2644 if (isa<UnaryOperator>(E)) {
2645 ReturnsReference = true;
2647 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2648 const FunctionDecl *FD = Call->getDirectCallee();
2649 QualType ReturnType = FD->getReturnType();
2650 ReturnsReference = ReturnType->isReferenceType();
2653 if (ReturnsReference) {
2654 // Loop variable creates a temporary. Suggest either to go with
2655 // non-reference loop variable to indicate a copy is made, or
2656 // the correct time to bind a const reference.
2657 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2658 << VD << VariableType << E->getType();
2659 QualType NonReferenceType = VariableType.getNonReferenceType();
2660 NonReferenceType.removeLocalConst();
2661 QualType NewReferenceType =
2662 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2663 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2664 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2666 // The range always returns a copy, so a temporary is always created.
2667 // Suggest removing the reference from the loop variable.
2668 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2669 << VD << RangeInitType;
2670 QualType NonReferenceType = VariableType.getNonReferenceType();
2671 NonReferenceType.removeLocalConst();
2672 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2673 << NonReferenceType << VD->getSourceRange();
2677 // Warns when the loop variable can be changed to a reference type to
2678 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2679 // "for (const Foo &x : Range)" if this form does not make a copy.
2680 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2681 const VarDecl *VD) {
2682 const Expr *InitExpr = VD->getInit();
2686 QualType VariableType = VD->getType();
2688 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2689 if (!CE->getConstructor()->isCopyConstructor())
2691 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2692 if (CE->getCastKind() != CK_LValueToRValue)
2698 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2699 // should be emitted. Also, only ignore POD types with trivial copy
2701 if (VariableType.isPODType(SemaRef.Context))
2704 // Suggest changing from a const variable to a const reference variable
2705 // if doing so will prevent a copy.
2706 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2707 << VD << VariableType << InitExpr->getType();
2708 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2709 << SemaRef.Context.getLValueReferenceType(VariableType)
2710 << VD->getSourceRange();
2713 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2714 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2715 /// using "const foo x" to show that a copy is made
2716 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2717 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2718 /// prevent the copy.
2719 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2720 /// Suggest "const foo &x" to prevent the copy.
2721 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2722 const CXXForRangeStmt *ForStmt) {
2723 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2724 ForStmt->getLocStart()) &&
2725 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2726 ForStmt->getLocStart()) &&
2727 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2728 ForStmt->getLocStart())) {
2732 const VarDecl *VD = ForStmt->getLoopVariable();
2736 QualType VariableType = VD->getType();
2738 if (VariableType->isIncompleteType())
2741 const Expr *InitExpr = VD->getInit();
2745 if (VariableType->isReferenceType()) {
2746 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2747 ForStmt->getRangeInit()->getType());
2748 } else if (VariableType.isConstQualified()) {
2749 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2753 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2754 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2755 /// body cannot be performed until after the type of the range variable is
2757 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2761 if (isa<ObjCForCollectionStmt>(S))
2762 return FinishObjCForCollectionStmt(S, B);
2764 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2765 ForStmt->setBody(B);
2767 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2768 diag::warn_empty_range_based_for_body);
2770 DiagnoseForRangeVariableCopies(*this, ForStmt);
2775 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2776 SourceLocation LabelLoc,
2777 LabelDecl *TheDecl) {
2778 setFunctionHasBranchIntoScope();
2779 TheDecl->markUsed(Context);
2780 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2784 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2786 // Convert operand to void*
2787 if (!E->isTypeDependent()) {
2788 QualType ETy = E->getType();
2789 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2790 ExprResult ExprRes = E;
2791 AssignConvertType ConvTy =
2792 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2793 if (ExprRes.isInvalid())
2796 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2800 ExprResult ExprRes = ActOnFinishFullExpr(E);
2801 if (ExprRes.isInvalid())
2805 setFunctionHasIndirectGoto();
2807 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2810 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2811 const Scope &DestScope) {
2812 if (!S.CurrentSEHFinally.empty() &&
2813 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2814 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2819 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2820 Scope *S = CurScope->getContinueParent();
2822 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2823 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2825 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2827 return new (Context) ContinueStmt(ContinueLoc);
2831 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2832 Scope *S = CurScope->getBreakParent();
2834 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2835 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2837 if (S->isOpenMPLoopScope())
2838 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2840 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2842 return new (Context) BreakStmt(BreakLoc);
2845 /// Determine whether the given expression is a candidate for
2846 /// copy elision in either a return statement or a throw expression.
2848 /// \param ReturnType If we're determining the copy elision candidate for
2849 /// a return statement, this is the return type of the function. If we're
2850 /// determining the copy elision candidate for a throw expression, this will
2853 /// \param E The expression being returned from the function or block, or
2856 /// \param CESK Whether we allow function parameters or
2857 /// id-expressions that could be moved out of the function to be considered NRVO
2858 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2859 /// determine whether we should try to move as part of a return or throw (which
2860 /// does allow function parameters).
2862 /// \returns The NRVO candidate variable, if the return statement may use the
2863 /// NRVO, or NULL if there is no such candidate.
2864 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2865 CopyElisionSemanticsKind CESK) {
2866 // - in a return statement in a function [where] ...
2867 // ... the expression is the name of a non-volatile automatic object ...
2868 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2869 if (!DR || DR->refersToEnclosingVariableOrCapture())
2871 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2875 if (isCopyElisionCandidate(ReturnType, VD, CESK))
2880 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2881 CopyElisionSemanticsKind CESK) {
2882 QualType VDType = VD->getType();
2883 // - in a return statement in a function with ...
2884 // ... a class return type ...
2885 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2886 if (!ReturnType->isRecordType())
2888 // ... the same cv-unqualified type as the function return type ...
2889 // When considering moving this expression out, allow dissimilar types.
2890 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
2891 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2895 // ...object (other than a function or catch-clause parameter)...
2896 if (VD->getKind() != Decl::Var &&
2897 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
2899 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2903 if (!VD->hasLocalStorage()) return false;
2905 // Return false if VD is a __block variable. We don't want to implicitly move
2906 // out of a __block variable during a return because we cannot assume the
2907 // variable will no longer be used.
2908 if (VD->hasAttr<BlocksAttr>()) return false;
2910 if (CESK & CES_AllowDifferentTypes)
2913 // ...non-volatile...
2914 if (VD->getType().isVolatileQualified()) return false;
2916 // Variables with higher required alignment than their type's ABI
2917 // alignment cannot use NRVO.
2918 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2919 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2925 /// Try to perform the initialization of a potentially-movable value,
2926 /// which is the operand to a return or throw statement.
2928 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2929 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2930 /// then falls back to treating them as lvalues if that failed.
2932 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2933 /// resolutions that find non-constructors, such as derived-to-base conversions
2934 /// or `operator T()&&` member functions. If false, do consider such
2935 /// conversion sequences.
2937 /// \param Res We will fill this in if move-initialization was possible.
2938 /// If move-initialization is not possible, such that we must fall back to
2939 /// treating the operand as an lvalue, we will leave Res in its original
2941 static void TryMoveInitialization(Sema& S,
2942 const InitializedEntity &Entity,
2943 const VarDecl *NRVOCandidate,
2944 QualType ResultType,
2946 bool ConvertingConstructorsOnly,
2948 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2949 CK_NoOp, Value, VK_XValue);
2951 Expr *InitExpr = &AsRvalue;
2953 InitializationKind Kind = InitializationKind::CreateCopy(
2954 Value->getLocStart(), Value->getLocStart());
2956 InitializationSequence Seq(S, Entity, Kind, InitExpr);
2961 for (const InitializationSequence::Step &Step : Seq.steps()) {
2962 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
2963 Step.Kind != InitializationSequence::SK_UserConversion)
2966 FunctionDecl *FD = Step.Function.Function;
2967 if (ConvertingConstructorsOnly) {
2968 if (isa<CXXConstructorDecl>(FD)) {
2969 // C++14 [class.copy]p32:
2970 // [...] If the first overload resolution fails or was not performed,
2971 // or if the type of the first parameter of the selected constructor
2972 // is not an rvalue reference to the object's type (possibly
2973 // cv-qualified), overload resolution is performed again, considering
2974 // the object as an lvalue.
2975 const RValueReferenceType *RRefType =
2976 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
2979 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2980 NRVOCandidate->getType()))
2986 if (isa<CXXConstructorDecl>(FD)) {
2987 // Check that overload resolution selected a constructor taking an
2988 // rvalue reference. If it selected an lvalue reference, then we
2989 // didn't need to cast this thing to an rvalue in the first place.
2990 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
2992 } else if (isa<CXXMethodDecl>(FD)) {
2993 // Check that overload resolution selected a conversion operator
2994 // taking an rvalue reference.
2995 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3002 // Promote "AsRvalue" to the heap, since we now need this
3003 // expression node to persist.
3004 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3005 Value, nullptr, VK_XValue);
3007 // Complete type-checking the initialization of the return type
3008 // using the constructor we found.
3009 Res = Seq.Perform(S, Entity, Kind, Value);
3013 /// Perform the initialization of a potentially-movable value, which
3014 /// is the result of return value.
3016 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3017 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3018 /// then falls back to treating them as lvalues if that failed.
3020 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3021 const VarDecl *NRVOCandidate,
3022 QualType ResultType,
3025 // C++14 [class.copy]p32:
3026 // When the criteria for elision of a copy/move operation are met, but not for
3027 // an exception-declaration, and the object to be copied is designated by an
3028 // lvalue, or when the expression in a return statement is a (possibly
3029 // parenthesized) id-expression that names an object with automatic storage
3030 // duration declared in the body or parameter-declaration-clause of the
3031 // innermost enclosing function or lambda-expression, overload resolution to
3032 // select the constructor for the copy is first performed as if the object
3033 // were designated by an rvalue.
3034 ExprResult Res = ExprError();
3037 bool AffectedByCWG1579 = false;
3039 if (!NRVOCandidate) {
3040 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3041 if (NRVOCandidate &&
3042 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3043 Value->getExprLoc())) {
3044 const VarDecl *NRVOCandidateInCXX11 =
3045 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3046 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3050 if (NRVOCandidate) {
3051 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3055 if (!Res.isInvalid() && AffectedByCWG1579) {
3056 QualType QT = NRVOCandidate->getType();
3057 if (QT.getNonReferenceType()
3058 .getUnqualifiedType()
3059 .isTriviallyCopyableType(Context)) {
3060 // Adding 'std::move' around a trivially copyable variable is probably
3061 // pointless. Don't suggest it.
3063 // Common cases for this are returning unique_ptr<Derived> from a
3064 // function of return type unique_ptr<Base>, or returning T from a
3065 // function of return type Expected<T>. This is totally fine in a
3066 // post-CWG1579 world, but was not fine before.
3067 assert(!ResultType.isNull());
3068 SmallString<32> Str;
3069 Str += "std::move(";
3070 Str += NRVOCandidate->getDeclName().getAsString();
3072 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3073 << Value->getSourceRange()
3074 << NRVOCandidate->getDeclName() << ResultType << QT;
3075 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3076 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3078 } else if (Res.isInvalid() &&
3079 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3080 Value->getExprLoc())) {
3081 const VarDecl *FakeNRVOCandidate =
3082 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3083 if (FakeNRVOCandidate) {
3084 QualType QT = FakeNRVOCandidate->getType();
3085 if (QT->isLValueReferenceType()) {
3086 // Adding 'std::move' around an lvalue reference variable's name is
3087 // dangerous. Don't suggest it.
3088 } else if (QT.getNonReferenceType()
3089 .getUnqualifiedType()
3090 .isTriviallyCopyableType(Context)) {
3091 // Adding 'std::move' around a trivially copyable variable is probably
3092 // pointless. Don't suggest it.
3094 ExprResult FakeRes = ExprError();
3095 Expr *FakeValue = Value;
3096 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3097 FakeValue, false, FakeRes);
3098 if (!FakeRes.isInvalid()) {
3100 (Entity.getKind() == InitializedEntity::EK_Exception);
3101 SmallString<32> Str;
3102 Str += "std::move(";
3103 Str += FakeNRVOCandidate->getDeclName().getAsString();
3105 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3106 << Value->getSourceRange()
3107 << FakeNRVOCandidate->getDeclName() << IsThrow;
3108 Diag(Value->getExprLoc(), diag::note_add_std_move)
3109 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3116 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3117 // above, or overload resolution failed. Either way, we need to try
3118 // (again) now with the return value expression as written.
3119 if (Res.isInvalid())
3120 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3125 /// Determine whether the declared return type of the specified function
3126 /// contains 'auto'.
3127 static bool hasDeducedReturnType(FunctionDecl *FD) {
3128 const FunctionProtoType *FPT =
3129 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3130 return FPT->getReturnType()->isUndeducedType();
3133 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3134 /// for capturing scopes.
3137 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3138 // If this is the first return we've seen, infer the return type.
3139 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3140 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3141 QualType FnRetType = CurCap->ReturnType;
3142 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3143 bool HasDeducedReturnType =
3144 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3146 if (ExprEvalContexts.back().Context ==
3147 ExpressionEvaluationContext::DiscardedStatement &&
3148 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3150 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3153 RetValExp = ER.get();
3155 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3158 if (HasDeducedReturnType) {
3159 // In C++1y, the return type may involve 'auto'.
3160 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3161 FunctionDecl *FD = CurLambda->CallOperator;
3162 if (CurCap->ReturnType.isNull())
3163 CurCap->ReturnType = FD->getReturnType();
3165 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3166 assert(AT && "lost auto type from lambda return type");
3167 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3168 FD->setInvalidDecl();
3171 CurCap->ReturnType = FnRetType = FD->getReturnType();
3172 } else if (CurCap->HasImplicitReturnType) {
3173 // For blocks/lambdas with implicit return types, we check each return
3174 // statement individually, and deduce the common return type when the block
3175 // or lambda is completed.
3176 // FIXME: Fold this into the 'auto' codepath above.
3177 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3178 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3179 if (Result.isInvalid())
3181 RetValExp = Result.get();
3183 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3184 // when deducing a return type for a lambda-expression (or by extension
3185 // for a block). These rules differ from the stated C++11 rules only in
3186 // that they remove top-level cv-qualifiers.
3187 if (!CurContext->isDependentContext())
3188 FnRetType = RetValExp->getType().getUnqualifiedType();
3190 FnRetType = CurCap->ReturnType = Context.DependentTy;
3193 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3194 // initializer list, because it is not an expression (even
3195 // though we represent it as one). We still deduce 'void'.
3196 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3197 << RetValExp->getSourceRange();
3200 FnRetType = Context.VoidTy;
3203 // Although we'll properly infer the type of the block once it's completed,
3204 // make sure we provide a return type now for better error recovery.
3205 if (CurCap->ReturnType.isNull())
3206 CurCap->ReturnType = FnRetType;
3208 assert(!FnRetType.isNull());
3210 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3211 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3212 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3215 } else if (CapturedRegionScopeInfo *CurRegion =
3216 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3217 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3220 assert(CurLambda && "unknown kind of captured scope");
3221 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3222 ->getNoReturnAttr()) {
3223 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3228 // Otherwise, verify that this result type matches the previous one. We are
3229 // pickier with blocks than for normal functions because we don't have GCC
3230 // compatibility to worry about here.
3231 const VarDecl *NRVOCandidate = nullptr;
3232 if (FnRetType->isDependentType()) {
3233 // Delay processing for now. TODO: there are lots of dependent
3234 // types we can conclusively prove aren't void.
3235 } else if (FnRetType->isVoidType()) {
3236 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3237 !(getLangOpts().CPlusPlus &&
3238 (RetValExp->isTypeDependent() ||
3239 RetValExp->getType()->isVoidType()))) {
3240 if (!getLangOpts().CPlusPlus &&
3241 RetValExp->getType()->isVoidType())
3242 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3244 Diag(ReturnLoc, diag::err_return_block_has_expr);
3245 RetValExp = nullptr;
3248 } else if (!RetValExp) {
3249 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3250 } else if (!RetValExp->isTypeDependent()) {
3251 // we have a non-void block with an expression, continue checking
3253 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3254 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3257 // In C++ the return statement is handled via a copy initialization.
3258 // the C version of which boils down to CheckSingleAssignmentConstraints.
3259 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3260 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3262 NRVOCandidate != nullptr);
3263 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3264 FnRetType, RetValExp);
3265 if (Res.isInvalid()) {
3266 // FIXME: Cleanup temporaries here, anyway?
3269 RetValExp = Res.get();
3270 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3272 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3276 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3279 RetValExp = ER.get();
3281 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3284 // If we need to check for the named return value optimization,
3285 // or if we need to infer the return type,
3286 // save the return statement in our scope for later processing.
3287 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3288 FunctionScopes.back()->Returns.push_back(Result);
3290 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3291 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3297 /// Marks all typedefs in all local classes in a type referenced.
3299 /// In a function like
3301 /// struct S { typedef int a; };
3305 /// the local type escapes and could be referenced in some TUs but not in
3306 /// others. Pretend that all local typedefs are always referenced, to not warn
3307 /// on this. This isn't necessary if f has internal linkage, or the typedef
3309 class LocalTypedefNameReferencer
3310 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3312 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3313 bool VisitRecordType(const RecordType *RT);
3317 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3318 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3319 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3320 R->isDependentType())
3322 for (auto *TmpD : R->decls())
3323 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3324 if (T->getAccess() != AS_private || R->hasFriends())
3325 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3330 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3331 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3332 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3333 TL = ATL.getModifiedLoc().IgnoreParens();
3334 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3337 /// Deduce the return type for a function from a returned expression, per
3338 /// C++1y [dcl.spec.auto]p6.
3339 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3340 SourceLocation ReturnLoc,
3343 // If this is the conversion function for a lambda, we choose to deduce it
3344 // type from the corresponding call operator, not from the synthesized return
3345 // statement within it. See Sema::DeduceReturnType.
3346 if (isLambdaConversionOperator(FD))
3349 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3352 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3353 // If the deduction is for a return statement and the initializer is
3354 // a braced-init-list, the program is ill-formed.
3355 Diag(RetExpr->getExprLoc(),
3356 getCurLambda() ? diag::err_lambda_return_init_list
3357 : diag::err_auto_fn_return_init_list)
3358 << RetExpr->getSourceRange();
3362 if (FD->isDependentContext()) {
3363 // C++1y [dcl.spec.auto]p12:
3364 // Return type deduction [...] occurs when the definition is
3365 // instantiated even if the function body contains a return
3366 // statement with a non-type-dependent operand.
3367 assert(AT->isDeduced() && "should have deduced to dependent type");
3372 // Otherwise, [...] deduce a value for U using the rules of template
3373 // argument deduction.
3374 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3376 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3377 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3378 << OrigResultType.getType() << RetExpr->getType();
3380 if (DAR != DAR_Succeeded)
3383 // If a local type is part of the returned type, mark its fields as
3385 LocalTypedefNameReferencer Referencer(*this);
3386 Referencer.TraverseType(RetExpr->getType());
3388 // In the case of a return with no operand, the initializer is considered
3391 // Deduction here can only succeed if the return type is exactly 'cv auto'
3392 // or 'decltype(auto)', so just check for that case directly.
3393 if (!OrigResultType.getType()->getAs<AutoType>()) {
3394 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3395 << OrigResultType.getType();
3398 // We always deduce U = void in this case.
3399 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3400 if (Deduced.isNull())
3404 // If a function with a declared return type that contains a placeholder type
3405 // has multiple return statements, the return type is deduced for each return
3406 // statement. [...] if the type deduced is not the same in each deduction,
3407 // the program is ill-formed.
3408 QualType DeducedT = AT->getDeducedType();
3409 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3410 AutoType *NewAT = Deduced->getContainedAutoType();
3411 // It is possible that NewAT->getDeducedType() is null. When that happens,
3412 // we should not crash, instead we ignore this deduction.
3413 if (NewAT->getDeducedType().isNull())
3416 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3418 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3419 NewAT->getDeducedType());
3420 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3421 const LambdaScopeInfo *LambdaSI = getCurLambda();
3422 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3423 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3424 << NewAT->getDeducedType() << DeducedT
3425 << true /*IsLambda*/;
3427 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3428 << (AT->isDecltypeAuto() ? 1 : 0)
3429 << NewAT->getDeducedType() << DeducedT;
3433 } else if (!FD->isInvalidDecl()) {
3434 // Update all declarations of the function to have the deduced return type.
3435 Context.adjustDeducedFunctionResultType(FD, Deduced);
3442 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3444 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3445 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3446 ExpressionEvaluationContext::DiscardedStatement)
3450 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3451 CurScope->addNRVOCandidate(VD);
3453 CurScope->setNoNRVO();
3456 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3461 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3462 // Check for unexpanded parameter packs.
3463 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3466 if (isa<CapturingScopeInfo>(getCurFunction()))
3467 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3470 QualType RelatedRetType;
3471 const AttrVec *Attrs = nullptr;
3472 bool isObjCMethod = false;
3474 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3475 FnRetType = FD->getReturnType();
3477 Attrs = &FD->getAttrs();
3478 if (FD->isNoReturn())
3479 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3480 << FD->getDeclName();
3481 if (FD->isMain() && RetValExp)
3482 if (isa<CXXBoolLiteralExpr>(RetValExp))
3483 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3484 << RetValExp->getSourceRange();
3485 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3486 FnRetType = MD->getReturnType();
3487 isObjCMethod = true;
3489 Attrs = &MD->getAttrs();
3490 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3491 // In the implementation of a method with a related return type, the
3492 // type used to type-check the validity of return statements within the
3493 // method body is a pointer to the type of the class being implemented.
3494 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3495 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3497 } else // If we don't have a function/method context, bail.
3500 // C++1z: discarded return statements are not considered when deducing a
3502 if (ExprEvalContexts.back().Context ==
3503 ExpressionEvaluationContext::DiscardedStatement &&
3504 FnRetType->getContainedAutoType()) {
3506 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3509 RetValExp = ER.get();
3511 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3514 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3516 if (getLangOpts().CPlusPlus14) {
3517 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3518 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3519 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3520 FD->setInvalidDecl();
3523 FnRetType = FD->getReturnType();
3528 bool HasDependentReturnType = FnRetType->isDependentType();
3530 ReturnStmt *Result = nullptr;
3531 if (FnRetType->isVoidType()) {
3533 if (isa<InitListExpr>(RetValExp)) {
3534 // We simply never allow init lists as the return value of void
3535 // functions. This is compatible because this was never allowed before,
3536 // so there's no legacy code to deal with.
3537 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3538 int FunctionKind = 0;
3539 if (isa<ObjCMethodDecl>(CurDecl))
3541 else if (isa<CXXConstructorDecl>(CurDecl))
3543 else if (isa<CXXDestructorDecl>(CurDecl))
3546 Diag(ReturnLoc, diag::err_return_init_list)
3547 << CurDecl->getDeclName() << FunctionKind
3548 << RetValExp->getSourceRange();
3550 // Drop the expression.
3551 RetValExp = nullptr;
3552 } else if (!RetValExp->isTypeDependent()) {
3553 // C99 6.8.6.4p1 (ext_ since GCC warns)
3554 unsigned D = diag::ext_return_has_expr;
3555 if (RetValExp->getType()->isVoidType()) {
3556 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3557 if (isa<CXXConstructorDecl>(CurDecl) ||
3558 isa<CXXDestructorDecl>(CurDecl))
3559 D = diag::err_ctor_dtor_returns_void;
3561 D = diag::ext_return_has_void_expr;
3564 ExprResult Result = RetValExp;
3565 Result = IgnoredValueConversions(Result.get());
3566 if (Result.isInvalid())
3568 RetValExp = Result.get();
3569 RetValExp = ImpCastExprToType(RetValExp,
3570 Context.VoidTy, CK_ToVoid).get();
3572 // return of void in constructor/destructor is illegal in C++.
3573 if (D == diag::err_ctor_dtor_returns_void) {
3574 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3576 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3577 << RetValExp->getSourceRange();
3579 // return (some void expression); is legal in C++.
3580 else if (D != diag::ext_return_has_void_expr ||
3581 !getLangOpts().CPlusPlus) {
3582 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3584 int FunctionKind = 0;
3585 if (isa<ObjCMethodDecl>(CurDecl))
3587 else if (isa<CXXConstructorDecl>(CurDecl))
3589 else if (isa<CXXDestructorDecl>(CurDecl))
3593 << CurDecl->getDeclName() << FunctionKind
3594 << RetValExp->getSourceRange();
3599 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3602 RetValExp = ER.get();
3606 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3607 } else if (!RetValExp && !HasDependentReturnType) {
3608 FunctionDecl *FD = getCurFunctionDecl();
3611 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3612 // C++11 [stmt.return]p2
3613 DiagID = diag::err_constexpr_return_missing_expr;
3614 FD->setInvalidDecl();
3615 } else if (getLangOpts().C99) {
3616 // C99 6.8.6.4p1 (ext_ since GCC warns)
3617 DiagID = diag::ext_return_missing_expr;
3620 DiagID = diag::warn_return_missing_expr;
3624 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3626 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3628 Result = new (Context) ReturnStmt(ReturnLoc);
3630 assert(RetValExp || HasDependentReturnType);
3631 const VarDecl *NRVOCandidate = nullptr;
3633 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3635 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3636 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3639 // In C++ the return statement is handled via a copy initialization,
3640 // the C version of which boils down to CheckSingleAssignmentConstraints.
3642 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3643 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3644 // we have a non-void function with an expression, continue checking
3645 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3647 NRVOCandidate != nullptr);
3648 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3649 RetType, RetValExp);
3650 if (Res.isInvalid()) {
3651 // FIXME: Clean up temporaries here anyway?
3654 RetValExp = Res.getAs<Expr>();
3656 // If we have a related result type, we need to implicitly
3657 // convert back to the formal result type. We can't pretend to
3658 // initialize the result again --- we might end double-retaining
3659 // --- so instead we initialize a notional temporary.
3660 if (!RelatedRetType.isNull()) {
3661 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3663 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3664 if (Res.isInvalid()) {
3665 // FIXME: Clean up temporaries here anyway?
3668 RetValExp = Res.getAs<Expr>();
3671 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3672 getCurFunctionDecl());
3676 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3679 RetValExp = ER.get();
3681 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3684 // If we need to check for the named return value optimization, save the
3685 // return statement in our scope for later processing.
3686 if (Result->getNRVOCandidate())
3687 FunctionScopes.back()->Returns.push_back(Result);
3689 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3690 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3696 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3697 SourceLocation RParen, Decl *Parm,
3699 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3700 if (Var && Var->isInvalidDecl())
3703 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3707 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3708 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3712 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3713 MultiStmtArg CatchStmts, Stmt *Finally) {
3714 if (!getLangOpts().ObjCExceptions)
3715 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3717 setFunctionHasBranchProtectedScope();
3718 unsigned NumCatchStmts = CatchStmts.size();
3719 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3720 NumCatchStmts, Finally);
3723 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3725 ExprResult Result = DefaultLvalueConversion(Throw);
3726 if (Result.isInvalid())
3729 Result = ActOnFinishFullExpr(Result.get());
3730 if (Result.isInvalid())
3732 Throw = Result.get();
3734 QualType ThrowType = Throw->getType();
3735 // Make sure the expression type is an ObjC pointer or "void *".
3736 if (!ThrowType->isDependentType() &&
3737 !ThrowType->isObjCObjectPointerType()) {
3738 const PointerType *PT = ThrowType->getAs<PointerType>();
3739 if (!PT || !PT->getPointeeType()->isVoidType())
3740 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3741 << Throw->getType() << Throw->getSourceRange());
3745 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3749 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3751 if (!getLangOpts().ObjCExceptions)
3752 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3755 // @throw without an expression designates a rethrow (which must occur
3756 // in the context of an @catch clause).
3757 Scope *AtCatchParent = CurScope;
3758 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3759 AtCatchParent = AtCatchParent->getParent();
3761 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3763 return BuildObjCAtThrowStmt(AtLoc, Throw);
3767 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3768 ExprResult result = DefaultLvalueConversion(operand);
3769 if (result.isInvalid())
3771 operand = result.get();
3773 // Make sure the expression type is an ObjC pointer or "void *".
3774 QualType type = operand->getType();
3775 if (!type->isDependentType() &&
3776 !type->isObjCObjectPointerType()) {
3777 const PointerType *pointerType = type->getAs<PointerType>();
3778 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3779 if (getLangOpts().CPlusPlus) {
3780 if (RequireCompleteType(atLoc, type,
3781 diag::err_incomplete_receiver_type))
3782 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3783 << type << operand->getSourceRange();
3785 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3786 if (result.isInvalid())
3788 if (!result.isUsable())
3789 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3790 << type << operand->getSourceRange();
3792 operand = result.get();
3794 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3795 << type << operand->getSourceRange();
3800 // The operand to @synchronized is a full-expression.
3801 return ActOnFinishFullExpr(operand);
3805 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3807 // We can't jump into or indirect-jump out of a @synchronized block.
3808 setFunctionHasBranchProtectedScope();
3809 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3812 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3813 /// and creates a proper catch handler from them.
3815 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3816 Stmt *HandlerBlock) {
3817 // There's nothing to test that ActOnExceptionDecl didn't already test.
3818 return new (Context)
3819 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3823 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3824 setFunctionHasBranchProtectedScope();
3825 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3829 class CatchHandlerType {
3831 unsigned IsPointer : 1;
3833 // This is a special constructor to be used only with DenseMapInfo's
3834 // getEmptyKey() and getTombstoneKey() functions.
3835 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3836 enum Unique { ForDenseMap };
3837 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3840 /// Used when creating a CatchHandlerType from a handler type; will determine
3841 /// whether the type is a pointer or reference and will strip off the top
3842 /// level pointer and cv-qualifiers.
3843 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3844 if (QT->isPointerType())
3847 if (IsPointer || QT->isReferenceType())
3848 QT = QT->getPointeeType();
3849 QT = QT.getUnqualifiedType();
3852 /// Used when creating a CatchHandlerType from a base class type; pretends the
3853 /// type passed in had the pointer qualifier, does not need to get an
3854 /// unqualified type.
3855 CatchHandlerType(QualType QT, bool IsPointer)
3856 : QT(QT), IsPointer(IsPointer) {}
3858 QualType underlying() const { return QT; }
3859 bool isPointer() const { return IsPointer; }
3861 friend bool operator==(const CatchHandlerType &LHS,
3862 const CatchHandlerType &RHS) {
3863 // If the pointer qualification does not match, we can return early.
3864 if (LHS.IsPointer != RHS.IsPointer)
3866 // Otherwise, check the underlying type without cv-qualifiers.
3867 return LHS.QT == RHS.QT;
3873 template <> struct DenseMapInfo<CatchHandlerType> {
3874 static CatchHandlerType getEmptyKey() {
3875 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3876 CatchHandlerType::ForDenseMap);
3879 static CatchHandlerType getTombstoneKey() {
3880 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3881 CatchHandlerType::ForDenseMap);
3884 static unsigned getHashValue(const CatchHandlerType &Base) {
3885 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3888 static bool isEqual(const CatchHandlerType &LHS,
3889 const CatchHandlerType &RHS) {
3896 class CatchTypePublicBases {
3898 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3899 const bool CheckAgainstPointer;
3901 CXXCatchStmt *FoundHandler;
3902 CanQualType FoundHandlerType;
3905 CatchTypePublicBases(
3907 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3908 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3909 FoundHandler(nullptr) {}
3911 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3912 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3914 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3915 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3916 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3917 const auto &M = TypesToCheck;
3918 auto I = M.find(Check);
3920 FoundHandler = I->second;
3921 FoundHandlerType = Ctx.getCanonicalType(S->getType());
3930 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3931 /// handlers and creates a try statement from them.
3932 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3933 ArrayRef<Stmt *> Handlers) {
3934 // Don't report an error if 'try' is used in system headers.
3935 if (!getLangOpts().CXXExceptions &&
3936 !getSourceManager().isInSystemHeader(TryLoc) &&
3937 (!getLangOpts().OpenMPIsDevice ||
3938 !getLangOpts().OpenMPHostCXXExceptions ||
3939 isInOpenMPTargetExecutionDirective() ||
3940 isInOpenMPDeclareTargetContext()))
3941 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3943 // Exceptions aren't allowed in CUDA device code.
3944 if (getLangOpts().CUDA)
3945 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3946 << "try" << CurrentCUDATarget();
3948 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3949 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3951 sema::FunctionScopeInfo *FSI = getCurFunction();
3953 // C++ try is incompatible with SEH __try.
3954 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3955 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3956 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3959 const unsigned NumHandlers = Handlers.size();
3960 assert(!Handlers.empty() &&
3961 "The parser shouldn't call this if there are no handlers.");
3963 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3964 for (unsigned i = 0; i < NumHandlers; ++i) {
3965 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3967 // Diagnose when the handler is a catch-all handler, but it isn't the last
3968 // handler for the try block. [except.handle]p5. Also, skip exception
3969 // declarations that are invalid, since we can't usefully report on them.
3970 if (!H->getExceptionDecl()) {
3971 if (i < NumHandlers - 1)
3972 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3974 } else if (H->getExceptionDecl()->isInvalidDecl())
3977 // Walk the type hierarchy to diagnose when this type has already been
3978 // handled (duplication), or cannot be handled (derivation inversion). We
3979 // ignore top-level cv-qualifiers, per [except.handle]p3
3980 CatchHandlerType HandlerCHT =
3981 (QualType)Context.getCanonicalType(H->getCaughtType());
3983 // We can ignore whether the type is a reference or a pointer; we need the
3984 // underlying declaration type in order to get at the underlying record
3985 // decl, if there is one.
3986 QualType Underlying = HandlerCHT.underlying();
3987 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3988 if (!RD->hasDefinition())
3990 // Check that none of the public, unambiguous base classes are in the
3991 // map ([except.handle]p1). Give the base classes the same pointer
3992 // qualification as the original type we are basing off of. This allows
3993 // comparison against the handler type using the same top-level pointer
3994 // as the original type.
3996 Paths.setOrigin(RD);
3997 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3998 if (RD->lookupInBases(CTPB, Paths)) {
3999 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4000 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4001 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4002 diag::warn_exception_caught_by_earlier_handler)
4003 << H->getCaughtType();
4004 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4005 diag::note_previous_exception_handler)
4006 << Problem->getCaughtType();
4011 // Add the type the list of ones we have handled; diagnose if we've already
4013 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4015 const CXXCatchStmt *Problem = R.first->second;
4016 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4017 diag::warn_exception_caught_by_earlier_handler)
4018 << H->getCaughtType();
4019 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4020 diag::note_previous_exception_handler)
4021 << Problem->getCaughtType();
4025 FSI->setHasCXXTry(TryLoc);
4027 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4030 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4031 Stmt *TryBlock, Stmt *Handler) {
4032 assert(TryBlock && Handler);
4034 sema::FunctionScopeInfo *FSI = getCurFunction();
4036 // SEH __try is incompatible with C++ try. Borland appears to support this,
4038 if (!getLangOpts().Borland) {
4039 if (FSI->FirstCXXTryLoc.isValid()) {
4040 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4041 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4045 FSI->setHasSEHTry(TryLoc);
4047 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4048 // track if they use SEH.
4049 DeclContext *DC = CurContext;
4050 while (DC && !DC->isFunctionOrMethod())
4051 DC = DC->getParent();
4052 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4054 FD->setUsesSEHTry(true);
4056 Diag(TryLoc, diag::err_seh_try_outside_functions);
4058 // Reject __try on unsupported targets.
4059 if (!Context.getTargetInfo().isSEHTrySupported())
4060 Diag(TryLoc, diag::err_seh_try_unsupported);
4062 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4066 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4069 assert(FilterExpr && Block);
4071 if(!FilterExpr->getType()->isIntegerType()) {
4072 return StmtError(Diag(FilterExpr->getExprLoc(),
4073 diag::err_filter_expression_integral)
4074 << FilterExpr->getType());
4077 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
4080 void Sema::ActOnStartSEHFinallyBlock() {
4081 CurrentSEHFinally.push_back(CurScope);
4084 void Sema::ActOnAbortSEHFinallyBlock() {
4085 CurrentSEHFinally.pop_back();
4088 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4090 CurrentSEHFinally.pop_back();
4091 return SEHFinallyStmt::Create(Context, Loc, Block);
4095 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4096 Scope *SEHTryParent = CurScope;
4097 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4098 SEHTryParent = SEHTryParent->getParent();
4100 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4101 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4103 return new (Context) SEHLeaveStmt(Loc);
4106 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4108 NestedNameSpecifierLoc QualifierLoc,
4109 DeclarationNameInfo NameInfo,
4112 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4113 QualifierLoc, NameInfo,
4114 cast<CompoundStmt>(Nested));
4118 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4121 UnqualifiedId &Name,
4123 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4124 SS.getWithLocInContext(Context),
4125 GetNameFromUnqualifiedId(Name),
4130 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4131 unsigned NumParams) {
4132 DeclContext *DC = CurContext;
4133 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4134 DC = DC->getParent();
4136 RecordDecl *RD = nullptr;
4137 if (getLangOpts().CPlusPlus)
4138 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4141 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4143 RD->setCapturedRecord();
4146 RD->startDefinition();
4148 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4149 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4155 buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4156 SmallVectorImpl<Expr *> &CaptureInits,
4157 ArrayRef<sema::Capture> Candidates) {
4158 for (const sema::Capture &Cap : Candidates) {
4159 if (Cap.isThisCapture()) {
4160 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4161 CapturedStmt::VCK_This));
4162 CaptureInits.push_back(Cap.getInitExpr());
4164 } else if (Cap.isVLATypeCapture()) {
4166 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4167 CaptureInits.push_back(nullptr);
4171 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4172 Cap.isReferenceCapture()
4173 ? CapturedStmt::VCK_ByRef
4174 : CapturedStmt::VCK_ByCopy,
4175 Cap.getVariable()));
4176 CaptureInits.push_back(Cap.getInitExpr());
4180 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4181 CapturedRegionKind Kind,
4182 unsigned NumParams) {
4183 CapturedDecl *CD = nullptr;
4184 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4186 // Build the context parameter
4187 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4188 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4189 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4191 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4192 ImplicitParamDecl::CapturedContext);
4195 CD->setContextParam(0, Param);
4197 // Enter the capturing scope for this captured region.
4198 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4201 PushDeclContext(CurScope, CD);
4205 PushExpressionEvaluationContext(
4206 ExpressionEvaluationContext::PotentiallyEvaluated);
4209 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4210 CapturedRegionKind Kind,
4211 ArrayRef<CapturedParamNameType> Params) {
4212 CapturedDecl *CD = nullptr;
4213 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4215 // Build the context parameter
4216 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4217 bool ContextIsFound = false;
4218 unsigned ParamNum = 0;
4219 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4221 I != E; ++I, ++ParamNum) {
4222 if (I->second.isNull()) {
4223 assert(!ContextIsFound &&
4224 "null type has been found already for '__context' parameter");
4225 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4226 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4230 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4231 ImplicitParamDecl::CapturedContext);
4233 CD->setContextParam(ParamNum, Param);
4234 ContextIsFound = true;
4236 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4238 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4239 ImplicitParamDecl::CapturedContext);
4241 CD->setParam(ParamNum, Param);
4244 assert(ContextIsFound && "no null type for '__context' parameter");
4245 if (!ContextIsFound) {
4246 // Add __context implicitly if it is not specified.
4247 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4248 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4250 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4251 ImplicitParamDecl::CapturedContext);
4253 CD->setContextParam(ParamNum, Param);
4255 // Enter the capturing scope for this captured region.
4256 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4259 PushDeclContext(CurScope, CD);
4263 PushExpressionEvaluationContext(
4264 ExpressionEvaluationContext::PotentiallyEvaluated);
4267 void Sema::ActOnCapturedRegionError() {
4268 DiscardCleanupsInEvaluationContext();
4269 PopExpressionEvaluationContext();
4271 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4272 RecordDecl *Record = RSI->TheRecordDecl;
4273 Record->setInvalidDecl();
4275 SmallVector<Decl*, 4> Fields(Record->fields());
4276 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4277 SourceLocation(), SourceLocation(), ParsedAttributesView());
4280 PopFunctionScopeInfo();
4283 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4284 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4286 SmallVector<CapturedStmt::Capture, 4> Captures;
4287 SmallVector<Expr *, 4> CaptureInits;
4288 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4290 CapturedDecl *CD = RSI->TheCapturedDecl;
4291 RecordDecl *RD = RSI->TheRecordDecl;
4293 CapturedStmt *Res = CapturedStmt::Create(
4294 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4295 Captures, CaptureInits, CD, RD);
4297 CD->setBody(Res->getCapturedStmt());
4298 RD->completeDefinition();
4300 DiscardCleanupsInEvaluationContext();
4301 PopExpressionEvaluationContext();
4304 PopFunctionScopeInfo();