1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
41 using namespace clang;
44 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
53 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
57 // Same thing in for stmt first clause (when expr) and third clause.
58 return StmtResult(FE.getAs<Stmt>());
62 StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
67 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
68 bool HasLeadingEmptyMacro) {
69 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
72 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
74 DeclGroupRef DG = dg.get();
76 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
79 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
82 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
83 DeclGroupRef DG = dg.get();
85 // If we don't have a declaration, or we have an invalid declaration,
87 if (DG.isNull() || !DG.isSingleDecl())
90 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
104 var->setInit(nullptr);
106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
109 if (getLangOpts().ObjCAutoRefCount) {
110 QualType type = var->getType();
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
123 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124 /// For '==' and '!=', suggest fixits for '=' or '|='.
126 /// Adding a cast to void (or other expression wrappers) will prevent the
127 /// warning from firing.
128 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
130 bool IsNotEqual, CanAssign, IsRelational;
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
133 if (!Op->isComparisonOp())
136 IsRelational = Op->isRelationalOp();
137 Loc = Op->getOperatorLoc();
138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
141 switch (Op->getOperator()) {
145 case OO_ExclaimEqual:
146 IsRelational = false;
150 case OO_GreaterEqual:
156 Loc = Op->getOperatorLoc();
157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
160 // Not a typo-prone comparison.
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
169 S.Diag(Loc, diag::warn_unused_comparison)
170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
174 if (!IsRelational && CanAssign) {
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
186 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
190 const Expr *E = dyn_cast_or_null<Expr>(S);
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
209 const Expr *WarnExpr;
212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
234 unsigned DiagID = diag::warn_unused_expr;
235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
236 E = Temps->getSubExpr();
237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
240 if (DiagnoseUnusedComparison(*this, E))
244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
245 if (E->getType()->isVoidType())
248 // If the callee has attribute pure, const, or warn_unused_result, warn with
249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
252 if (const Decl *FD = CE->getCalleeDecl()) {
253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
261 if (FD->hasAttr<PureAttr>()) {
262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
265 if (FD->hasAttr<ConstAttr>()) {
266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
270 } else if (ShouldSuppress)
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
278 const ObjCMethodDecl *MD = ME->getMethodDecl();
280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
290 DiagID = diag::warn_unused_property_expr;
291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
293 const Expr *E = FC->getSubExpr();
294 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
295 E = TE->getSubExpr();
296 if (isa<CXXTemporaryObjectExpr>(E))
298 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
299 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
300 if (!RD->getAttr<WarnUnusedAttr>())
303 // Diagnose "(void*) blah" as a typo for "(void) blah".
304 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
305 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
306 QualType T = TI->getType();
308 // We really do want to use the non-canonical type here.
309 if (T == Context.VoidPtrTy) {
310 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
312 Diag(Loc, diag::warn_unused_voidptr)
313 << FixItHint::CreateRemoval(TL.getStarLoc());
318 if (E->isGLValue() && E->getType().isVolatileQualified()) {
319 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
323 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
326 void Sema::ActOnStartOfCompoundStmt() {
330 void Sema::ActOnFinishOfCompoundStmt() {
334 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
335 return getCurFunction()->CompoundScopes.back();
338 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
339 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
340 const unsigned NumElts = Elts.size();
342 // If we're in C89 mode, check that we don't have any decls after stmts. If
343 // so, emit an extension diagnostic.
344 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
345 // Note that __extension__ can be around a decl.
347 // Skip over all declarations.
348 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
351 // We found the end of the list or a statement. Scan for another declstmt.
352 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
356 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
357 Diag(D->getLocation(), diag::ext_mixed_decls_code);
360 // Warn about unused expressions in statements.
361 for (unsigned i = 0; i != NumElts; ++i) {
362 // Ignore statements that are last in a statement expression.
363 if (isStmtExpr && i == NumElts - 1)
366 DiagnoseUnusedExprResult(Elts[i]);
369 // Check for suspicious empty body (null statement) in `for' and `while'
370 // statements. Don't do anything for template instantiations, this just adds
372 if (NumElts != 0 && !CurrentInstantiationScope &&
373 getCurCompoundScope().HasEmptyLoopBodies) {
374 for (unsigned i = 0; i != NumElts - 1; ++i)
375 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
378 return new (Context) CompoundStmt(Context, Elts, L, R);
382 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
383 SourceLocation DotDotDotLoc, Expr *RHSVal,
384 SourceLocation ColonLoc) {
385 assert(LHSVal && "missing expression in case statement");
387 if (getCurFunction()->SwitchStack.empty()) {
388 Diag(CaseLoc, diag::err_case_not_in_switch);
393 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
394 if (!getLangOpts().CPlusPlus11)
395 return VerifyIntegerConstantExpression(E);
397 getCurFunction()->SwitchStack.back()->getCond()) {
398 QualType CondType = CondExpr->getType();
399 llvm::APSInt TempVal;
400 return CheckConvertedConstantExpression(E, CondType, TempVal,
409 if (!getLangOpts().CPlusPlus11) {
410 // C99 6.8.4.2p3: The expression shall be an integer constant.
411 // However, GCC allows any evaluatable integer expression.
412 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
413 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
418 // GCC extension: The expression shall be an integer constant.
420 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
421 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
422 // Recover from an error by just forgetting about it.
426 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
427 getLangOpts().CPlusPlus11);
431 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
432 getLangOpts().CPlusPlus11)
437 CaseStmt *CS = new (Context)
438 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
439 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
443 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
444 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
445 DiagnoseUnusedExprResult(SubStmt);
447 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
448 CS->setSubStmt(SubStmt);
452 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
453 Stmt *SubStmt, Scope *CurScope) {
454 DiagnoseUnusedExprResult(SubStmt);
456 if (getCurFunction()->SwitchStack.empty()) {
457 Diag(DefaultLoc, diag::err_default_not_in_switch);
461 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
462 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
467 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
468 SourceLocation ColonLoc, Stmt *SubStmt) {
469 // If the label was multiply defined, reject it now.
470 if (TheDecl->getStmt()) {
471 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
472 Diag(TheDecl->getLocation(), diag::note_previous_definition);
476 // Otherwise, things are good. Fill in the declaration and return it.
477 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
478 TheDecl->setStmt(LS);
479 if (!TheDecl->isGnuLocal()) {
480 TheDecl->setLocStart(IdentLoc);
481 if (!TheDecl->isMSAsmLabel()) {
482 // Don't update the location of MS ASM labels. These will result in
483 // a diagnostic, and changing the location here will mess that up.
484 TheDecl->setLocation(IdentLoc);
490 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
491 ArrayRef<const Attr*> Attrs,
493 // Fill in the declaration and return it.
494 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
499 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
500 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
503 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
504 void VisitBinaryOperator(BinaryOperator *E) {
505 if (E->getOpcode() == BO_Comma)
506 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
507 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
513 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
514 ConditionResult Cond,
515 Stmt *thenStmt, SourceLocation ElseLoc,
517 if (Cond.isInvalid())
518 Cond = ConditionResult(
520 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
521 Context.BoolTy, VK_RValue),
525 Expr *CondExpr = Cond.get().second;
526 if (!Diags.isIgnored(diag::warn_comma_operator,
527 CondExpr->getExprLoc()))
528 CommaVisitor(*this).Visit(CondExpr);
531 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
532 diag::warn_empty_if_body);
534 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
538 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
539 Stmt *InitStmt, ConditionResult Cond,
540 Stmt *thenStmt, SourceLocation ElseLoc,
542 if (Cond.isInvalid())
545 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
546 getCurFunction()->setHasBranchProtectedScope();
548 DiagnoseUnusedExprResult(thenStmt);
549 DiagnoseUnusedExprResult(elseStmt);
552 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
553 Cond.get().second, thenStmt, ElseLoc, elseStmt);
557 struct CaseCompareFunctor {
558 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
559 const llvm::APSInt &RHS) {
560 return LHS.first < RHS;
562 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
563 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
564 return LHS.first < RHS.first;
566 bool operator()(const llvm::APSInt &LHS,
567 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
568 return LHS < RHS.first;
573 /// CmpCaseVals - Comparison predicate for sorting case values.
575 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
576 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
577 if (lhs.first < rhs.first)
580 if (lhs.first == rhs.first &&
581 lhs.second->getCaseLoc().getRawEncoding()
582 < rhs.second->getCaseLoc().getRawEncoding())
587 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
589 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
590 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
592 return lhs.first < rhs.first;
595 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
597 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
598 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
600 return lhs.first == rhs.first;
603 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
604 /// potentially integral-promoted expression @p expr.
605 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
606 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
607 expr = cleanups->getSubExpr();
608 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
609 if (impcast->getCastKind() != CK_IntegralCast) break;
610 expr = impcast->getSubExpr();
612 return expr->getType();
615 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
616 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
620 SwitchConvertDiagnoser(Expr *Cond)
621 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
624 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
625 QualType T) override {
626 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
629 SemaDiagnosticBuilder diagnoseIncomplete(
630 Sema &S, SourceLocation Loc, QualType T) override {
631 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
632 << T << Cond->getSourceRange();
635 SemaDiagnosticBuilder diagnoseExplicitConv(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
637 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
640 SemaDiagnosticBuilder noteExplicitConv(
641 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
642 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
643 << ConvTy->isEnumeralType() << ConvTy;
646 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
647 QualType T) override {
648 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
651 SemaDiagnosticBuilder noteAmbiguous(
652 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
653 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
654 << ConvTy->isEnumeralType() << ConvTy;
657 SemaDiagnosticBuilder diagnoseConversion(
658 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
659 llvm_unreachable("conversion functions are permitted");
661 } SwitchDiagnoser(Cond);
663 ExprResult CondResult =
664 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
665 if (CondResult.isInvalid())
668 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
669 return UsualUnaryConversions(CondResult.get());
672 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
673 Stmt *InitStmt, ConditionResult Cond) {
674 if (Cond.isInvalid())
677 getCurFunction()->setHasBranchIntoScope();
679 SwitchStmt *SS = new (Context)
680 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
681 getCurFunction()->SwitchStack.push_back(SS);
685 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
686 Val = Val.extOrTrunc(BitWidth);
687 Val.setIsSigned(IsSigned);
690 /// Check the specified case value is in range for the given unpromoted switch
692 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
693 unsigned UnpromotedWidth, bool UnpromotedSign) {
694 // If the case value was signed and negative and the switch expression is
695 // unsigned, don't bother to warn: this is implementation-defined behavior.
696 // FIXME: Introduce a second, default-ignored warning for this case?
697 if (UnpromotedWidth < Val.getBitWidth()) {
698 llvm::APSInt ConvVal(Val);
699 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
700 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
701 // FIXME: Use different diagnostics for overflow in conversion to promoted
702 // type versus "switch expression cannot have this value". Use proper
703 // IntRange checking rather than just looking at the unpromoted type here.
705 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
706 << ConvVal.toString(10);
710 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
712 /// Returns true if we should emit a diagnostic about this case expression not
713 /// being a part of the enum used in the switch controlling expression.
714 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
716 const Expr *CaseExpr,
717 EnumValsTy::iterator &EI,
718 EnumValsTy::iterator &EIEnd,
719 const llvm::APSInt &Val) {
723 if (const DeclRefExpr *DRE =
724 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
725 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
726 QualType VarType = VD->getType();
727 QualType EnumType = S.Context.getTypeDeclType(ED);
728 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
729 S.Context.hasSameUnqualifiedType(EnumType, VarType))
734 if (ED->hasAttr<FlagEnumAttr>())
735 return !S.IsValueInFlagEnum(ED, Val, false);
737 while (EI != EIEnd && EI->first < Val)
740 if (EI != EIEnd && EI->first == Val)
747 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
749 SwitchStmt *SS = cast<SwitchStmt>(Switch);
750 assert(SS == getCurFunction()->SwitchStack.back() &&
751 "switch stack missing push/pop!");
753 getCurFunction()->SwitchStack.pop_back();
755 if (!BodyStmt) return StmtError();
756 SS->setBody(BodyStmt, SwitchLoc);
758 Expr *CondExpr = SS->getCond();
759 if (!CondExpr) return StmtError();
761 QualType CondType = CondExpr->getType();
763 Expr *CondExprBeforePromotion = CondExpr;
764 QualType CondTypeBeforePromotion =
765 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
768 // Integral promotions are performed (on the switch condition).
770 // A case value unrepresentable by the original switch condition
771 // type (before the promotion) doesn't make sense, even when it can
772 // be represented by the promoted type. Therefore we need to find
773 // the pre-promotion type of the switch condition.
774 if (!CondExpr->isTypeDependent()) {
775 // We have already converted the expression to an integral or enumeration
776 // type, when we started the switch statement. If we don't have an
777 // appropriate type now, just return an error.
778 if (!CondType->isIntegralOrEnumerationType())
781 if (CondExpr->isKnownToHaveBooleanValue()) {
782 // switch(bool_expr) {...} is often a programmer error, e.g.
783 // switch(n && mask) { ... } // Doh - should be "n & mask".
784 // One can always use an if statement instead of switch(bool_expr).
785 Diag(SwitchLoc, diag::warn_bool_switch_condition)
786 << CondExpr->getSourceRange();
790 // Get the bitwidth of the switched-on value after promotions. We must
791 // convert the integer case values to this width before comparison.
792 bool HasDependentValue
793 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
794 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
795 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
797 // Get the width and signedness that the condition might actually have, for
799 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
801 unsigned CondWidthBeforePromotion
802 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
803 bool CondIsSignedBeforePromotion
804 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
806 // Accumulate all of the case values in a vector so that we can sort them
807 // and detect duplicates. This vector contains the APInt for the case after
808 // it has been converted to the condition type.
809 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
812 // Keep track of any GNU case ranges we see. The APSInt is the low value.
813 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
814 CaseRangesTy CaseRanges;
816 DefaultStmt *TheDefaultStmt = nullptr;
818 bool CaseListIsErroneous = false;
820 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
821 SC = SC->getNextSwitchCase()) {
823 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
824 if (TheDefaultStmt) {
825 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
826 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
828 // FIXME: Remove the default statement from the switch block so that
829 // we'll return a valid AST. This requires recursing down the AST and
830 // finding it, not something we are set up to do right now. For now,
831 // just lop the entire switch stmt out of the AST.
832 CaseListIsErroneous = true;
837 CaseStmt *CS = cast<CaseStmt>(SC);
839 Expr *Lo = CS->getLHS();
841 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
842 HasDependentValue = true;
848 if (getLangOpts().CPlusPlus11) {
849 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
850 // constant expression of the promoted type of the switch condition.
852 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
853 if (ConvLo.isInvalid()) {
854 CaseListIsErroneous = true;
859 // We already verified that the expression has a i-c-e value (C99
860 // 6.8.4.2p3) - get that value now.
861 LoVal = Lo->EvaluateKnownConstInt(Context);
863 // If the LHS is not the same type as the condition, insert an implicit
865 Lo = DefaultLvalueConversion(Lo).get();
866 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
869 // Check the unconverted value is within the range of possible values of
870 // the switch expression.
871 checkCaseValue(*this, Lo->getLocStart(), LoVal,
872 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
874 // Convert the value to the same width/sign as the condition.
875 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
879 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
881 if (CS->getRHS()->isTypeDependent() ||
882 CS->getRHS()->isValueDependent()) {
883 HasDependentValue = true;
886 CaseRanges.push_back(std::make_pair(LoVal, CS));
888 CaseVals.push_back(std::make_pair(LoVal, CS));
892 if (!HasDependentValue) {
893 // If we don't have a default statement, check whether the
894 // condition is constant.
895 llvm::APSInt ConstantCondValue;
896 bool HasConstantCond = false;
897 if (!HasDependentValue && !TheDefaultStmt) {
898 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
899 Expr::SE_AllowSideEffects);
900 assert(!HasConstantCond ||
901 (ConstantCondValue.getBitWidth() == CondWidth &&
902 ConstantCondValue.isSigned() == CondIsSigned));
904 bool ShouldCheckConstantCond = HasConstantCond;
906 // Sort all the scalar case values so we can easily detect duplicates.
907 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
909 if (!CaseVals.empty()) {
910 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
911 if (ShouldCheckConstantCond &&
912 CaseVals[i].first == ConstantCondValue)
913 ShouldCheckConstantCond = false;
915 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
916 // If we have a duplicate, report it.
917 // First, determine if either case value has a name
918 StringRef PrevString, CurrString;
919 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
920 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
921 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
922 PrevString = DeclRef->getDecl()->getName();
924 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
925 CurrString = DeclRef->getDecl()->getName();
927 SmallString<16> CaseValStr;
928 CaseVals[i-1].first.toString(CaseValStr);
930 if (PrevString == CurrString)
931 Diag(CaseVals[i].second->getLHS()->getLocStart(),
932 diag::err_duplicate_case) <<
933 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
935 Diag(CaseVals[i].second->getLHS()->getLocStart(),
936 diag::err_duplicate_case_differing_expr) <<
937 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
938 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
941 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
942 diag::note_duplicate_case_prev);
943 // FIXME: We really want to remove the bogus case stmt from the
944 // substmt, but we have no way to do this right now.
945 CaseListIsErroneous = true;
950 // Detect duplicate case ranges, which usually don't exist at all in
952 if (!CaseRanges.empty()) {
953 // Sort all the case ranges by their low value so we can easily detect
954 // overlaps between ranges.
955 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
957 // Scan the ranges, computing the high values and removing empty ranges.
958 std::vector<llvm::APSInt> HiVals;
959 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
960 llvm::APSInt &LoVal = CaseRanges[i].first;
961 CaseStmt *CR = CaseRanges[i].second;
962 Expr *Hi = CR->getRHS();
965 if (getLangOpts().CPlusPlus11) {
966 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
967 // constant expression of the promoted type of the switch condition.
969 CheckConvertedConstantExpression(Hi, CondType, HiVal,
971 if (ConvHi.isInvalid()) {
972 CaseListIsErroneous = true;
977 HiVal = Hi->EvaluateKnownConstInt(Context);
979 // If the RHS is not the same type as the condition, insert an
981 Hi = DefaultLvalueConversion(Hi).get();
982 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
985 // Check the unconverted value is within the range of possible values of
986 // the switch expression.
987 checkCaseValue(*this, Hi->getLocStart(), HiVal,
988 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
990 // Convert the value to the same width/sign as the condition.
991 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
995 // If the low value is bigger than the high value, the case is empty.
997 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
998 << SourceRange(CR->getLHS()->getLocStart(),
1000 CaseRanges.erase(CaseRanges.begin()+i);
1006 if (ShouldCheckConstantCond &&
1007 LoVal <= ConstantCondValue &&
1008 ConstantCondValue <= HiVal)
1009 ShouldCheckConstantCond = false;
1011 HiVals.push_back(HiVal);
1014 // Rescan the ranges, looking for overlap with singleton values and other
1015 // ranges. Since the range list is sorted, we only need to compare case
1016 // ranges with their neighbors.
1017 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1018 llvm::APSInt &CRLo = CaseRanges[i].first;
1019 llvm::APSInt &CRHi = HiVals[i];
1020 CaseStmt *CR = CaseRanges[i].second;
1022 // Check to see whether the case range overlaps with any
1024 CaseStmt *OverlapStmt = nullptr;
1025 llvm::APSInt OverlapVal(32);
1027 // Find the smallest value >= the lower bound. If I is in the
1028 // case range, then we have overlap.
1029 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1030 CaseVals.end(), CRLo,
1031 CaseCompareFunctor());
1032 if (I != CaseVals.end() && I->first < CRHi) {
1033 OverlapVal = I->first; // Found overlap with scalar.
1034 OverlapStmt = I->second;
1037 // Find the smallest value bigger than the upper bound.
1038 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1039 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1040 OverlapVal = (I-1)->first; // Found overlap with scalar.
1041 OverlapStmt = (I-1)->second;
1044 // Check to see if this case stmt overlaps with the subsequent
1046 if (i && CRLo <= HiVals[i-1]) {
1047 OverlapVal = HiVals[i-1]; // Found overlap with range.
1048 OverlapStmt = CaseRanges[i-1].second;
1052 // If we have a duplicate, report it.
1053 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1054 << OverlapVal.toString(10);
1055 Diag(OverlapStmt->getLHS()->getLocStart(),
1056 diag::note_duplicate_case_prev);
1057 // FIXME: We really want to remove the bogus case stmt from the
1058 // substmt, but we have no way to do this right now.
1059 CaseListIsErroneous = true;
1064 // Complain if we have a constant condition and we didn't find a match.
1065 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1066 // TODO: it would be nice if we printed enums as enums, chars as
1068 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1069 << ConstantCondValue.toString(10)
1070 << CondExpr->getSourceRange();
1073 // Check to see if switch is over an Enum and handles all of its
1074 // values. We only issue a warning if there is not 'default:', but
1075 // we still do the analysis to preserve this information in the AST
1076 // (which can be used by flow-based analyes).
1078 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1080 // If switch has default case, then ignore it.
1081 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1082 ET->getDecl()->isCompleteDefinition()) {
1083 const EnumDecl *ED = ET->getDecl();
1084 EnumValsTy EnumVals;
1086 // Gather all enum values, set their type and sort them,
1087 // allowing easier comparison with CaseVals.
1088 for (auto *EDI : ED->enumerators()) {
1089 llvm::APSInt Val = EDI->getInitVal();
1090 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1091 EnumVals.push_back(std::make_pair(Val, EDI));
1093 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1094 auto EI = EnumVals.begin(), EIEnd =
1095 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1097 // See which case values aren't in enum.
1098 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1099 CI != CaseVals.end(); CI++) {
1100 Expr *CaseExpr = CI->second->getLHS();
1101 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1103 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1104 << CondTypeBeforePromotion;
1107 // See which of case ranges aren't in enum
1108 EI = EnumVals.begin();
1109 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1110 RI != CaseRanges.end(); RI++) {
1111 Expr *CaseExpr = RI->second->getLHS();
1112 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1114 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1115 << CondTypeBeforePromotion;
1118 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1119 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1121 CaseExpr = RI->second->getRHS();
1122 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1124 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1125 << CondTypeBeforePromotion;
1128 // Check which enum vals aren't in switch
1129 auto CI = CaseVals.begin();
1130 auto RI = CaseRanges.begin();
1131 bool hasCasesNotInSwitch = false;
1133 SmallVector<DeclarationName,8> UnhandledNames;
1135 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1136 // Drop unneeded case values
1137 while (CI != CaseVals.end() && CI->first < EI->first)
1140 if (CI != CaseVals.end() && CI->first == EI->first)
1143 // Drop unneeded case ranges
1144 for (; RI != CaseRanges.end(); RI++) {
1146 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1147 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1148 if (EI->first <= Hi)
1152 if (RI == CaseRanges.end() || EI->first < RI->first) {
1153 hasCasesNotInSwitch = true;
1154 UnhandledNames.push_back(EI->second->getDeclName());
1158 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1159 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1161 // Produce a nice diagnostic if multiple values aren't handled.
1162 if (!UnhandledNames.empty()) {
1163 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1164 TheDefaultStmt ? diag::warn_def_missing_case
1165 : diag::warn_missing_case)
1166 << (int)UnhandledNames.size();
1168 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1170 DB << UnhandledNames[I];
1173 if (!hasCasesNotInSwitch)
1174 SS->setAllEnumCasesCovered();
1179 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1180 diag::warn_empty_switch_body);
1182 // FIXME: If the case list was broken is some way, we don't have a good system
1183 // to patch it up. Instead, just return the whole substmt as broken.
1184 if (CaseListIsErroneous)
1191 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1193 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1196 if (const EnumType *ET = DstType->getAs<EnumType>())
1197 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1198 SrcType->isIntegerType()) {
1199 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1200 SrcExpr->isIntegerConstantExpr(Context)) {
1201 // Get the bitwidth of the enum value before promotions.
1202 unsigned DstWidth = Context.getIntWidth(DstType);
1203 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1205 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1206 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1207 const EnumDecl *ED = ET->getDecl();
1209 if (!ED->isClosed())
1212 if (ED->hasAttr<FlagEnumAttr>()) {
1213 if (!IsValueInFlagEnum(ED, RhsVal, true))
1214 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1215 << DstType.getUnqualifiedType();
1217 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1219 EnumValsTy EnumVals;
1221 // Gather all enum values, set their type and sort them,
1222 // allowing easier comparison with rhs constant.
1223 for (auto *EDI : ED->enumerators()) {
1224 llvm::APSInt Val = EDI->getInitVal();
1225 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1226 EnumVals.push_back(std::make_pair(Val, EDI));
1228 if (EnumVals.empty())
1230 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1231 EnumValsTy::iterator EIend =
1232 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1234 // See which values aren't in the enum.
1235 EnumValsTy::const_iterator EI = EnumVals.begin();
1236 while (EI != EIend && EI->first < RhsVal)
1238 if (EI == EIend || EI->first != RhsVal) {
1239 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1240 << DstType.getUnqualifiedType();
1247 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1249 if (Cond.isInvalid())
1252 auto CondVal = Cond.get();
1253 CheckBreakContinueBinding(CondVal.second);
1255 if (CondVal.second &&
1256 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1257 CommaVisitor(*this).Visit(CondVal.second);
1259 DiagnoseUnusedExprResult(Body);
1261 if (isa<NullStmt>(Body))
1262 getCurCompoundScope().setHasEmptyLoopBodies();
1264 return new (Context)
1265 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
1269 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1270 SourceLocation WhileLoc, SourceLocation CondLParen,
1271 Expr *Cond, SourceLocation CondRParen) {
1272 assert(Cond && "ActOnDoStmt(): missing expression");
1274 CheckBreakContinueBinding(Cond);
1275 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1276 if (CondResult.isInvalid())
1278 Cond = CondResult.get();
1280 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1281 if (CondResult.isInvalid())
1283 Cond = CondResult.get();
1285 DiagnoseUnusedExprResult(Body);
1287 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1291 // This visitor will traverse a conditional statement and store all
1292 // the evaluated decls into a vector. Simple is set to true if none
1293 // of the excluded constructs are used.
1294 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1295 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1296 SmallVectorImpl<SourceRange> &Ranges;
1299 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1301 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1302 SmallVectorImpl<SourceRange> &Ranges) :
1303 Inherited(S.Context),
1308 bool isSimple() { return Simple; }
1310 // Replaces the method in EvaluatedExprVisitor.
1311 void VisitMemberExpr(MemberExpr* E) {
1315 // Any Stmt not whitelisted will cause the condition to be marked complex.
1316 void VisitStmt(Stmt *S) {
1320 void VisitBinaryOperator(BinaryOperator *E) {
1325 void VisitCastExpr(CastExpr *E) {
1326 Visit(E->getSubExpr());
1329 void VisitUnaryOperator(UnaryOperator *E) {
1330 // Skip checking conditionals with derefernces.
1331 if (E->getOpcode() == UO_Deref)
1334 Visit(E->getSubExpr());
1337 void VisitConditionalOperator(ConditionalOperator *E) {
1338 Visit(E->getCond());
1339 Visit(E->getTrueExpr());
1340 Visit(E->getFalseExpr());
1343 void VisitParenExpr(ParenExpr *E) {
1344 Visit(E->getSubExpr());
1347 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1348 Visit(E->getOpaqueValue()->getSourceExpr());
1349 Visit(E->getFalseExpr());
1352 void VisitIntegerLiteral(IntegerLiteral *E) { }
1353 void VisitFloatingLiteral(FloatingLiteral *E) { }
1354 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1355 void VisitCharacterLiteral(CharacterLiteral *E) { }
1356 void VisitGNUNullExpr(GNUNullExpr *E) { }
1357 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1359 void VisitDeclRefExpr(DeclRefExpr *E) {
1360 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1363 Ranges.push_back(E->getSourceRange());
1368 }; // end class DeclExtractor
1370 // DeclMatcher checks to see if the decls are used in a non-evaluated
1372 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1373 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1377 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1379 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1381 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1382 if (!Statement) return;
1387 void VisitReturnStmt(ReturnStmt *S) {
1391 void VisitBreakStmt(BreakStmt *S) {
1395 void VisitGotoStmt(GotoStmt *S) {
1399 void VisitCastExpr(CastExpr *E) {
1400 if (E->getCastKind() == CK_LValueToRValue)
1401 CheckLValueToRValueCast(E->getSubExpr());
1403 Visit(E->getSubExpr());
1406 void CheckLValueToRValueCast(Expr *E) {
1407 E = E->IgnoreParenImpCasts();
1409 if (isa<DeclRefExpr>(E)) {
1413 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1414 Visit(CO->getCond());
1415 CheckLValueToRValueCast(CO->getTrueExpr());
1416 CheckLValueToRValueCast(CO->getFalseExpr());
1420 if (BinaryConditionalOperator *BCO =
1421 dyn_cast<BinaryConditionalOperator>(E)) {
1422 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1423 CheckLValueToRValueCast(BCO->getFalseExpr());
1430 void VisitDeclRefExpr(DeclRefExpr *E) {
1431 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1432 if (Decls.count(VD))
1436 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1437 // Only need to visit the semantics for POE.
1438 // SyntaticForm doesn't really use the Decal.
1439 for (auto *S : POE->semantics()) {
1440 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1441 // Look past the OVE into the expression it binds.
1442 Visit(OVE->getSourceExpr());
1448 bool FoundDeclInUse() { return FoundDecl; }
1450 }; // end class DeclMatcher
1452 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1453 Expr *Third, Stmt *Body) {
1454 // Condition is empty
1455 if (!Second) return;
1457 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1458 Second->getLocStart()))
1461 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1462 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1463 SmallVector<SourceRange, 10> Ranges;
1464 DeclExtractor DE(S, Decls, Ranges);
1467 // Don't analyze complex conditionals.
1468 if (!DE.isSimple()) return;
1471 if (Decls.size() == 0) return;
1473 // Don't warn on volatile, static, or global variables.
1474 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1477 if ((*I)->getType().isVolatileQualified() ||
1478 (*I)->hasGlobalStorage()) return;
1480 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1481 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1482 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1485 // Load decl names into diagnostic.
1486 if (Decls.size() > 4)
1489 PDiag << Decls.size();
1490 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1493 PDiag << (*I)->getDeclName();
1496 // Load SourceRanges into diagnostic if there is room.
1497 // Otherwise, load the SourceRange of the conditional expression.
1498 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1499 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1504 PDiag << Second->getSourceRange();
1506 S.Diag(Ranges.begin()->getBegin(), PDiag);
1509 // If Statement is an incemement or decrement, return true and sets the
1510 // variables Increment and DRE.
1511 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1512 DeclRefExpr *&DRE) {
1513 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1514 if (!Cleanups->cleanupsHaveSideEffects())
1515 Statement = Cleanups->getSubExpr();
1517 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1518 switch (UO->getOpcode()) {
1519 default: return false;
1529 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1533 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1534 FunctionDecl *FD = Call->getDirectCallee();
1535 if (!FD || !FD->isOverloadedOperator()) return false;
1536 switch (FD->getOverloadedOperator()) {
1537 default: return false;
1545 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1552 // A visitor to determine if a continue or break statement is a
1554 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1555 SourceLocation BreakLoc;
1556 SourceLocation ContinueLoc;
1558 BreakContinueFinder(Sema &S, Stmt* Body) :
1559 Inherited(S.Context) {
1563 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1565 void VisitContinueStmt(ContinueStmt* E) {
1566 ContinueLoc = E->getContinueLoc();
1569 void VisitBreakStmt(BreakStmt* E) {
1570 BreakLoc = E->getBreakLoc();
1573 bool ContinueFound() { return ContinueLoc.isValid(); }
1574 bool BreakFound() { return BreakLoc.isValid(); }
1575 SourceLocation GetContinueLoc() { return ContinueLoc; }
1576 SourceLocation GetBreakLoc() { return BreakLoc; }
1578 }; // end class BreakContinueFinder
1580 // Emit a warning when a loop increment/decrement appears twice per loop
1581 // iteration. The conditions which trigger this warning are:
1582 // 1) The last statement in the loop body and the third expression in the
1583 // for loop are both increment or both decrement of the same variable
1584 // 2) No continue statements in the loop body.
1585 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1586 // Return when there is nothing to check.
1587 if (!Body || !Third) return;
1589 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1590 Third->getLocStart()))
1593 // Get the last statement from the loop body.
1594 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1595 if (!CS || CS->body_empty()) return;
1596 Stmt *LastStmt = CS->body_back();
1597 if (!LastStmt) return;
1599 bool LoopIncrement, LastIncrement;
1600 DeclRefExpr *LoopDRE, *LastDRE;
1602 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1603 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1605 // Check that the two statements are both increments or both decrements
1606 // on the same variable.
1607 if (LoopIncrement != LastIncrement ||
1608 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1610 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1612 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1613 << LastDRE->getDecl() << LastIncrement;
1614 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1621 void Sema::CheckBreakContinueBinding(Expr *E) {
1622 if (!E || getLangOpts().CPlusPlus)
1624 BreakContinueFinder BCFinder(*this, E);
1625 Scope *BreakParent = CurScope->getBreakParent();
1626 if (BCFinder.BreakFound() && BreakParent) {
1627 if (BreakParent->getFlags() & Scope::SwitchScope) {
1628 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1630 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1633 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1634 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1639 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1640 Stmt *First, ConditionResult Second,
1641 FullExprArg third, SourceLocation RParenLoc,
1643 if (Second.isInvalid())
1646 if (!getLangOpts().CPlusPlus) {
1647 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1648 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1649 // declare identifiers for objects having storage class 'auto' or
1651 for (auto *DI : DS->decls()) {
1652 VarDecl *VD = dyn_cast<VarDecl>(DI);
1653 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1656 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1657 DI->setInvalidDecl();
1663 CheckBreakContinueBinding(Second.get().second);
1664 CheckBreakContinueBinding(third.get());
1666 if (!Second.get().first)
1667 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1669 CheckForRedundantIteration(*this, third.get(), Body);
1671 if (Second.get().second &&
1672 !Diags.isIgnored(diag::warn_comma_operator,
1673 Second.get().second->getExprLoc()))
1674 CommaVisitor(*this).Visit(Second.get().second);
1676 Expr *Third = third.release().getAs<Expr>();
1678 DiagnoseUnusedExprResult(First);
1679 DiagnoseUnusedExprResult(Third);
1680 DiagnoseUnusedExprResult(Body);
1682 if (isa<NullStmt>(Body))
1683 getCurCompoundScope().setHasEmptyLoopBodies();
1685 return new (Context)
1686 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1687 Body, ForLoc, LParenLoc, RParenLoc);
1690 /// In an Objective C collection iteration statement:
1692 /// x can be an arbitrary l-value expression. Bind it up as a
1693 /// full-expression.
1694 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1695 // Reduce placeholder expressions here. Note that this rejects the
1696 // use of pseudo-object l-values in this position.
1697 ExprResult result = CheckPlaceholderExpr(E);
1698 if (result.isInvalid()) return StmtError();
1701 ExprResult FullExpr = ActOnFinishFullExpr(E);
1702 if (FullExpr.isInvalid())
1704 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1708 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1712 ExprResult result = CorrectDelayedTyposInExpr(collection);
1713 if (!result.isUsable())
1715 collection = result.get();
1717 // Bail out early if we've got a type-dependent expression.
1718 if (collection->isTypeDependent()) return collection;
1720 // Perform normal l-value conversion.
1721 result = DefaultFunctionArrayLvalueConversion(collection);
1722 if (result.isInvalid())
1724 collection = result.get();
1726 // The operand needs to have object-pointer type.
1727 // TODO: should we do a contextual conversion?
1728 const ObjCObjectPointerType *pointerType =
1729 collection->getType()->getAs<ObjCObjectPointerType>();
1731 return Diag(forLoc, diag::err_collection_expr_type)
1732 << collection->getType() << collection->getSourceRange();
1734 // Check that the operand provides
1735 // - countByEnumeratingWithState:objects:count:
1736 const ObjCObjectType *objectType = pointerType->getObjectType();
1737 ObjCInterfaceDecl *iface = objectType->getInterface();
1739 // If we have a forward-declared type, we can't do this check.
1740 // Under ARC, it is an error not to have a forward-declared class.
1742 (getLangOpts().ObjCAutoRefCount
1743 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1744 diag::err_arc_collection_forward, collection)
1745 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1746 // Otherwise, if we have any useful type information, check that
1747 // the type declares the appropriate method.
1748 } else if (iface || !objectType->qual_empty()) {
1749 IdentifierInfo *selectorIdents[] = {
1750 &Context.Idents.get("countByEnumeratingWithState"),
1751 &Context.Idents.get("objects"),
1752 &Context.Idents.get("count")
1754 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1756 ObjCMethodDecl *method = nullptr;
1758 // If there's an interface, look in both the public and private APIs.
1760 method = iface->lookupInstanceMethod(selector);
1761 if (!method) method = iface->lookupPrivateMethod(selector);
1764 // Also check protocol qualifiers.
1766 method = LookupMethodInQualifiedType(selector, pointerType,
1769 // If we didn't find it anywhere, give up.
1771 Diag(forLoc, diag::warn_collection_expr_type)
1772 << collection->getType() << selector << collection->getSourceRange();
1775 // TODO: check for an incompatible signature?
1778 // Wrap up any cleanups in the expression.
1783 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1784 Stmt *First, Expr *collection,
1785 SourceLocation RParenLoc) {
1786 getCurFunction()->setHasBranchProtectedScope();
1788 ExprResult CollectionExprResult =
1789 CheckObjCForCollectionOperand(ForLoc, collection);
1793 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1794 if (!DS->isSingleDecl())
1795 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1796 diag::err_toomany_element_decls));
1798 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1799 if (!D || D->isInvalidDecl())
1802 FirstType = D->getType();
1803 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1804 // declare identifiers for objects having storage class 'auto' or
1806 if (!D->hasLocalStorage())
1807 return StmtError(Diag(D->getLocation(),
1808 diag::err_non_local_variable_decl_in_for));
1810 // If the type contained 'auto', deduce the 'auto' to 'id'.
1811 if (FirstType->getContainedAutoType()) {
1812 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1814 Expr *DeducedInit = &OpaqueId;
1815 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1817 DiagnoseAutoDeductionFailure(D, DeducedInit);
1818 if (FirstType.isNull()) {
1819 D->setInvalidDecl();
1823 D->setType(FirstType);
1825 if (!inTemplateInstantiation()) {
1826 SourceLocation Loc =
1827 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1828 Diag(Loc, diag::warn_auto_var_is_id)
1829 << D->getDeclName();
1834 Expr *FirstE = cast<Expr>(First);
1835 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1836 return StmtError(Diag(First->getLocStart(),
1837 diag::err_selector_element_not_lvalue)
1838 << First->getSourceRange());
1840 FirstType = static_cast<Expr*>(First)->getType();
1841 if (FirstType.isConstQualified())
1842 Diag(ForLoc, diag::err_selector_element_const_type)
1843 << FirstType << First->getSourceRange();
1845 if (!FirstType->isDependentType() &&
1846 !FirstType->isObjCObjectPointerType() &&
1847 !FirstType->isBlockPointerType())
1848 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1849 << FirstType << First->getSourceRange());
1852 if (CollectionExprResult.isInvalid())
1855 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1856 if (CollectionExprResult.isInvalid())
1859 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1860 nullptr, ForLoc, RParenLoc);
1863 /// Finish building a variable declaration for a for-range statement.
1864 /// \return true if an error occurs.
1865 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1866 SourceLocation Loc, int DiagID) {
1867 if (Decl->getType()->isUndeducedType()) {
1868 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1869 if (!Res.isUsable()) {
1870 Decl->setInvalidDecl();
1876 // Deduce the type for the iterator variable now rather than leaving it to
1877 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1879 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1880 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1882 SemaRef.Diag(Loc, DiagID) << Init->getType();
1883 if (InitType.isNull()) {
1884 Decl->setInvalidDecl();
1887 Decl->setType(InitType);
1889 // In ARC, infer lifetime.
1890 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1891 // we're doing the equivalent of fast iteration.
1892 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1893 SemaRef.inferObjCARCLifetime(Decl))
1894 Decl->setInvalidDecl();
1896 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1897 SemaRef.FinalizeDeclaration(Decl);
1898 SemaRef.CurContext->addHiddenDecl(Decl);
1903 // An enum to represent whether something is dealing with a call to begin()
1904 // or a call to end() in a range-based for loop.
1905 enum BeginEndFunction {
1910 /// Produce a note indicating which begin/end function was implicitly called
1911 /// by a C++11 for-range statement. This is often not obvious from the code,
1912 /// nor from the diagnostics produced when analysing the implicit expressions
1913 /// required in a for-range statement.
1914 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1915 BeginEndFunction BEF) {
1916 CallExpr *CE = dyn_cast<CallExpr>(E);
1919 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1922 SourceLocation Loc = D->getLocation();
1924 std::string Description;
1925 bool IsTemplate = false;
1926 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1927 Description = SemaRef.getTemplateArgumentBindingsText(
1928 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1932 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1933 << BEF << IsTemplate << Description << E->getType();
1936 /// Build a variable declaration for a for-range statement.
1937 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1938 QualType Type, const char *Name) {
1939 DeclContext *DC = SemaRef.CurContext;
1940 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1941 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1942 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1944 Decl->setImplicit();
1950 static bool ObjCEnumerationCollection(Expr *Collection) {
1951 return !Collection->isTypeDependent()
1952 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1955 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1957 /// C++11 [stmt.ranged]:
1958 /// A range-based for statement is equivalent to
1961 /// auto && __range = range-init;
1962 /// for ( auto __begin = begin-expr,
1963 /// __end = end-expr;
1964 /// __begin != __end;
1966 /// for-range-declaration = *__begin;
1971 /// The body of the loop is not available yet, since it cannot be analysed until
1972 /// we have determined the type of the for-range-declaration.
1973 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1974 SourceLocation CoawaitLoc, Stmt *First,
1975 SourceLocation ColonLoc, Expr *Range,
1976 SourceLocation RParenLoc,
1977 BuildForRangeKind Kind) {
1981 if (Range && ObjCEnumerationCollection(Range))
1982 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1984 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1985 assert(DS && "first part of for range not a decl stmt");
1987 if (!DS->isSingleDecl()) {
1988 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1992 Decl *LoopVar = DS->getSingleDecl();
1993 if (LoopVar->isInvalidDecl() || !Range ||
1994 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1995 LoopVar->setInvalidDecl();
1999 // Coroutines: 'for co_await' implicitly co_awaits its range.
2000 if (CoawaitLoc.isValid()) {
2001 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
2002 if (Coawait.isInvalid()) return StmtError();
2003 Range = Coawait.get();
2006 // Build auto && __range = range-init
2007 SourceLocation RangeLoc = Range->getLocStart();
2008 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2009 Context.getAutoRRefDeductType(),
2011 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2012 diag::err_for_range_deduction_failure)) {
2013 LoopVar->setInvalidDecl();
2017 // Claim the type doesn't contain auto: we've already done the checking.
2018 DeclGroupPtrTy RangeGroup =
2019 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2020 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2021 if (RangeDecl.isInvalid()) {
2022 LoopVar->setInvalidDecl();
2026 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
2027 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2028 /*Cond=*/nullptr, /*Inc=*/nullptr,
2029 DS, RParenLoc, Kind);
2032 /// \brief Create the initialization, compare, and increment steps for
2033 /// the range-based for loop expression.
2034 /// This function does not handle array-based for loops,
2035 /// which are created in Sema::BuildCXXForRangeStmt.
2037 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2038 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2039 /// CandidateSet and BEF are set and some non-success value is returned on
2041 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
2042 Expr *BeginRange, Expr *EndRange,
2046 SourceLocation ColonLoc,
2047 OverloadCandidateSet *CandidateSet,
2048 ExprResult *BeginExpr,
2049 ExprResult *EndExpr,
2050 BeginEndFunction *BEF) {
2051 DeclarationNameInfo BeginNameInfo(
2052 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2053 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2056 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2057 Sema::LookupMemberName);
2058 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2060 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2061 // - if _RangeT is a class type, the unqualified-ids begin and end are
2062 // looked up in the scope of class _RangeT as if by class member access
2063 // lookup (3.4.5), and if either (or both) finds at least one
2064 // declaration, begin-expr and end-expr are __range.begin() and
2065 // __range.end(), respectively;
2066 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2067 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2069 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2070 SourceLocation RangeLoc = BeginVar->getLocation();
2071 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
2073 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2074 << RangeLoc << BeginRange->getType() << *BEF;
2075 return Sema::FRS_DiagnosticIssued;
2078 // - otherwise, begin-expr and end-expr are begin(__range) and
2079 // end(__range), respectively, where begin and end are looked up with
2080 // argument-dependent lookup (3.4.2). For the purposes of this name
2081 // lookup, namespace std is an associated namespace.
2086 Sema::ForRangeStatus RangeStatus =
2087 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2088 BeginMemberLookup, CandidateSet,
2089 BeginRange, BeginExpr);
2091 if (RangeStatus != Sema::FRS_Success) {
2092 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2093 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2094 << ColonLoc << BEF_begin << BeginRange->getType();
2097 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2098 diag::err_for_range_iter_deduction_failure)) {
2099 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2100 return Sema::FRS_DiagnosticIssued;
2105 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2106 EndMemberLookup, CandidateSet,
2108 if (RangeStatus != Sema::FRS_Success) {
2109 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2110 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2111 << ColonLoc << BEF_end << EndRange->getType();
2114 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2115 diag::err_for_range_iter_deduction_failure)) {
2116 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2117 return Sema::FRS_DiagnosticIssued;
2119 return Sema::FRS_Success;
2122 /// Speculatively attempt to dereference an invalid range expression.
2123 /// If the attempt fails, this function will return a valid, null StmtResult
2124 /// and emit no diagnostics.
2125 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2126 SourceLocation ForLoc,
2127 SourceLocation CoawaitLoc,
2129 SourceLocation ColonLoc,
2131 SourceLocation RangeLoc,
2132 SourceLocation RParenLoc) {
2133 // Determine whether we can rebuild the for-range statement with a
2134 // dereferenced range expression.
2135 ExprResult AdjustedRange;
2137 Sema::SFINAETrap Trap(SemaRef);
2139 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2140 if (AdjustedRange.isInvalid())
2141 return StmtResult();
2143 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2144 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2145 RParenLoc, Sema::BFRK_Check);
2147 return StmtResult();
2150 // The attempt to dereference worked well enough that it could produce a valid
2151 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2152 // case there are any other (non-fatal) problems with it.
2153 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2154 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2155 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2156 ColonLoc, AdjustedRange.get(), RParenLoc,
2157 Sema::BFRK_Rebuild);
2161 /// RAII object to automatically invalidate a declaration if an error occurs.
2162 struct InvalidateOnErrorScope {
2163 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2164 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2165 ~InvalidateOnErrorScope() {
2166 if (Enabled && Trap.hasErrorOccurred())
2167 D->setInvalidDecl();
2170 DiagnosticErrorTrap Trap;
2176 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2178 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2179 SourceLocation ColonLoc, Stmt *RangeDecl,
2180 Stmt *Begin, Stmt *End, Expr *Cond,
2181 Expr *Inc, Stmt *LoopVarDecl,
2182 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2183 // FIXME: This should not be used during template instantiation. We should
2184 // pick up the set of unqualified lookup results for the != and + operators
2185 // in the initial parse.
2187 // Testcase (accepts-invalid):
2188 // template<typename T> void f() { for (auto x : T()) {} }
2189 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2190 // bool operator!=(N::X, N::X); void operator++(N::X);
2191 // void g() { f<N::X>(); }
2192 Scope *S = getCurScope();
2194 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2195 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2196 QualType RangeVarType = RangeVar->getType();
2198 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2199 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2201 // If we hit any errors, mark the loop variable as invalid if its type
2203 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2204 LoopVar->getType()->isUndeducedType());
2206 StmtResult BeginDeclStmt = Begin;
2207 StmtResult EndDeclStmt = End;
2208 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2210 if (RangeVarType->isDependentType()) {
2211 // The range is implicitly used as a placeholder when it is dependent.
2212 RangeVar->markUsed(Context);
2214 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2215 // them in properly when we instantiate the loop.
2216 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2217 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2218 } else if (!BeginDeclStmt.get()) {
2219 SourceLocation RangeLoc = RangeVar->getLocation();
2221 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2223 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2224 VK_LValue, ColonLoc);
2225 if (BeginRangeRef.isInvalid())
2228 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2229 VK_LValue, ColonLoc);
2230 if (EndRangeRef.isInvalid())
2233 QualType AutoType = Context.getAutoDeductType();
2234 Expr *Range = RangeVar->getInit();
2237 QualType RangeType = Range->getType();
2239 if (RequireCompleteType(RangeLoc, RangeType,
2240 diag::err_for_range_incomplete_type))
2243 // Build auto __begin = begin-expr, __end = end-expr.
2244 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2246 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2249 // Build begin-expr and end-expr and attach to __begin and __end variables.
2250 ExprResult BeginExpr, EndExpr;
2251 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2252 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2253 // __range + __bound, respectively, where __bound is the array bound. If
2254 // _RangeT is an array of unknown size or an array of incomplete type,
2255 // the program is ill-formed;
2257 // begin-expr is __range.
2258 BeginExpr = BeginRangeRef;
2259 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2260 diag::err_for_range_iter_deduction_failure)) {
2261 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2265 // Find the array bound.
2266 ExprResult BoundExpr;
2267 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2268 BoundExpr = IntegerLiteral::Create(
2269 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2270 else if (const VariableArrayType *VAT =
2271 dyn_cast<VariableArrayType>(UnqAT)) {
2272 // For a variably modified type we can't just use the expression within
2273 // the array bounds, since we don't want that to be re-evaluated here.
2274 // Rather, we need to determine what it was when the array was first
2275 // created - so we resort to using sizeof(vla)/sizeof(element).
2279 // b = -1; <-- This should not affect the num of iterations below
2280 // for (int &c : vla) { .. }
2283 // FIXME: This results in codegen generating IR that recalculates the
2284 // run-time number of elements (as opposed to just using the IR Value
2285 // that corresponds to the run-time value of each bound that was
2286 // generated when the array was created.) If this proves too embarassing
2287 // even for unoptimized IR, consider passing a magic-value/cookie to
2288 // codegen that then knows to simply use that initial llvm::Value (that
2289 // corresponds to the bound at time of array creation) within
2290 // getelementptr. But be prepared to pay the price of increasing a
2291 // customized form of coupling between the two components - which could
2292 // be hard to maintain as the codebase evolves.
2294 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2295 EndVar->getLocation(), UETT_SizeOf,
2297 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2298 VAT->desugar(), RangeLoc))
2300 EndVar->getSourceRange());
2301 if (SizeOfVLAExprR.isInvalid())
2304 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2305 EndVar->getLocation(), UETT_SizeOf,
2307 CreateParsedType(VAT->desugar(),
2308 Context.getTrivialTypeSourceInfo(
2309 VAT->getElementType(), RangeLoc))
2311 EndVar->getSourceRange());
2312 if (SizeOfEachElementExprR.isInvalid())
2316 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2317 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2318 if (BoundExpr.isInvalid())
2322 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2323 // UnqAT is not incomplete and Range is not type-dependent.
2324 llvm_unreachable("Unexpected array type in for-range");
2327 // end-expr is __range + __bound.
2328 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2330 if (EndExpr.isInvalid())
2332 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2333 diag::err_for_range_iter_deduction_failure)) {
2334 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2338 OverloadCandidateSet CandidateSet(RangeLoc,
2339 OverloadCandidateSet::CSK_Normal);
2340 BeginEndFunction BEFFailure;
2341 ForRangeStatus RangeStatus =
2342 BuildNonArrayForRange(*this, BeginRangeRef.get(),
2343 EndRangeRef.get(), RangeType,
2344 BeginVar, EndVar, ColonLoc, &CandidateSet,
2345 &BeginExpr, &EndExpr, &BEFFailure);
2347 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2348 BEFFailure == BEF_begin) {
2349 // If the range is being built from an array parameter, emit a
2350 // a diagnostic that it is being treated as a pointer.
2351 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2352 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2353 QualType ArrayTy = PVD->getOriginalType();
2354 QualType PointerTy = PVD->getType();
2355 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2356 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2357 << RangeLoc << PVD << ArrayTy << PointerTy;
2358 Diag(PVD->getLocation(), diag::note_declared_at);
2364 // If building the range failed, try dereferencing the range expression
2365 // unless a diagnostic was issued or the end function is problematic.
2366 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2368 LoopVarDecl, ColonLoc,
2371 if (SR.isInvalid() || SR.isUsable())
2375 // Otherwise, emit diagnostics if we haven't already.
2376 if (RangeStatus == FRS_NoViableFunction) {
2377 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2378 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2379 << RangeLoc << Range->getType() << BEFFailure;
2380 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2382 // Return an error if no fix was discovered.
2383 if (RangeStatus != FRS_Success)
2387 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2388 "invalid range expression in for loop");
2390 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2391 // C++1z removes this restriction.
2392 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2393 if (!Context.hasSameType(BeginType, EndType)) {
2394 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2395 ? diag::warn_for_range_begin_end_types_differ
2396 : diag::ext_for_range_begin_end_types_differ)
2397 << BeginType << EndType;
2398 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2399 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2403 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2405 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2407 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2408 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2409 VK_LValue, ColonLoc);
2410 if (BeginRef.isInvalid())
2413 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2414 VK_LValue, ColonLoc);
2415 if (EndRef.isInvalid())
2418 // Build and check __begin != __end expression.
2419 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2420 BeginRef.get(), EndRef.get());
2421 if (!NotEqExpr.isInvalid())
2422 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2423 if (!NotEqExpr.isInvalid())
2424 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2425 if (NotEqExpr.isInvalid()) {
2426 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2427 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2428 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2429 if (!Context.hasSameType(BeginType, EndType))
2430 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2434 // Build and check ++__begin expression.
2435 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2436 VK_LValue, ColonLoc);
2437 if (BeginRef.isInvalid())
2440 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2441 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2442 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2443 if (!IncrExpr.isInvalid())
2444 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2445 if (IncrExpr.isInvalid()) {
2446 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2447 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2448 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2452 // Build and check *__begin expression.
2453 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2454 VK_LValue, ColonLoc);
2455 if (BeginRef.isInvalid())
2458 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2459 if (DerefExpr.isInvalid()) {
2460 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2461 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2462 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2466 // Attach *__begin as initializer for VD. Don't touch it if we're just
2467 // trying to determine whether this would be a valid range.
2468 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2469 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2470 if (LoopVar->isInvalidDecl())
2471 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2475 // Don't bother to actually allocate the result if we're just trying to
2476 // determine whether it would be valid.
2477 if (Kind == BFRK_Check)
2478 return StmtResult();
2480 return new (Context) CXXForRangeStmt(
2481 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2482 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2483 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2484 ColonLoc, RParenLoc);
2487 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2489 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2492 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2494 ForStmt->setBody(B);
2498 // Warn when the loop variable is a const reference that creates a copy.
2499 // Suggest using the non-reference type for copies. If a copy can be prevented
2500 // suggest the const reference type that would do so.
2501 // For instance, given "for (const &Foo : Range)", suggest
2502 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2503 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2504 // the copy altogether.
2505 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2507 QualType RangeInitType) {
2508 const Expr *InitExpr = VD->getInit();
2512 QualType VariableType = VD->getType();
2514 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2515 if (!Cleanups->cleanupsHaveSideEffects())
2516 InitExpr = Cleanups->getSubExpr();
2518 const MaterializeTemporaryExpr *MTE =
2519 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2525 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2527 // Searching for either UnaryOperator for dereference of a pointer or
2528 // CXXOperatorCallExpr for handling iterators.
2529 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2530 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2532 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2533 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2536 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2537 E = MTE->GetTemporaryExpr();
2539 E = E->IgnoreImpCasts();
2542 bool ReturnsReference = false;
2543 if (isa<UnaryOperator>(E)) {
2544 ReturnsReference = true;
2546 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2547 const FunctionDecl *FD = Call->getDirectCallee();
2548 QualType ReturnType = FD->getReturnType();
2549 ReturnsReference = ReturnType->isReferenceType();
2552 if (ReturnsReference) {
2553 // Loop variable creates a temporary. Suggest either to go with
2554 // non-reference loop variable to indiciate a copy is made, or
2555 // the correct time to bind a const reference.
2556 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2557 << VD << VariableType << E->getType();
2558 QualType NonReferenceType = VariableType.getNonReferenceType();
2559 NonReferenceType.removeLocalConst();
2560 QualType NewReferenceType =
2561 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2562 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2563 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2565 // The range always returns a copy, so a temporary is always created.
2566 // Suggest removing the reference from the loop variable.
2567 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2568 << VD << RangeInitType;
2569 QualType NonReferenceType = VariableType.getNonReferenceType();
2570 NonReferenceType.removeLocalConst();
2571 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2572 << NonReferenceType << VD->getSourceRange();
2576 // Warns when the loop variable can be changed to a reference type to
2577 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2578 // "for (const Foo &x : Range)" if this form does not make a copy.
2579 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2580 const VarDecl *VD) {
2581 const Expr *InitExpr = VD->getInit();
2585 QualType VariableType = VD->getType();
2587 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2588 if (!CE->getConstructor()->isCopyConstructor())
2590 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2591 if (CE->getCastKind() != CK_LValueToRValue)
2597 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2598 // should be emitted. Also, only ignore POD types with trivial copy
2600 if (VariableType.isPODType(SemaRef.Context))
2603 // Suggest changing from a const variable to a const reference variable
2604 // if doing so will prevent a copy.
2605 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2606 << VD << VariableType << InitExpr->getType();
2607 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2608 << SemaRef.Context.getLValueReferenceType(VariableType)
2609 << VD->getSourceRange();
2612 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2613 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2614 /// using "const foo x" to show that a copy is made
2615 /// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2616 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2617 /// prevent the copy.
2618 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2619 /// Suggest "const foo &x" to prevent the copy.
2620 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2621 const CXXForRangeStmt *ForStmt) {
2622 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2623 ForStmt->getLocStart()) &&
2624 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2625 ForStmt->getLocStart()) &&
2626 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2627 ForStmt->getLocStart())) {
2631 const VarDecl *VD = ForStmt->getLoopVariable();
2635 QualType VariableType = VD->getType();
2637 if (VariableType->isIncompleteType())
2640 const Expr *InitExpr = VD->getInit();
2644 if (VariableType->isReferenceType()) {
2645 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2646 ForStmt->getRangeInit()->getType());
2647 } else if (VariableType.isConstQualified()) {
2648 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2652 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2653 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2654 /// body cannot be performed until after the type of the range variable is
2656 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2660 if (isa<ObjCForCollectionStmt>(S))
2661 return FinishObjCForCollectionStmt(S, B);
2663 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2664 ForStmt->setBody(B);
2666 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2667 diag::warn_empty_range_based_for_body);
2669 DiagnoseForRangeVariableCopies(*this, ForStmt);
2674 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2675 SourceLocation LabelLoc,
2676 LabelDecl *TheDecl) {
2677 getCurFunction()->setHasBranchIntoScope();
2678 TheDecl->markUsed(Context);
2679 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2683 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2685 // Convert operand to void*
2686 if (!E->isTypeDependent()) {
2687 QualType ETy = E->getType();
2688 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2689 ExprResult ExprRes = E;
2690 AssignConvertType ConvTy =
2691 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2692 if (ExprRes.isInvalid())
2695 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2699 ExprResult ExprRes = ActOnFinishFullExpr(E);
2700 if (ExprRes.isInvalid())
2704 getCurFunction()->setHasIndirectGoto();
2706 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2709 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2710 const Scope &DestScope) {
2711 if (!S.CurrentSEHFinally.empty() &&
2712 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2713 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2718 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2719 Scope *S = CurScope->getContinueParent();
2721 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2722 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2724 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2726 return new (Context) ContinueStmt(ContinueLoc);
2730 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2731 Scope *S = CurScope->getBreakParent();
2733 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2734 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2736 if (S->isOpenMPLoopScope())
2737 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2739 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2741 return new (Context) BreakStmt(BreakLoc);
2744 /// \brief Determine whether the given expression is a candidate for
2745 /// copy elision in either a return statement or a throw expression.
2747 /// \param ReturnType If we're determining the copy elision candidate for
2748 /// a return statement, this is the return type of the function. If we're
2749 /// determining the copy elision candidate for a throw expression, this will
2752 /// \param E The expression being returned from the function or block, or
2755 /// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2756 /// id-expressions that could be moved out of the function to be considered NRVO
2757 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2758 /// determine whether we should try to move as part of a return or throw (which
2759 /// does allow function parameters).
2761 /// \returns The NRVO candidate variable, if the return statement may use the
2762 /// NRVO, or NULL if there is no such candidate.
2763 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2764 bool AllowParamOrMoveConstructible) {
2765 if (!getLangOpts().CPlusPlus)
2768 // - in a return statement in a function [where] ...
2769 // ... the expression is the name of a non-volatile automatic object ...
2770 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2771 if (!DR || DR->refersToEnclosingVariableOrCapture())
2773 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2777 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
2782 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2783 bool AllowParamOrMoveConstructible) {
2784 QualType VDType = VD->getType();
2785 // - in a return statement in a function with ...
2786 // ... a class return type ...
2787 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2788 if (!ReturnType->isRecordType())
2790 // ... the same cv-unqualified type as the function return type ...
2791 // When considering moving this expression out, allow dissimilar types.
2792 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
2793 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2797 // ...object (other than a function or catch-clause parameter)...
2798 if (VD->getKind() != Decl::Var &&
2799 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
2801 if (VD->isExceptionVariable()) return false;
2804 if (!VD->hasLocalStorage()) return false;
2806 // Return false if VD is a __block variable. We don't want to implicitly move
2807 // out of a __block variable during a return because we cannot assume the
2808 // variable will no longer be used.
2809 if (VD->hasAttr<BlocksAttr>()) return false;
2811 if (AllowParamOrMoveConstructible)
2814 // ...non-volatile...
2815 if (VD->getType().isVolatileQualified()) return false;
2817 // Variables with higher required alignment than their type's ABI
2818 // alignment cannot use NRVO.
2819 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2820 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2826 /// \brief Perform the initialization of a potentially-movable value, which
2827 /// is the result of return value.
2829 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2830 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2831 /// then falls back to treating them as lvalues if that failed.
2833 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2834 const VarDecl *NRVOCandidate,
2835 QualType ResultType,
2838 // C++14 [class.copy]p32:
2839 // When the criteria for elision of a copy/move operation are met, but not for
2840 // an exception-declaration, and the object to be copied is designated by an
2841 // lvalue, or when the expression in a return statement is a (possibly
2842 // parenthesized) id-expression that names an object with automatic storage
2843 // duration declared in the body or parameter-declaration-clause of the
2844 // innermost enclosing function or lambda-expression, overload resolution to
2845 // select the constructor for the copy is first performed as if the object
2846 // were designated by an rvalue.
2847 ExprResult Res = ExprError();
2849 if (AllowNRVO && !NRVOCandidate)
2850 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2852 if (AllowNRVO && NRVOCandidate) {
2853 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2854 CK_NoOp, Value, VK_XValue);
2856 Expr *InitExpr = &AsRvalue;
2858 InitializationKind Kind = InitializationKind::CreateCopy(
2859 Value->getLocStart(), Value->getLocStart());
2861 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2863 for (const InitializationSequence::Step &Step : Seq.steps()) {
2865 InitializationSequence::SK_ConstructorInitialization ||
2866 (Step.Kind == InitializationSequence::SK_UserConversion &&
2867 isa<CXXConstructorDecl>(Step.Function.Function))))
2870 CXXConstructorDecl *Constructor =
2871 cast<CXXConstructorDecl>(Step.Function.Function);
2873 const RValueReferenceType *RRefType
2874 = Constructor->getParamDecl(0)->getType()
2875 ->getAs<RValueReferenceType>();
2877 // [...] If the first overload resolution fails or was not performed, or
2878 // if the type of the first parameter of the selected constructor is not
2879 // an rvalue reference to the object's type (possibly cv-qualified),
2880 // overload resolution is performed again, considering the object as an
2883 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2884 NRVOCandidate->getType()))
2887 // Promote "AsRvalue" to the heap, since we now need this
2888 // expression node to persist.
2889 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2890 Value, nullptr, VK_XValue);
2892 // Complete type-checking the initialization of the return type
2893 // using the constructor we found.
2894 Res = Seq.Perform(*this, Entity, Kind, Value);
2899 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2900 // above, or overload resolution failed. Either way, we need to try
2901 // (again) now with the return value expression as written.
2902 if (Res.isInvalid())
2903 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2908 /// \brief Determine whether the declared return type of the specified function
2909 /// contains 'auto'.
2910 static bool hasDeducedReturnType(FunctionDecl *FD) {
2911 const FunctionProtoType *FPT =
2912 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2913 return FPT->getReturnType()->isUndeducedType();
2916 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2917 /// for capturing scopes.
2920 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2921 // If this is the first return we've seen, infer the return type.
2922 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2923 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2924 QualType FnRetType = CurCap->ReturnType;
2925 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2926 bool HasDeducedReturnType =
2927 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
2929 if (ExprEvalContexts.back().Context ==
2930 ExpressionEvaluationContext::DiscardedStatement &&
2931 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
2933 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2936 RetValExp = ER.get();
2938 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2941 if (HasDeducedReturnType) {
2942 // In C++1y, the return type may involve 'auto'.
2943 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2944 FunctionDecl *FD = CurLambda->CallOperator;
2945 if (CurCap->ReturnType.isNull())
2946 CurCap->ReturnType = FD->getReturnType();
2948 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2949 assert(AT && "lost auto type from lambda return type");
2950 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2951 FD->setInvalidDecl();
2954 CurCap->ReturnType = FnRetType = FD->getReturnType();
2955 } else if (CurCap->HasImplicitReturnType) {
2956 // For blocks/lambdas with implicit return types, we check each return
2957 // statement individually, and deduce the common return type when the block
2958 // or lambda is completed.
2959 // FIXME: Fold this into the 'auto' codepath above.
2960 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2961 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2962 if (Result.isInvalid())
2964 RetValExp = Result.get();
2966 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2967 // when deducing a return type for a lambda-expression (or by extension
2968 // for a block). These rules differ from the stated C++11 rules only in
2969 // that they remove top-level cv-qualifiers.
2970 if (!CurContext->isDependentContext())
2971 FnRetType = RetValExp->getType().getUnqualifiedType();
2973 FnRetType = CurCap->ReturnType = Context.DependentTy;
2976 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2977 // initializer list, because it is not an expression (even
2978 // though we represent it as one). We still deduce 'void'.
2979 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2980 << RetValExp->getSourceRange();
2983 FnRetType = Context.VoidTy;
2986 // Although we'll properly infer the type of the block once it's completed,
2987 // make sure we provide a return type now for better error recovery.
2988 if (CurCap->ReturnType.isNull())
2989 CurCap->ReturnType = FnRetType;
2991 assert(!FnRetType.isNull());
2993 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2994 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2995 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2998 } else if (CapturedRegionScopeInfo *CurRegion =
2999 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3000 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3003 assert(CurLambda && "unknown kind of captured scope");
3004 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3005 ->getNoReturnAttr()) {
3006 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3011 // Otherwise, verify that this result type matches the previous one. We are
3012 // pickier with blocks than for normal functions because we don't have GCC
3013 // compatibility to worry about here.
3014 const VarDecl *NRVOCandidate = nullptr;
3015 if (FnRetType->isDependentType()) {
3016 // Delay processing for now. TODO: there are lots of dependent
3017 // types we can conclusively prove aren't void.
3018 } else if (FnRetType->isVoidType()) {
3019 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3020 !(getLangOpts().CPlusPlus &&
3021 (RetValExp->isTypeDependent() ||
3022 RetValExp->getType()->isVoidType()))) {
3023 if (!getLangOpts().CPlusPlus &&
3024 RetValExp->getType()->isVoidType())
3025 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3027 Diag(ReturnLoc, diag::err_return_block_has_expr);
3028 RetValExp = nullptr;
3031 } else if (!RetValExp) {
3032 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3033 } else if (!RetValExp->isTypeDependent()) {
3034 // we have a non-void block with an expression, continue checking
3036 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3037 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3040 // In C++ the return statement is handled via a copy initialization.
3041 // the C version of which boils down to CheckSingleAssignmentConstraints.
3042 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3043 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3045 NRVOCandidate != nullptr);
3046 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3047 FnRetType, RetValExp);
3048 if (Res.isInvalid()) {
3049 // FIXME: Cleanup temporaries here, anyway?
3052 RetValExp = Res.get();
3053 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3055 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3059 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3062 RetValExp = ER.get();
3064 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3067 // If we need to check for the named return value optimization,
3068 // or if we need to infer the return type,
3069 // save the return statement in our scope for later processing.
3070 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3071 FunctionScopes.back()->Returns.push_back(Result);
3073 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3074 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3080 /// \brief Marks all typedefs in all local classes in a type referenced.
3082 /// In a function like
3084 /// struct S { typedef int a; };
3088 /// the local type escapes and could be referenced in some TUs but not in
3089 /// others. Pretend that all local typedefs are always referenced, to not warn
3090 /// on this. This isn't necessary if f has internal linkage, or the typedef
3092 class LocalTypedefNameReferencer
3093 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3095 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3096 bool VisitRecordType(const RecordType *RT);
3100 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3101 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3102 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3103 R->isDependentType())
3105 for (auto *TmpD : R->decls())
3106 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3107 if (T->getAccess() != AS_private || R->hasFriends())
3108 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3113 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3114 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3115 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3116 TL = ATL.getModifiedLoc().IgnoreParens();
3117 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3120 /// Deduce the return type for a function from a returned expression, per
3121 /// C++1y [dcl.spec.auto]p6.
3122 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3123 SourceLocation ReturnLoc,
3126 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3129 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3130 // If the deduction is for a return statement and the initializer is
3131 // a braced-init-list, the program is ill-formed.
3132 Diag(RetExpr->getExprLoc(),
3133 getCurLambda() ? diag::err_lambda_return_init_list
3134 : diag::err_auto_fn_return_init_list)
3135 << RetExpr->getSourceRange();
3139 if (FD->isDependentContext()) {
3140 // C++1y [dcl.spec.auto]p12:
3141 // Return type deduction [...] occurs when the definition is
3142 // instantiated even if the function body contains a return
3143 // statement with a non-type-dependent operand.
3144 assert(AT->isDeduced() && "should have deduced to dependent type");
3149 // Otherwise, [...] deduce a value for U using the rules of template
3150 // argument deduction.
3151 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3153 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3154 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3155 << OrigResultType.getType() << RetExpr->getType();
3157 if (DAR != DAR_Succeeded)
3160 // If a local type is part of the returned type, mark its fields as
3162 LocalTypedefNameReferencer Referencer(*this);
3163 Referencer.TraverseType(RetExpr->getType());
3165 // In the case of a return with no operand, the initializer is considered
3168 // Deduction here can only succeed if the return type is exactly 'cv auto'
3169 // or 'decltype(auto)', so just check for that case directly.
3170 if (!OrigResultType.getType()->getAs<AutoType>()) {
3171 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3172 << OrigResultType.getType();
3175 // We always deduce U = void in this case.
3176 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3177 if (Deduced.isNull())
3181 // If a function with a declared return type that contains a placeholder type
3182 // has multiple return statements, the return type is deduced for each return
3183 // statement. [...] if the type deduced is not the same in each deduction,
3184 // the program is ill-formed.
3185 QualType DeducedT = AT->getDeducedType();
3186 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3187 AutoType *NewAT = Deduced->getContainedAutoType();
3188 // It is possible that NewAT->getDeducedType() is null. When that happens,
3189 // we should not crash, instead we ignore this deduction.
3190 if (NewAT->getDeducedType().isNull())
3193 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3195 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3196 NewAT->getDeducedType());
3197 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3198 const LambdaScopeInfo *LambdaSI = getCurLambda();
3199 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3200 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3201 << NewAT->getDeducedType() << DeducedT
3202 << true /*IsLambda*/;
3204 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3205 << (AT->isDecltypeAuto() ? 1 : 0)
3206 << NewAT->getDeducedType() << DeducedT;
3210 } else if (!FD->isInvalidDecl()) {
3211 // Update all declarations of the function to have the deduced return type.
3212 Context.adjustDeducedFunctionResultType(FD, Deduced);
3219 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3221 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3222 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3223 ExpressionEvaluationContext::DiscardedStatement)
3227 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3228 CurScope->addNRVOCandidate(VD);
3230 CurScope->setNoNRVO();
3233 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3238 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3239 // Check for unexpanded parameter packs.
3240 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3243 if (isa<CapturingScopeInfo>(getCurFunction()))
3244 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3247 QualType RelatedRetType;
3248 const AttrVec *Attrs = nullptr;
3249 bool isObjCMethod = false;
3251 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3252 FnRetType = FD->getReturnType();
3254 Attrs = &FD->getAttrs();
3255 if (FD->isNoReturn())
3256 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3257 << FD->getDeclName();
3258 if (FD->isMain() && RetValExp)
3259 if (isa<CXXBoolLiteralExpr>(RetValExp))
3260 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3261 << RetValExp->getSourceRange();
3262 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3263 FnRetType = MD->getReturnType();
3264 isObjCMethod = true;
3266 Attrs = &MD->getAttrs();
3267 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3268 // In the implementation of a method with a related return type, the
3269 // type used to type-check the validity of return statements within the
3270 // method body is a pointer to the type of the class being implemented.
3271 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3272 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3274 } else // If we don't have a function/method context, bail.
3277 // C++1z: discarded return statements are not considered when deducing a
3279 if (ExprEvalContexts.back().Context ==
3280 ExpressionEvaluationContext::DiscardedStatement &&
3281 FnRetType->getContainedAutoType()) {
3283 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3286 RetValExp = ER.get();
3288 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3291 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3293 if (getLangOpts().CPlusPlus14) {
3294 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3295 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3296 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3297 FD->setInvalidDecl();
3300 FnRetType = FD->getReturnType();
3305 bool HasDependentReturnType = FnRetType->isDependentType();
3307 ReturnStmt *Result = nullptr;
3308 if (FnRetType->isVoidType()) {
3310 if (isa<InitListExpr>(RetValExp)) {
3311 // We simply never allow init lists as the return value of void
3312 // functions. This is compatible because this was never allowed before,
3313 // so there's no legacy code to deal with.
3314 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3315 int FunctionKind = 0;
3316 if (isa<ObjCMethodDecl>(CurDecl))
3318 else if (isa<CXXConstructorDecl>(CurDecl))
3320 else if (isa<CXXDestructorDecl>(CurDecl))
3323 Diag(ReturnLoc, diag::err_return_init_list)
3324 << CurDecl->getDeclName() << FunctionKind
3325 << RetValExp->getSourceRange();
3327 // Drop the expression.
3328 RetValExp = nullptr;
3329 } else if (!RetValExp->isTypeDependent()) {
3330 // C99 6.8.6.4p1 (ext_ since GCC warns)
3331 unsigned D = diag::ext_return_has_expr;
3332 if (RetValExp->getType()->isVoidType()) {
3333 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3334 if (isa<CXXConstructorDecl>(CurDecl) ||
3335 isa<CXXDestructorDecl>(CurDecl))
3336 D = diag::err_ctor_dtor_returns_void;
3338 D = diag::ext_return_has_void_expr;
3341 ExprResult Result = RetValExp;
3342 Result = IgnoredValueConversions(Result.get());
3343 if (Result.isInvalid())
3345 RetValExp = Result.get();
3346 RetValExp = ImpCastExprToType(RetValExp,
3347 Context.VoidTy, CK_ToVoid).get();
3349 // return of void in constructor/destructor is illegal in C++.
3350 if (D == diag::err_ctor_dtor_returns_void) {
3351 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3353 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3354 << RetValExp->getSourceRange();
3356 // return (some void expression); is legal in C++.
3357 else if (D != diag::ext_return_has_void_expr ||
3358 !getLangOpts().CPlusPlus) {
3359 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3361 int FunctionKind = 0;
3362 if (isa<ObjCMethodDecl>(CurDecl))
3364 else if (isa<CXXConstructorDecl>(CurDecl))
3366 else if (isa<CXXDestructorDecl>(CurDecl))
3370 << CurDecl->getDeclName() << FunctionKind
3371 << RetValExp->getSourceRange();
3376 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3379 RetValExp = ER.get();
3383 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3384 } else if (!RetValExp && !HasDependentReturnType) {
3385 FunctionDecl *FD = getCurFunctionDecl();
3388 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3389 // C++11 [stmt.return]p2
3390 DiagID = diag::err_constexpr_return_missing_expr;
3391 FD->setInvalidDecl();
3392 } else if (getLangOpts().C99) {
3393 // C99 6.8.6.4p1 (ext_ since GCC warns)
3394 DiagID = diag::ext_return_missing_expr;
3397 DiagID = diag::warn_return_missing_expr;
3401 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3403 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3405 Result = new (Context) ReturnStmt(ReturnLoc);
3407 assert(RetValExp || HasDependentReturnType);
3408 const VarDecl *NRVOCandidate = nullptr;
3410 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3412 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3413 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3416 // In C++ the return statement is handled via a copy initialization,
3417 // the C version of which boils down to CheckSingleAssignmentConstraints.
3419 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3420 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3421 // we have a non-void function with an expression, continue checking
3422 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3424 NRVOCandidate != nullptr);
3425 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3426 RetType, RetValExp);
3427 if (Res.isInvalid()) {
3428 // FIXME: Clean up temporaries here anyway?
3431 RetValExp = Res.getAs<Expr>();
3433 // If we have a related result type, we need to implicitly
3434 // convert back to the formal result type. We can't pretend to
3435 // initialize the result again --- we might end double-retaining
3436 // --- so instead we initialize a notional temporary.
3437 if (!RelatedRetType.isNull()) {
3438 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3440 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3441 if (Res.isInvalid()) {
3442 // FIXME: Clean up temporaries here anyway?
3445 RetValExp = Res.getAs<Expr>();
3448 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3449 getCurFunctionDecl());
3453 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3456 RetValExp = ER.get();
3458 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3461 // If we need to check for the named return value optimization, save the
3462 // return statement in our scope for later processing.
3463 if (Result->getNRVOCandidate())
3464 FunctionScopes.back()->Returns.push_back(Result);
3466 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3467 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3473 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3474 SourceLocation RParen, Decl *Parm,
3476 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3477 if (Var && Var->isInvalidDecl())
3480 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3484 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3485 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3489 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3490 MultiStmtArg CatchStmts, Stmt *Finally) {
3491 if (!getLangOpts().ObjCExceptions)
3492 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3494 getCurFunction()->setHasBranchProtectedScope();
3495 unsigned NumCatchStmts = CatchStmts.size();
3496 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3497 NumCatchStmts, Finally);
3500 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3502 ExprResult Result = DefaultLvalueConversion(Throw);
3503 if (Result.isInvalid())
3506 Result = ActOnFinishFullExpr(Result.get());
3507 if (Result.isInvalid())
3509 Throw = Result.get();
3511 QualType ThrowType = Throw->getType();
3512 // Make sure the expression type is an ObjC pointer or "void *".
3513 if (!ThrowType->isDependentType() &&
3514 !ThrowType->isObjCObjectPointerType()) {
3515 const PointerType *PT = ThrowType->getAs<PointerType>();
3516 if (!PT || !PT->getPointeeType()->isVoidType())
3517 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3518 << Throw->getType() << Throw->getSourceRange());
3522 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3526 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3528 if (!getLangOpts().ObjCExceptions)
3529 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3532 // @throw without an expression designates a rethrow (which must occur
3533 // in the context of an @catch clause).
3534 Scope *AtCatchParent = CurScope;
3535 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3536 AtCatchParent = AtCatchParent->getParent();
3538 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3540 return BuildObjCAtThrowStmt(AtLoc, Throw);
3544 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3545 ExprResult result = DefaultLvalueConversion(operand);
3546 if (result.isInvalid())
3548 operand = result.get();
3550 // Make sure the expression type is an ObjC pointer or "void *".
3551 QualType type = operand->getType();
3552 if (!type->isDependentType() &&
3553 !type->isObjCObjectPointerType()) {
3554 const PointerType *pointerType = type->getAs<PointerType>();
3555 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3556 if (getLangOpts().CPlusPlus) {
3557 if (RequireCompleteType(atLoc, type,
3558 diag::err_incomplete_receiver_type))
3559 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3560 << type << operand->getSourceRange();
3562 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3563 if (result.isInvalid())
3565 if (!result.isUsable())
3566 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3567 << type << operand->getSourceRange();
3569 operand = result.get();
3571 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3572 << type << operand->getSourceRange();
3577 // The operand to @synchronized is a full-expression.
3578 return ActOnFinishFullExpr(operand);
3582 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3584 // We can't jump into or indirect-jump out of a @synchronized block.
3585 getCurFunction()->setHasBranchProtectedScope();
3586 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3589 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3590 /// and creates a proper catch handler from them.
3592 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3593 Stmt *HandlerBlock) {
3594 // There's nothing to test that ActOnExceptionDecl didn't already test.
3595 return new (Context)
3596 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3600 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3601 getCurFunction()->setHasBranchProtectedScope();
3602 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3606 class CatchHandlerType {
3608 unsigned IsPointer : 1;
3610 // This is a special constructor to be used only with DenseMapInfo's
3611 // getEmptyKey() and getTombstoneKey() functions.
3612 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3613 enum Unique { ForDenseMap };
3614 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3617 /// Used when creating a CatchHandlerType from a handler type; will determine
3618 /// whether the type is a pointer or reference and will strip off the top
3619 /// level pointer and cv-qualifiers.
3620 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3621 if (QT->isPointerType())
3624 if (IsPointer || QT->isReferenceType())
3625 QT = QT->getPointeeType();
3626 QT = QT.getUnqualifiedType();
3629 /// Used when creating a CatchHandlerType from a base class type; pretends the
3630 /// type passed in had the pointer qualifier, does not need to get an
3631 /// unqualified type.
3632 CatchHandlerType(QualType QT, bool IsPointer)
3633 : QT(QT), IsPointer(IsPointer) {}
3635 QualType underlying() const { return QT; }
3636 bool isPointer() const { return IsPointer; }
3638 friend bool operator==(const CatchHandlerType &LHS,
3639 const CatchHandlerType &RHS) {
3640 // If the pointer qualification does not match, we can return early.
3641 if (LHS.IsPointer != RHS.IsPointer)
3643 // Otherwise, check the underlying type without cv-qualifiers.
3644 return LHS.QT == RHS.QT;
3650 template <> struct DenseMapInfo<CatchHandlerType> {
3651 static CatchHandlerType getEmptyKey() {
3652 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3653 CatchHandlerType::ForDenseMap);
3656 static CatchHandlerType getTombstoneKey() {
3657 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3658 CatchHandlerType::ForDenseMap);
3661 static unsigned getHashValue(const CatchHandlerType &Base) {
3662 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3665 static bool isEqual(const CatchHandlerType &LHS,
3666 const CatchHandlerType &RHS) {
3673 class CatchTypePublicBases {
3675 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3676 const bool CheckAgainstPointer;
3678 CXXCatchStmt *FoundHandler;
3679 CanQualType FoundHandlerType;
3682 CatchTypePublicBases(
3684 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3685 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3686 FoundHandler(nullptr) {}
3688 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3689 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3691 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3692 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3693 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3694 const auto &M = TypesToCheck;
3695 auto I = M.find(Check);
3697 FoundHandler = I->second;
3698 FoundHandlerType = Ctx.getCanonicalType(S->getType());
3707 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3708 /// handlers and creates a try statement from them.
3709 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3710 ArrayRef<Stmt *> Handlers) {
3711 // Don't report an error if 'try' is used in system headers.
3712 if (!getLangOpts().CXXExceptions &&
3713 !getSourceManager().isInSystemHeader(TryLoc))
3714 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3716 // Exceptions aren't allowed in CUDA device code.
3717 if (getLangOpts().CUDA)
3718 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3719 << "try" << CurrentCUDATarget();
3721 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3722 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3724 sema::FunctionScopeInfo *FSI = getCurFunction();
3726 // C++ try is incompatible with SEH __try.
3727 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3728 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3729 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3732 const unsigned NumHandlers = Handlers.size();
3733 assert(!Handlers.empty() &&
3734 "The parser shouldn't call this if there are no handlers.");
3736 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3737 for (unsigned i = 0; i < NumHandlers; ++i) {
3738 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3740 // Diagnose when the handler is a catch-all handler, but it isn't the last
3741 // handler for the try block. [except.handle]p5. Also, skip exception
3742 // declarations that are invalid, since we can't usefully report on them.
3743 if (!H->getExceptionDecl()) {
3744 if (i < NumHandlers - 1)
3745 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3747 } else if (H->getExceptionDecl()->isInvalidDecl())
3750 // Walk the type hierarchy to diagnose when this type has already been
3751 // handled (duplication), or cannot be handled (derivation inversion). We
3752 // ignore top-level cv-qualifiers, per [except.handle]p3
3753 CatchHandlerType HandlerCHT =
3754 (QualType)Context.getCanonicalType(H->getCaughtType());
3756 // We can ignore whether the type is a reference or a pointer; we need the
3757 // underlying declaration type in order to get at the underlying record
3758 // decl, if there is one.
3759 QualType Underlying = HandlerCHT.underlying();
3760 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3761 if (!RD->hasDefinition())
3763 // Check that none of the public, unambiguous base classes are in the
3764 // map ([except.handle]p1). Give the base classes the same pointer
3765 // qualification as the original type we are basing off of. This allows
3766 // comparison against the handler type using the same top-level pointer
3767 // as the original type.
3769 Paths.setOrigin(RD);
3770 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3771 if (RD->lookupInBases(CTPB, Paths)) {
3772 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3773 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3774 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3775 diag::warn_exception_caught_by_earlier_handler)
3776 << H->getCaughtType();
3777 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3778 diag::note_previous_exception_handler)
3779 << Problem->getCaughtType();
3784 // Add the type the list of ones we have handled; diagnose if we've already
3786 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3788 const CXXCatchStmt *Problem = R.first->second;
3789 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3790 diag::warn_exception_caught_by_earlier_handler)
3791 << H->getCaughtType();
3792 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3793 diag::note_previous_exception_handler)
3794 << Problem->getCaughtType();
3798 FSI->setHasCXXTry(TryLoc);
3800 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3803 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3804 Stmt *TryBlock, Stmt *Handler) {
3805 assert(TryBlock && Handler);
3807 sema::FunctionScopeInfo *FSI = getCurFunction();
3809 // SEH __try is incompatible with C++ try. Borland appears to support this,
3811 if (!getLangOpts().Borland) {
3812 if (FSI->FirstCXXTryLoc.isValid()) {
3813 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3814 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3818 FSI->setHasSEHTry(TryLoc);
3820 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3821 // track if they use SEH.
3822 DeclContext *DC = CurContext;
3823 while (DC && !DC->isFunctionOrMethod())
3824 DC = DC->getParent();
3825 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3827 FD->setUsesSEHTry(true);
3829 Diag(TryLoc, diag::err_seh_try_outside_functions);
3831 // Reject __try on unsupported targets.
3832 if (!Context.getTargetInfo().isSEHTrySupported())
3833 Diag(TryLoc, diag::err_seh_try_unsupported);
3835 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
3839 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3842 assert(FilterExpr && Block);
3844 if(!FilterExpr->getType()->isIntegerType()) {
3845 return StmtError(Diag(FilterExpr->getExprLoc(),
3846 diag::err_filter_expression_integral)
3847 << FilterExpr->getType());
3850 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3853 void Sema::ActOnStartSEHFinallyBlock() {
3854 CurrentSEHFinally.push_back(CurScope);
3857 void Sema::ActOnAbortSEHFinallyBlock() {
3858 CurrentSEHFinally.pop_back();
3861 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
3863 CurrentSEHFinally.pop_back();
3864 return SEHFinallyStmt::Create(Context, Loc, Block);
3868 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3869 Scope *SEHTryParent = CurScope;
3870 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3871 SEHTryParent = SEHTryParent->getParent();
3873 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3874 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
3876 return new (Context) SEHLeaveStmt(Loc);
3879 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3881 NestedNameSpecifierLoc QualifierLoc,
3882 DeclarationNameInfo NameInfo,
3885 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3886 QualifierLoc, NameInfo,
3887 cast<CompoundStmt>(Nested));
3891 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3894 UnqualifiedId &Name,
3896 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3897 SS.getWithLocInContext(Context),
3898 GetNameFromUnqualifiedId(Name),
3903 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3904 unsigned NumParams) {
3905 DeclContext *DC = CurContext;
3906 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3907 DC = DC->getParent();
3909 RecordDecl *RD = nullptr;
3910 if (getLangOpts().CPlusPlus)
3911 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3914 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3916 RD->setCapturedRecord();
3919 RD->startDefinition();
3921 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3922 CD = CapturedDecl::Create(Context, CurContext, NumParams);
3927 static void buildCapturedStmtCaptureList(
3928 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3929 SmallVectorImpl<Expr *> &CaptureInits,
3930 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3932 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3933 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3935 if (Cap->isThisCapture()) {
3936 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3937 CapturedStmt::VCK_This));
3938 CaptureInits.push_back(Cap->getInitExpr());
3940 } else if (Cap->isVLATypeCapture()) {
3942 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3943 CaptureInits.push_back(nullptr);
3947 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3948 Cap->isReferenceCapture()
3949 ? CapturedStmt::VCK_ByRef
3950 : CapturedStmt::VCK_ByCopy,
3951 Cap->getVariable()));
3952 CaptureInits.push_back(Cap->getInitExpr());
3956 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3957 CapturedRegionKind Kind,
3958 unsigned NumParams) {
3959 CapturedDecl *CD = nullptr;
3960 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3962 // Build the context parameter
3963 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3964 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3965 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3966 ImplicitParamDecl *Param
3967 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3970 CD->setContextParam(0, Param);
3972 // Enter the capturing scope for this captured region.
3973 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3976 PushDeclContext(CurScope, CD);
3980 PushExpressionEvaluationContext(
3981 ExpressionEvaluationContext::PotentiallyEvaluated);
3984 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3985 CapturedRegionKind Kind,
3986 ArrayRef<CapturedParamNameType> Params) {
3987 CapturedDecl *CD = nullptr;
3988 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3990 // Build the context parameter
3991 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3992 bool ContextIsFound = false;
3993 unsigned ParamNum = 0;
3994 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3996 I != E; ++I, ++ParamNum) {
3997 if (I->second.isNull()) {
3998 assert(!ContextIsFound &&
3999 "null type has been found already for '__context' parameter");
4000 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4001 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4002 ImplicitParamDecl *Param
4003 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
4005 CD->setContextParam(ParamNum, Param);
4006 ContextIsFound = true;
4008 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4009 ImplicitParamDecl *Param
4010 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
4012 CD->setParam(ParamNum, Param);
4015 assert(ContextIsFound && "no null type for '__context' parameter");
4016 if (!ContextIsFound) {
4017 // Add __context implicitly if it is not specified.
4018 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4019 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4020 ImplicitParamDecl *Param =
4021 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
4023 CD->setContextParam(ParamNum, Param);
4025 // Enter the capturing scope for this captured region.
4026 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4029 PushDeclContext(CurScope, CD);
4033 PushExpressionEvaluationContext(
4034 ExpressionEvaluationContext::PotentiallyEvaluated);
4037 void Sema::ActOnCapturedRegionError() {
4038 DiscardCleanupsInEvaluationContext();
4039 PopExpressionEvaluationContext();
4041 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4042 RecordDecl *Record = RSI->TheRecordDecl;
4043 Record->setInvalidDecl();
4045 SmallVector<Decl*, 4> Fields(Record->fields());
4046 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4047 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
4050 PopFunctionScopeInfo();
4053 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4054 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4056 SmallVector<CapturedStmt::Capture, 4> Captures;
4057 SmallVector<Expr *, 4> CaptureInits;
4058 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4060 CapturedDecl *CD = RSI->TheCapturedDecl;
4061 RecordDecl *RD = RSI->TheRecordDecl;
4063 CapturedStmt *Res = CapturedStmt::Create(
4064 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4065 Captures, CaptureInits, CD, RD);
4067 CD->setBody(Res->getCapturedStmt());
4068 RD->completeDefinition();
4070 DiscardCleanupsInEvaluationContext();
4071 PopExpressionEvaluationContext();
4074 PopFunctionScopeInfo();