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/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/SmallVector.h"
35 using namespace clang;
38 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
42 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43 /*DiscardedValue*/ true);
47 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48 // void expression for its side effects. Conversion to void allows any
49 // operand, even incomplete types.
51 // Same thing in for stmt first clause (when expr) and third clause.
52 return StmtResult(FE.getAs<Stmt>());
56 StmtResult Sema::ActOnExprStmtError() {
57 DiscardCleanupsInEvaluationContext();
61 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
62 bool HasLeadingEmptyMacro) {
63 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
66 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67 SourceLocation EndLoc) {
68 DeclGroupRef DG = dg.get();
70 // If we have an invalid decl, just return an error.
71 if (DG.isNull()) return StmtError();
73 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
76 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
77 DeclGroupRef DG = dg.get();
79 // If we don't have a declaration, or we have an invalid declaration,
81 if (DG.isNull() || !DG.isSingleDecl())
84 Decl *decl = DG.getSingleDecl();
85 if (!decl || decl->isInvalidDecl())
88 // Only variable declarations are permitted.
89 VarDecl *var = dyn_cast<VarDecl>(decl);
91 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
92 decl->setInvalidDecl();
96 // foreach variables are never actually initialized in the way that
97 // the parser came up with.
98 var->setInit(nullptr);
100 // In ARC, we don't need to retain the iteration variable of a fast
101 // enumeration loop. Rather than actually trying to catch that
102 // during declaration processing, we remove the consequences here.
103 if (getLangOpts().ObjCAutoRefCount) {
104 QualType type = var->getType();
106 // Only do this if we inferred the lifetime. Inferred lifetime
107 // will show up as a local qualifier because explicit lifetime
108 // should have shown up as an AttributedType instead.
109 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
110 // Add 'const' and mark the variable as pseudo-strong.
111 var->setType(type.withConst());
112 var->setARCPseudoStrong(true);
117 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
118 /// For '==' and '!=', suggest fixits for '=' or '|='.
120 /// Adding a cast to void (or other expression wrappers) will prevent the
121 /// warning from firing.
122 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
124 bool IsNotEqual, CanAssign, IsRelational;
126 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
127 if (!Op->isComparisonOp())
130 IsRelational = Op->isRelationalOp();
131 Loc = Op->getOperatorLoc();
132 IsNotEqual = Op->getOpcode() == BO_NE;
133 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
134 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
135 switch (Op->getOperator()) {
139 case OO_ExclaimEqual:
140 IsRelational = false;
144 case OO_GreaterEqual:
150 Loc = Op->getOperatorLoc();
151 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
152 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
154 // Not a typo-prone comparison.
158 // Suppress warnings when the operator, suspicious as it may be, comes from
159 // a macro expansion.
160 if (S.SourceMgr.isMacroBodyExpansion(Loc))
163 S.Diag(Loc, diag::warn_unused_comparison)
164 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
166 // If the LHS is a plausible entity to assign to, provide a fixit hint to
167 // correct common typos.
168 if (!IsRelational && CanAssign) {
170 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
171 << FixItHint::CreateReplacement(Loc, "|=");
173 S.Diag(Loc, diag::note_equality_comparison_to_assign)
174 << FixItHint::CreateReplacement(Loc, "=");
180 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
181 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
182 return DiagnoseUnusedExprResult(Label->getSubStmt());
184 const Expr *E = dyn_cast_or_null<Expr>(S);
187 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
188 // In most cases, we don't want to warn if the expression is written in a
189 // macro body, or if the macro comes from a system header. If the offending
190 // expression is a call to a function with the warn_unused_result attribute,
191 // we warn no matter the location. Because of the order in which the various
192 // checks need to happen, we factor out the macro-related test here.
193 bool ShouldSuppress =
194 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
195 SourceMgr.isInSystemMacro(ExprLoc);
197 const Expr *WarnExpr;
200 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
203 // If this is a GNU statement expression expanded from a macro, it is probably
204 // unused because it is a function-like macro that can be used as either an
205 // expression or statement. Don't warn, because it is almost certainly a
207 if (isa<StmtExpr>(E) && Loc.isMacroID())
210 // Okay, we have an unused result. Depending on what the base expression is,
211 // we might want to make a more specific diagnostic. Check for one of these
213 unsigned DiagID = diag::warn_unused_expr;
214 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
215 E = Temps->getSubExpr();
216 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
217 E = TempExpr->getSubExpr();
219 if (DiagnoseUnusedComparison(*this, E))
223 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
224 if (E->getType()->isVoidType())
227 // If the callee has attribute pure, const, or warn_unused_result, warn with
228 // a more specific message to make it clear what is happening. If the call
229 // is written in a macro body, only warn if it has the warn_unused_result
231 if (const Decl *FD = CE->getCalleeDecl()) {
232 if (FD->hasAttr<WarnUnusedResultAttr>()) {
233 Diag(Loc, diag::warn_unused_result) << R1 << R2;
238 if (FD->hasAttr<PureAttr>()) {
239 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
242 if (FD->hasAttr<ConstAttr>()) {
243 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
247 } else if (ShouldSuppress)
250 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
251 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
252 Diag(Loc, diag::err_arc_unused_init_message) << R1;
255 const ObjCMethodDecl *MD = ME->getMethodDecl();
257 if (MD->hasAttr<WarnUnusedResultAttr>()) {
258 Diag(Loc, diag::warn_unused_result) << R1 << R2;
261 if (MD->isPropertyAccessor()) {
262 Diag(Loc, diag::warn_unused_property_expr);
266 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
267 const Expr *Source = POE->getSyntacticForm();
268 if (isa<ObjCSubscriptRefExpr>(Source))
269 DiagID = diag::warn_unused_container_subscript_expr;
271 DiagID = diag::warn_unused_property_expr;
272 } else if (const CXXFunctionalCastExpr *FC
273 = dyn_cast<CXXFunctionalCastExpr>(E)) {
274 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
275 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
278 // Diagnose "(void*) blah" as a typo for "(void) blah".
279 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
280 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
281 QualType T = TI->getType();
283 // We really do want to use the non-canonical type here.
284 if (T == Context.VoidPtrTy) {
285 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
287 Diag(Loc, diag::warn_unused_voidptr)
288 << FixItHint::CreateRemoval(TL.getStarLoc());
293 if (E->isGLValue() && E->getType().isVolatileQualified()) {
294 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
298 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
301 void Sema::ActOnStartOfCompoundStmt() {
305 void Sema::ActOnFinishOfCompoundStmt() {
309 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
310 return getCurFunction()->CompoundScopes.back();
313 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
314 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
315 const unsigned NumElts = Elts.size();
317 // If we're in C89 mode, check that we don't have any decls after stmts. If
318 // so, emit an extension diagnostic.
319 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
320 // Note that __extension__ can be around a decl.
322 // Skip over all declarations.
323 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
326 // We found the end of the list or a statement. Scan for another declstmt.
327 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
331 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
332 Diag(D->getLocation(), diag::ext_mixed_decls_code);
335 // Warn about unused expressions in statements.
336 for (unsigned i = 0; i != NumElts; ++i) {
337 // Ignore statements that are last in a statement expression.
338 if (isStmtExpr && i == NumElts - 1)
341 DiagnoseUnusedExprResult(Elts[i]);
344 // Check for suspicious empty body (null statement) in `for' and `while'
345 // statements. Don't do anything for template instantiations, this just adds
347 if (NumElts != 0 && !CurrentInstantiationScope &&
348 getCurCompoundScope().HasEmptyLoopBodies) {
349 for (unsigned i = 0; i != NumElts - 1; ++i)
350 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
353 return new (Context) CompoundStmt(Context, Elts, L, R);
357 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
358 SourceLocation DotDotDotLoc, Expr *RHSVal,
359 SourceLocation ColonLoc) {
360 assert(LHSVal && "missing expression in case statement");
362 if (getCurFunction()->SwitchStack.empty()) {
363 Diag(CaseLoc, diag::err_case_not_in_switch);
367 if (!getLangOpts().CPlusPlus11) {
368 // C99 6.8.4.2p3: The expression shall be an integer constant.
369 // However, GCC allows any evaluatable integer expression.
370 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
371 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
376 // GCC extension: The expression shall be an integer constant.
378 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
379 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
380 // Recover from an error by just forgetting about it.
384 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
385 getLangOpts().CPlusPlus11).get();
387 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
388 getLangOpts().CPlusPlus11).get();
390 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
392 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
396 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
397 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
398 DiagnoseUnusedExprResult(SubStmt);
400 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
401 CS->setSubStmt(SubStmt);
405 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
406 Stmt *SubStmt, Scope *CurScope) {
407 DiagnoseUnusedExprResult(SubStmt);
409 if (getCurFunction()->SwitchStack.empty()) {
410 Diag(DefaultLoc, diag::err_default_not_in_switch);
414 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
415 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
420 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
421 SourceLocation ColonLoc, Stmt *SubStmt) {
422 // If the label was multiply defined, reject it now.
423 if (TheDecl->getStmt()) {
424 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
425 Diag(TheDecl->getLocation(), diag::note_previous_definition);
429 // Otherwise, things are good. Fill in the declaration and return it.
430 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
431 TheDecl->setStmt(LS);
432 if (!TheDecl->isGnuLocal()) {
433 TheDecl->setLocStart(IdentLoc);
434 TheDecl->setLocation(IdentLoc);
439 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
440 ArrayRef<const Attr*> Attrs,
442 // Fill in the declaration and return it.
443 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
448 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
449 Stmt *thenStmt, SourceLocation ElseLoc,
451 // If the condition was invalid, discard the if statement. We could recover
452 // better by replacing it with a valid expr, but don't do that yet.
453 if (!CondVal.get() && !CondVar) {
454 getCurFunction()->setHasDroppedStmt();
458 ExprResult CondResult(CondVal.release());
460 VarDecl *ConditionVar = nullptr;
462 ConditionVar = cast<VarDecl>(CondVar);
463 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
464 if (CondResult.isInvalid())
467 Expr *ConditionExpr = CondResult.getAs<Expr>();
471 DiagnoseUnusedExprResult(thenStmt);
474 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
475 diag::warn_empty_if_body);
478 DiagnoseUnusedExprResult(elseStmt);
480 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
481 thenStmt, ElseLoc, elseStmt);
484 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
485 /// the specified width and sign. If an overflow occurs, detect it and emit
486 /// the specified diagnostic.
487 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
488 unsigned NewWidth, bool NewSign,
491 // Perform a conversion to the promoted condition type if needed.
492 if (NewWidth > Val.getBitWidth()) {
493 // If this is an extension, just do it.
494 Val = Val.extend(NewWidth);
495 Val.setIsSigned(NewSign);
497 // If the input was signed and negative and the output is
498 // unsigned, don't bother to warn: this is implementation-defined
500 // FIXME: Introduce a second, default-ignored warning for this case?
501 } else if (NewWidth < Val.getBitWidth()) {
502 // If this is a truncation, check for overflow.
503 llvm::APSInt ConvVal(Val);
504 ConvVal = ConvVal.trunc(NewWidth);
505 ConvVal.setIsSigned(NewSign);
506 ConvVal = ConvVal.extend(Val.getBitWidth());
507 ConvVal.setIsSigned(Val.isSigned());
509 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
511 // Regardless of whether a diagnostic was emitted, really do the
513 Val = Val.trunc(NewWidth);
514 Val.setIsSigned(NewSign);
515 } else if (NewSign != Val.isSigned()) {
516 // Convert the sign to match the sign of the condition. This can cause
517 // overflow as well: unsigned(INTMIN)
518 // We don't diagnose this overflow, because it is implementation-defined
520 // FIXME: Introduce a second, default-ignored warning for this case?
521 Val.setIsSigned(NewSign);
526 struct CaseCompareFunctor {
527 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
528 const llvm::APSInt &RHS) {
529 return LHS.first < RHS;
531 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
532 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
533 return LHS.first < RHS.first;
535 bool operator()(const llvm::APSInt &LHS,
536 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
537 return LHS < RHS.first;
542 /// CmpCaseVals - Comparison predicate for sorting case values.
544 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
545 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
546 if (lhs.first < rhs.first)
549 if (lhs.first == rhs.first &&
550 lhs.second->getCaseLoc().getRawEncoding()
551 < rhs.second->getCaseLoc().getRawEncoding())
556 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
558 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
559 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
561 return lhs.first < rhs.first;
564 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
566 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
567 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
569 return lhs.first == rhs.first;
572 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
573 /// potentially integral-promoted expression @p expr.
574 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
575 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
576 expr = cleanups->getSubExpr();
577 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
578 if (impcast->getCastKind() != CK_IntegralCast) break;
579 expr = impcast->getSubExpr();
581 return expr->getType();
585 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
587 ExprResult CondResult;
589 VarDecl *ConditionVar = nullptr;
591 ConditionVar = cast<VarDecl>(CondVar);
592 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
593 if (CondResult.isInvalid())
596 Cond = CondResult.get();
602 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
606 SwitchConvertDiagnoser(Expr *Cond)
607 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
610 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
611 QualType T) override {
612 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
615 SemaDiagnosticBuilder diagnoseIncomplete(
616 Sema &S, SourceLocation Loc, QualType T) override {
617 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
618 << T << Cond->getSourceRange();
621 SemaDiagnosticBuilder diagnoseExplicitConv(
622 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
623 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
626 SemaDiagnosticBuilder noteExplicitConv(
627 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
628 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
629 << ConvTy->isEnumeralType() << ConvTy;
632 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
633 QualType T) override {
634 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
637 SemaDiagnosticBuilder noteAmbiguous(
638 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
639 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
640 << ConvTy->isEnumeralType() << ConvTy;
643 SemaDiagnosticBuilder diagnoseConversion(
644 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
645 llvm_unreachable("conversion functions are permitted");
647 } SwitchDiagnoser(Cond);
650 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
651 if (CondResult.isInvalid()) return StmtError();
652 Cond = CondResult.get();
654 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
655 CondResult = UsualUnaryConversions(Cond);
656 if (CondResult.isInvalid()) return StmtError();
657 Cond = CondResult.get();
660 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
661 if (CondResult.isInvalid())
663 Cond = CondResult.get();
666 getCurFunction()->setHasBranchIntoScope();
668 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
669 getCurFunction()->SwitchStack.push_back(SS);
673 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
674 if (Val.getBitWidth() < BitWidth)
675 Val = Val.extend(BitWidth);
676 else if (Val.getBitWidth() > BitWidth)
677 Val = Val.trunc(BitWidth);
678 Val.setIsSigned(IsSigned);
681 /// Returns true if we should emit a diagnostic about this case expression not
682 /// being a part of the enum used in the switch controlling expression.
683 static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
685 const Expr *CaseExpr) {
686 // Don't warn if the 'case' expression refers to a static const variable of
688 CaseExpr = CaseExpr->IgnoreParenImpCasts();
689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
690 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
691 if (!VD->hasGlobalStorage())
693 QualType VarType = VD->getType();
694 if (!VarType.isConstQualified())
696 QualType EnumType = Ctx.getTypeDeclType(ED);
697 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
705 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
707 SwitchStmt *SS = cast<SwitchStmt>(Switch);
708 assert(SS == getCurFunction()->SwitchStack.back() &&
709 "switch stack missing push/pop!");
711 if (!BodyStmt) return StmtError();
712 SS->setBody(BodyStmt, SwitchLoc);
713 getCurFunction()->SwitchStack.pop_back();
715 Expr *CondExpr = SS->getCond();
716 if (!CondExpr) return StmtError();
718 QualType CondType = CondExpr->getType();
720 Expr *CondExprBeforePromotion = CondExpr;
721 QualType CondTypeBeforePromotion =
722 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
725 // Integral promotions are performed (on the switch condition).
727 // A case value unrepresentable by the original switch condition
728 // type (before the promotion) doesn't make sense, even when it can
729 // be represented by the promoted type. Therefore we need to find
730 // the pre-promotion type of the switch condition.
731 if (!CondExpr->isTypeDependent()) {
732 // We have already converted the expression to an integral or enumeration
733 // type, when we started the switch statement. If we don't have an
734 // appropriate type now, just return an error.
735 if (!CondType->isIntegralOrEnumerationType())
738 if (CondExpr->isKnownToHaveBooleanValue()) {
739 // switch(bool_expr) {...} is often a programmer error, e.g.
740 // switch(n && mask) { ... } // Doh - should be "n & mask".
741 // One can always use an if statement instead of switch(bool_expr).
742 Diag(SwitchLoc, diag::warn_bool_switch_condition)
743 << CondExpr->getSourceRange();
747 // Get the bitwidth of the switched-on value before promotions. We must
748 // convert the integer case values to this width before comparison.
749 bool HasDependentValue
750 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
752 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
754 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
756 // Accumulate all of the case values in a vector so that we can sort them
757 // and detect duplicates. This vector contains the APInt for the case after
758 // it has been converted to the condition type.
759 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
762 // Keep track of any GNU case ranges we see. The APSInt is the low value.
763 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
764 CaseRangesTy CaseRanges;
766 DefaultStmt *TheDefaultStmt = nullptr;
768 bool CaseListIsErroneous = false;
770 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
771 SC = SC->getNextSwitchCase()) {
773 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
774 if (TheDefaultStmt) {
775 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
776 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
778 // FIXME: Remove the default statement from the switch block so that
779 // we'll return a valid AST. This requires recursing down the AST and
780 // finding it, not something we are set up to do right now. For now,
781 // just lop the entire switch stmt out of the AST.
782 CaseListIsErroneous = true;
787 CaseStmt *CS = cast<CaseStmt>(SC);
789 Expr *Lo = CS->getLHS();
791 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
792 HasDependentValue = true;
798 if (getLangOpts().CPlusPlus11) {
799 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
800 // constant expression of the promoted type of the switch condition.
802 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
803 if (ConvLo.isInvalid()) {
804 CaseListIsErroneous = true;
809 // We already verified that the expression has a i-c-e value (C99
810 // 6.8.4.2p3) - get that value now.
811 LoVal = Lo->EvaluateKnownConstInt(Context);
813 // If the LHS is not the same type as the condition, insert an implicit
815 Lo = DefaultLvalueConversion(Lo).get();
816 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
819 // Convert the value to the same width/sign as the condition had prior to
820 // integral promotions.
822 // FIXME: This causes us to reject valid code:
823 // switch ((char)c) { case 256: case 0: return 0; }
824 // Here we claim there is a duplicated condition value, but there is not.
825 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
827 diag::warn_case_value_overflow);
831 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
833 if (CS->getRHS()->isTypeDependent() ||
834 CS->getRHS()->isValueDependent()) {
835 HasDependentValue = true;
838 CaseRanges.push_back(std::make_pair(LoVal, CS));
840 CaseVals.push_back(std::make_pair(LoVal, CS));
844 if (!HasDependentValue) {
845 // If we don't have a default statement, check whether the
846 // condition is constant.
847 llvm::APSInt ConstantCondValue;
848 bool HasConstantCond = false;
849 if (!HasDependentValue && !TheDefaultStmt) {
851 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
852 Expr::SE_AllowSideEffects);
853 assert(!HasConstantCond ||
854 (ConstantCondValue.getBitWidth() == CondWidth &&
855 ConstantCondValue.isSigned() == CondIsSigned));
857 bool ShouldCheckConstantCond = HasConstantCond;
859 // Sort all the scalar case values so we can easily detect duplicates.
860 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
862 if (!CaseVals.empty()) {
863 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
864 if (ShouldCheckConstantCond &&
865 CaseVals[i].first == ConstantCondValue)
866 ShouldCheckConstantCond = false;
868 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
869 // If we have a duplicate, report it.
870 // First, determine if either case value has a name
871 StringRef PrevString, CurrString;
872 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
873 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
874 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
875 PrevString = DeclRef->getDecl()->getName();
877 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
878 CurrString = DeclRef->getDecl()->getName();
880 SmallString<16> CaseValStr;
881 CaseVals[i-1].first.toString(CaseValStr);
883 if (PrevString == CurrString)
884 Diag(CaseVals[i].second->getLHS()->getLocStart(),
885 diag::err_duplicate_case) <<
886 (PrevString.empty() ? CaseValStr.str() : PrevString);
888 Diag(CaseVals[i].second->getLHS()->getLocStart(),
889 diag::err_duplicate_case_differing_expr) <<
890 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
891 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
894 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
895 diag::note_duplicate_case_prev);
896 // FIXME: We really want to remove the bogus case stmt from the
897 // substmt, but we have no way to do this right now.
898 CaseListIsErroneous = true;
903 // Detect duplicate case ranges, which usually don't exist at all in
905 if (!CaseRanges.empty()) {
906 // Sort all the case ranges by their low value so we can easily detect
907 // overlaps between ranges.
908 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
910 // Scan the ranges, computing the high values and removing empty ranges.
911 std::vector<llvm::APSInt> HiVals;
912 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
913 llvm::APSInt &LoVal = CaseRanges[i].first;
914 CaseStmt *CR = CaseRanges[i].second;
915 Expr *Hi = CR->getRHS();
918 if (getLangOpts().CPlusPlus11) {
919 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
920 // constant expression of the promoted type of the switch condition.
922 CheckConvertedConstantExpression(Hi, CondType, HiVal,
924 if (ConvHi.isInvalid()) {
925 CaseListIsErroneous = true;
930 HiVal = Hi->EvaluateKnownConstInt(Context);
932 // If the RHS is not the same type as the condition, insert an
934 Hi = DefaultLvalueConversion(Hi).get();
935 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
938 // Convert the value to the same width/sign as the condition.
939 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
941 diag::warn_case_value_overflow);
945 // If the low value is bigger than the high value, the case is empty.
947 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
948 << SourceRange(CR->getLHS()->getLocStart(),
950 CaseRanges.erase(CaseRanges.begin()+i);
955 if (ShouldCheckConstantCond &&
956 LoVal <= ConstantCondValue &&
957 ConstantCondValue <= HiVal)
958 ShouldCheckConstantCond = false;
960 HiVals.push_back(HiVal);
963 // Rescan the ranges, looking for overlap with singleton values and other
964 // ranges. Since the range list is sorted, we only need to compare case
965 // ranges with their neighbors.
966 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
967 llvm::APSInt &CRLo = CaseRanges[i].first;
968 llvm::APSInt &CRHi = HiVals[i];
969 CaseStmt *CR = CaseRanges[i].second;
971 // Check to see whether the case range overlaps with any
973 CaseStmt *OverlapStmt = nullptr;
974 llvm::APSInt OverlapVal(32);
976 // Find the smallest value >= the lower bound. If I is in the
977 // case range, then we have overlap.
978 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
979 CaseVals.end(), CRLo,
980 CaseCompareFunctor());
981 if (I != CaseVals.end() && I->first < CRHi) {
982 OverlapVal = I->first; // Found overlap with scalar.
983 OverlapStmt = I->second;
986 // Find the smallest value bigger than the upper bound.
987 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
988 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
989 OverlapVal = (I-1)->first; // Found overlap with scalar.
990 OverlapStmt = (I-1)->second;
993 // Check to see if this case stmt overlaps with the subsequent
995 if (i && CRLo <= HiVals[i-1]) {
996 OverlapVal = HiVals[i-1]; // Found overlap with range.
997 OverlapStmt = CaseRanges[i-1].second;
1001 // If we have a duplicate, report it.
1002 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1003 << OverlapVal.toString(10);
1004 Diag(OverlapStmt->getLHS()->getLocStart(),
1005 diag::note_duplicate_case_prev);
1006 // FIXME: We really want to remove the bogus case stmt from the
1007 // substmt, but we have no way to do this right now.
1008 CaseListIsErroneous = true;
1013 // Complain if we have a constant condition and we didn't find a match.
1014 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1015 // TODO: it would be nice if we printed enums as enums, chars as
1017 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1018 << ConstantCondValue.toString(10)
1019 << CondExpr->getSourceRange();
1022 // Check to see if switch is over an Enum and handles all of its
1023 // values. We only issue a warning if there is not 'default:', but
1024 // we still do the analysis to preserve this information in the AST
1025 // (which can be used by flow-based analyes).
1027 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1029 // If switch has default case, then ignore it.
1030 if (!CaseListIsErroneous && !HasConstantCond && ET) {
1031 const EnumDecl *ED = ET->getDecl();
1032 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1034 EnumValsTy EnumVals;
1036 // Gather all enum values, set their type and sort them,
1037 // allowing easier comparison with CaseVals.
1038 for (auto *EDI : ED->enumerators()) {
1039 llvm::APSInt Val = EDI->getInitVal();
1040 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1041 EnumVals.push_back(std::make_pair(Val, EDI));
1043 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1044 EnumValsTy::iterator EIend =
1045 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1047 // See which case values aren't in enum.
1048 EnumValsTy::const_iterator EI = EnumVals.begin();
1049 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1050 CI != CaseVals.end(); CI++) {
1051 while (EI != EIend && EI->first < CI->first)
1053 if (EI == EIend || EI->first > CI->first) {
1054 Expr *CaseExpr = CI->second->getLHS();
1055 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1056 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1057 << CondTypeBeforePromotion;
1060 // See which of case ranges aren't in enum
1061 EI = EnumVals.begin();
1062 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1063 RI != CaseRanges.end() && EI != EIend; RI++) {
1064 while (EI != EIend && EI->first < RI->first)
1067 if (EI == EIend || EI->first != RI->first) {
1068 Expr *CaseExpr = RI->second->getLHS();
1069 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1070 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1071 << CondTypeBeforePromotion;
1075 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1076 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1077 while (EI != EIend && EI->first < Hi)
1079 if (EI == EIend || EI->first != Hi) {
1080 Expr *CaseExpr = RI->second->getRHS();
1081 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1082 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1083 << CondTypeBeforePromotion;
1087 // Check which enum vals aren't in switch
1088 CaseValsTy::const_iterator CI = CaseVals.begin();
1089 CaseRangesTy::const_iterator RI = CaseRanges.begin();
1090 bool hasCasesNotInSwitch = false;
1092 SmallVector<DeclarationName,8> UnhandledNames;
1094 for (EI = EnumVals.begin(); EI != EIend; EI++){
1095 // Drop unneeded case values
1096 while (CI != CaseVals.end() && CI->first < EI->first)
1099 if (CI != CaseVals.end() && CI->first == EI->first)
1102 // Drop unneeded case ranges
1103 for (; RI != CaseRanges.end(); RI++) {
1105 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1106 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1107 if (EI->first <= Hi)
1111 if (RI == CaseRanges.end() || EI->first < RI->first) {
1112 hasCasesNotInSwitch = true;
1113 UnhandledNames.push_back(EI->second->getDeclName());
1117 if (TheDefaultStmt && UnhandledNames.empty())
1118 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1120 // Produce a nice diagnostic if multiple values aren't handled.
1121 switch (UnhandledNames.size()) {
1124 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1125 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1126 << UnhandledNames[0];
1129 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1130 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1131 << UnhandledNames[0] << UnhandledNames[1];
1134 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1135 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1136 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1139 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1140 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1141 << (unsigned)UnhandledNames.size()
1142 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1146 if (!hasCasesNotInSwitch)
1147 SS->setAllEnumCasesCovered();
1152 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1153 diag::warn_empty_switch_body);
1155 // FIXME: If the case list was broken is some way, we don't have a good system
1156 // to patch it up. Instead, just return the whole substmt as broken.
1157 if (CaseListIsErroneous)
1164 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1166 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1169 if (const EnumType *ET = DstType->getAs<EnumType>())
1170 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1171 SrcType->isIntegerType()) {
1172 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1173 SrcExpr->isIntegerConstantExpr(Context)) {
1174 // Get the bitwidth of the enum value before promotions.
1175 unsigned DstWidth = Context.getIntWidth(DstType);
1176 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1178 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1179 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1180 const EnumDecl *ED = ET->getDecl();
1181 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1183 EnumValsTy EnumVals;
1185 // Gather all enum values, set their type and sort them,
1186 // allowing easier comparison with rhs constant.
1187 for (auto *EDI : ED->enumerators()) {
1188 llvm::APSInt Val = EDI->getInitVal();
1189 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1190 EnumVals.push_back(std::make_pair(Val, EDI));
1192 if (EnumVals.empty())
1194 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1195 EnumValsTy::iterator EIend =
1196 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1198 // See which values aren't in the enum.
1199 EnumValsTy::const_iterator EI = EnumVals.begin();
1200 while (EI != EIend && EI->first < RhsVal)
1202 if (EI == EIend || EI->first != RhsVal) {
1203 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1204 << DstType.getUnqualifiedType();
1211 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1212 Decl *CondVar, Stmt *Body) {
1213 ExprResult CondResult(Cond.release());
1215 VarDecl *ConditionVar = nullptr;
1217 ConditionVar = cast<VarDecl>(CondVar);
1218 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1219 if (CondResult.isInvalid())
1222 Expr *ConditionExpr = CondResult.get();
1225 CheckBreakContinueBinding(ConditionExpr);
1227 DiagnoseUnusedExprResult(Body);
1229 if (isa<NullStmt>(Body))
1230 getCurCompoundScope().setHasEmptyLoopBodies();
1232 return new (Context)
1233 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
1237 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1238 SourceLocation WhileLoc, SourceLocation CondLParen,
1239 Expr *Cond, SourceLocation CondRParen) {
1240 assert(Cond && "ActOnDoStmt(): missing expression");
1242 CheckBreakContinueBinding(Cond);
1243 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1244 if (CondResult.isInvalid())
1246 Cond = CondResult.get();
1248 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1249 if (CondResult.isInvalid())
1251 Cond = CondResult.get();
1253 DiagnoseUnusedExprResult(Body);
1255 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1259 // This visitor will traverse a conditional statement and store all
1260 // the evaluated decls into a vector. Simple is set to true if none
1261 // of the excluded constructs are used.
1262 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1263 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1264 SmallVectorImpl<SourceRange> &Ranges;
1267 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1269 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1270 SmallVectorImpl<SourceRange> &Ranges) :
1271 Inherited(S.Context),
1276 bool isSimple() { return Simple; }
1278 // Replaces the method in EvaluatedExprVisitor.
1279 void VisitMemberExpr(MemberExpr* E) {
1283 // Any Stmt not whitelisted will cause the condition to be marked complex.
1284 void VisitStmt(Stmt *S) {
1288 void VisitBinaryOperator(BinaryOperator *E) {
1293 void VisitCastExpr(CastExpr *E) {
1294 Visit(E->getSubExpr());
1297 void VisitUnaryOperator(UnaryOperator *E) {
1298 // Skip checking conditionals with derefernces.
1299 if (E->getOpcode() == UO_Deref)
1302 Visit(E->getSubExpr());
1305 void VisitConditionalOperator(ConditionalOperator *E) {
1306 Visit(E->getCond());
1307 Visit(E->getTrueExpr());
1308 Visit(E->getFalseExpr());
1311 void VisitParenExpr(ParenExpr *E) {
1312 Visit(E->getSubExpr());
1315 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1316 Visit(E->getOpaqueValue()->getSourceExpr());
1317 Visit(E->getFalseExpr());
1320 void VisitIntegerLiteral(IntegerLiteral *E) { }
1321 void VisitFloatingLiteral(FloatingLiteral *E) { }
1322 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1323 void VisitCharacterLiteral(CharacterLiteral *E) { }
1324 void VisitGNUNullExpr(GNUNullExpr *E) { }
1325 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1327 void VisitDeclRefExpr(DeclRefExpr *E) {
1328 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1331 Ranges.push_back(E->getSourceRange());
1336 }; // end class DeclExtractor
1338 // DeclMatcher checks to see if the decls are used in a non-evauluated
1340 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1341 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1345 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1347 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1349 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1350 if (!Statement) return;
1355 void VisitReturnStmt(ReturnStmt *S) {
1359 void VisitBreakStmt(BreakStmt *S) {
1363 void VisitGotoStmt(GotoStmt *S) {
1367 void VisitCastExpr(CastExpr *E) {
1368 if (E->getCastKind() == CK_LValueToRValue)
1369 CheckLValueToRValueCast(E->getSubExpr());
1371 Visit(E->getSubExpr());
1374 void CheckLValueToRValueCast(Expr *E) {
1375 E = E->IgnoreParenImpCasts();
1377 if (isa<DeclRefExpr>(E)) {
1381 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1382 Visit(CO->getCond());
1383 CheckLValueToRValueCast(CO->getTrueExpr());
1384 CheckLValueToRValueCast(CO->getFalseExpr());
1388 if (BinaryConditionalOperator *BCO =
1389 dyn_cast<BinaryConditionalOperator>(E)) {
1390 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1391 CheckLValueToRValueCast(BCO->getFalseExpr());
1398 void VisitDeclRefExpr(DeclRefExpr *E) {
1399 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1400 if (Decls.count(VD))
1404 bool FoundDeclInUse() { return FoundDecl; }
1406 }; // end class DeclMatcher
1408 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1409 Expr *Third, Stmt *Body) {
1410 // Condition is empty
1411 if (!Second) return;
1413 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1414 Second->getLocStart()))
1417 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1418 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1419 SmallVector<SourceRange, 10> Ranges;
1420 DeclExtractor DE(S, Decls, Ranges);
1423 // Don't analyze complex conditionals.
1424 if (!DE.isSimple()) return;
1427 if (Decls.size() == 0) return;
1429 // Don't warn on volatile, static, or global variables.
1430 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1433 if ((*I)->getType().isVolatileQualified() ||
1434 (*I)->hasGlobalStorage()) return;
1436 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1437 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1438 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1441 // Load decl names into diagnostic.
1442 if (Decls.size() > 4)
1445 PDiag << Decls.size();
1446 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1449 PDiag << (*I)->getDeclName();
1452 // Load SourceRanges into diagnostic if there is room.
1453 // Otherwise, load the SourceRange of the conditional expression.
1454 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1455 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1460 PDiag << Second->getSourceRange();
1462 S.Diag(Ranges.begin()->getBegin(), PDiag);
1465 // If Statement is an incemement or decrement, return true and sets the
1466 // variables Increment and DRE.
1467 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1468 DeclRefExpr *&DRE) {
1469 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1470 switch (UO->getOpcode()) {
1471 default: return false;
1481 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1485 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1486 FunctionDecl *FD = Call->getDirectCallee();
1487 if (!FD || !FD->isOverloadedOperator()) return false;
1488 switch (FD->getOverloadedOperator()) {
1489 default: return false;
1497 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1504 // A visitor to determine if a continue or break statement is a
1506 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1507 SourceLocation BreakLoc;
1508 SourceLocation ContinueLoc;
1510 BreakContinueFinder(Sema &S, Stmt* Body) :
1511 Inherited(S.Context) {
1515 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1517 void VisitContinueStmt(ContinueStmt* E) {
1518 ContinueLoc = E->getContinueLoc();
1521 void VisitBreakStmt(BreakStmt* E) {
1522 BreakLoc = E->getBreakLoc();
1525 bool ContinueFound() { return ContinueLoc.isValid(); }
1526 bool BreakFound() { return BreakLoc.isValid(); }
1527 SourceLocation GetContinueLoc() { return ContinueLoc; }
1528 SourceLocation GetBreakLoc() { return BreakLoc; }
1530 }; // end class BreakContinueFinder
1532 // Emit a warning when a loop increment/decrement appears twice per loop
1533 // iteration. The conditions which trigger this warning are:
1534 // 1) The last statement in the loop body and the third expression in the
1535 // for loop are both increment or both decrement of the same variable
1536 // 2) No continue statements in the loop body.
1537 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1538 // Return when there is nothing to check.
1539 if (!Body || !Third) return;
1541 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1542 Third->getLocStart()))
1545 // Get the last statement from the loop body.
1546 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1547 if (!CS || CS->body_empty()) return;
1548 Stmt *LastStmt = CS->body_back();
1549 if (!LastStmt) return;
1551 bool LoopIncrement, LastIncrement;
1552 DeclRefExpr *LoopDRE, *LastDRE;
1554 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1555 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1557 // Check that the two statements are both increments or both decrements
1558 // on the same variable.
1559 if (LoopIncrement != LastIncrement ||
1560 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1562 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1564 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1565 << LastDRE->getDecl() << LastIncrement;
1566 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1573 void Sema::CheckBreakContinueBinding(Expr *E) {
1574 if (!E || getLangOpts().CPlusPlus)
1576 BreakContinueFinder BCFinder(*this, E);
1577 Scope *BreakParent = CurScope->getBreakParent();
1578 if (BCFinder.BreakFound() && BreakParent) {
1579 if (BreakParent->getFlags() & Scope::SwitchScope) {
1580 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1582 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1585 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1586 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1592 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1593 Stmt *First, FullExprArg second, Decl *secondVar,
1595 SourceLocation RParenLoc, Stmt *Body) {
1596 if (!getLangOpts().CPlusPlus) {
1597 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1598 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1599 // declare identifiers for objects having storage class 'auto' or
1601 for (auto *DI : DS->decls()) {
1602 VarDecl *VD = dyn_cast<VarDecl>(DI);
1603 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1606 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1607 DI->setInvalidDecl();
1613 CheckBreakContinueBinding(second.get());
1614 CheckBreakContinueBinding(third.get());
1616 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1617 CheckForRedundantIteration(*this, third.get(), Body);
1619 ExprResult SecondResult(second.release());
1620 VarDecl *ConditionVar = nullptr;
1622 ConditionVar = cast<VarDecl>(secondVar);
1623 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1624 if (SecondResult.isInvalid())
1628 Expr *Third = third.release().getAs<Expr>();
1630 DiagnoseUnusedExprResult(First);
1631 DiagnoseUnusedExprResult(Third);
1632 DiagnoseUnusedExprResult(Body);
1634 if (isa<NullStmt>(Body))
1635 getCurCompoundScope().setHasEmptyLoopBodies();
1637 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1638 Third, Body, ForLoc, LParenLoc, RParenLoc);
1641 /// In an Objective C collection iteration statement:
1643 /// x can be an arbitrary l-value expression. Bind it up as a
1644 /// full-expression.
1645 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1646 // Reduce placeholder expressions here. Note that this rejects the
1647 // use of pseudo-object l-values in this position.
1648 ExprResult result = CheckPlaceholderExpr(E);
1649 if (result.isInvalid()) return StmtError();
1652 ExprResult FullExpr = ActOnFinishFullExpr(E);
1653 if (FullExpr.isInvalid())
1655 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1659 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1663 // Bail out early if we've got a type-dependent expression.
1664 if (collection->isTypeDependent()) return collection;
1666 // Perform normal l-value conversion.
1667 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1668 if (result.isInvalid())
1670 collection = result.get();
1672 // The operand needs to have object-pointer type.
1673 // TODO: should we do a contextual conversion?
1674 const ObjCObjectPointerType *pointerType =
1675 collection->getType()->getAs<ObjCObjectPointerType>();
1677 return Diag(forLoc, diag::err_collection_expr_type)
1678 << collection->getType() << collection->getSourceRange();
1680 // Check that the operand provides
1681 // - countByEnumeratingWithState:objects:count:
1682 const ObjCObjectType *objectType = pointerType->getObjectType();
1683 ObjCInterfaceDecl *iface = objectType->getInterface();
1685 // If we have a forward-declared type, we can't do this check.
1686 // Under ARC, it is an error not to have a forward-declared class.
1688 RequireCompleteType(forLoc, QualType(objectType, 0),
1689 getLangOpts().ObjCAutoRefCount
1690 ? diag::err_arc_collection_forward
1693 // Otherwise, if we have any useful type information, check that
1694 // the type declares the appropriate method.
1695 } else if (iface || !objectType->qual_empty()) {
1696 IdentifierInfo *selectorIdents[] = {
1697 &Context.Idents.get("countByEnumeratingWithState"),
1698 &Context.Idents.get("objects"),
1699 &Context.Idents.get("count")
1701 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1703 ObjCMethodDecl *method = nullptr;
1705 // If there's an interface, look in both the public and private APIs.
1707 method = iface->lookupInstanceMethod(selector);
1708 if (!method) method = iface->lookupPrivateMethod(selector);
1711 // Also check protocol qualifiers.
1713 method = LookupMethodInQualifiedType(selector, pointerType,
1716 // If we didn't find it anywhere, give up.
1718 Diag(forLoc, diag::warn_collection_expr_type)
1719 << collection->getType() << selector << collection->getSourceRange();
1722 // TODO: check for an incompatible signature?
1725 // Wrap up any cleanups in the expression.
1730 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1731 Stmt *First, Expr *collection,
1732 SourceLocation RParenLoc) {
1734 ExprResult CollectionExprResult =
1735 CheckObjCForCollectionOperand(ForLoc, collection);
1739 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1740 if (!DS->isSingleDecl())
1741 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1742 diag::err_toomany_element_decls));
1744 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1745 if (!D || D->isInvalidDecl())
1748 FirstType = D->getType();
1749 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1750 // declare identifiers for objects having storage class 'auto' or
1752 if (!D->hasLocalStorage())
1753 return StmtError(Diag(D->getLocation(),
1754 diag::err_non_local_variable_decl_in_for));
1756 // If the type contained 'auto', deduce the 'auto' to 'id'.
1757 if (FirstType->getContainedAutoType()) {
1758 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1760 Expr *DeducedInit = &OpaqueId;
1761 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1763 DiagnoseAutoDeductionFailure(D, DeducedInit);
1764 if (FirstType.isNull()) {
1765 D->setInvalidDecl();
1769 D->setType(FirstType);
1771 if (ActiveTemplateInstantiations.empty()) {
1772 SourceLocation Loc =
1773 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1774 Diag(Loc, diag::warn_auto_var_is_id)
1775 << D->getDeclName();
1780 Expr *FirstE = cast<Expr>(First);
1781 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1782 return StmtError(Diag(First->getLocStart(),
1783 diag::err_selector_element_not_lvalue)
1784 << First->getSourceRange());
1786 FirstType = static_cast<Expr*>(First)->getType();
1787 if (FirstType.isConstQualified())
1788 Diag(ForLoc, diag::err_selector_element_const_type)
1789 << FirstType << First->getSourceRange();
1791 if (!FirstType->isDependentType() &&
1792 !FirstType->isObjCObjectPointerType() &&
1793 !FirstType->isBlockPointerType())
1794 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1795 << FirstType << First->getSourceRange());
1798 if (CollectionExprResult.isInvalid())
1801 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1802 if (CollectionExprResult.isInvalid())
1805 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1806 nullptr, ForLoc, RParenLoc);
1809 /// Finish building a variable declaration for a for-range statement.
1810 /// \return true if an error occurs.
1811 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1812 SourceLocation Loc, int DiagID) {
1813 // Deduce the type for the iterator variable now rather than leaving it to
1814 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1816 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1817 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1819 SemaRef.Diag(Loc, DiagID) << Init->getType();
1820 if (InitType.isNull()) {
1821 Decl->setInvalidDecl();
1824 Decl->setType(InitType);
1826 // In ARC, infer lifetime.
1827 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1828 // we're doing the equivalent of fast iteration.
1829 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1830 SemaRef.inferObjCARCLifetime(Decl))
1831 Decl->setInvalidDecl();
1833 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1834 /*TypeMayContainAuto=*/false);
1835 SemaRef.FinalizeDeclaration(Decl);
1836 SemaRef.CurContext->addHiddenDecl(Decl);
1842 /// Produce a note indicating which begin/end function was implicitly called
1843 /// by a C++11 for-range statement. This is often not obvious from the code,
1844 /// nor from the diagnostics produced when analysing the implicit expressions
1845 /// required in a for-range statement.
1846 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1847 Sema::BeginEndFunction BEF) {
1848 CallExpr *CE = dyn_cast<CallExpr>(E);
1851 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1854 SourceLocation Loc = D->getLocation();
1856 std::string Description;
1857 bool IsTemplate = false;
1858 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1859 Description = SemaRef.getTemplateArgumentBindingsText(
1860 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1864 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1865 << BEF << IsTemplate << Description << E->getType();
1868 /// Build a variable declaration for a for-range statement.
1869 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1870 QualType Type, const char *Name) {
1871 DeclContext *DC = SemaRef.CurContext;
1872 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1873 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1874 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1876 Decl->setImplicit();
1882 static bool ObjCEnumerationCollection(Expr *Collection) {
1883 return !Collection->isTypeDependent()
1884 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1887 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1889 /// C++11 [stmt.ranged]:
1890 /// A range-based for statement is equivalent to
1893 /// auto && __range = range-init;
1894 /// for ( auto __begin = begin-expr,
1895 /// __end = end-expr;
1896 /// __begin != __end;
1898 /// for-range-declaration = *__begin;
1903 /// The body of the loop is not available yet, since it cannot be analysed until
1904 /// we have determined the type of the for-range-declaration.
1906 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1907 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1908 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1912 if (Range && ObjCEnumerationCollection(Range))
1913 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1915 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1916 assert(DS && "first part of for range not a decl stmt");
1918 if (!DS->isSingleDecl()) {
1919 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1923 Decl *LoopVar = DS->getSingleDecl();
1924 if (LoopVar->isInvalidDecl() || !Range ||
1925 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1926 LoopVar->setInvalidDecl();
1930 // Build auto && __range = range-init
1931 SourceLocation RangeLoc = Range->getLocStart();
1932 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1933 Context.getAutoRRefDeductType(),
1935 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1936 diag::err_for_range_deduction_failure)) {
1937 LoopVar->setInvalidDecl();
1941 // Claim the type doesn't contain auto: we've already done the checking.
1942 DeclGroupPtrTy RangeGroup =
1943 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1944 /*TypeMayContainAuto=*/ false);
1945 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1946 if (RangeDecl.isInvalid()) {
1947 LoopVar->setInvalidDecl();
1951 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1952 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1953 /*Inc=*/nullptr, DS, RParenLoc, Kind);
1956 /// \brief Create the initialization, compare, and increment steps for
1957 /// the range-based for loop expression.
1958 /// This function does not handle array-based for loops,
1959 /// which are created in Sema::BuildCXXForRangeStmt.
1961 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1962 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1963 /// CandidateSet and BEF are set and some non-success value is returned on
1965 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1966 Expr *BeginRange, Expr *EndRange,
1970 SourceLocation ColonLoc,
1971 OverloadCandidateSet *CandidateSet,
1972 ExprResult *BeginExpr,
1973 ExprResult *EndExpr,
1974 Sema::BeginEndFunction *BEF) {
1975 DeclarationNameInfo BeginNameInfo(
1976 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1977 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1980 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1981 Sema::LookupMemberName);
1982 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1984 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1985 // - if _RangeT is a class type, the unqualified-ids begin and end are
1986 // looked up in the scope of class _RangeT as if by class member access
1987 // lookup (3.4.5), and if either (or both) finds at least one
1988 // declaration, begin-expr and end-expr are __range.begin() and
1989 // __range.end(), respectively;
1990 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1991 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1993 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1994 SourceLocation RangeLoc = BeginVar->getLocation();
1995 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1997 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1998 << RangeLoc << BeginRange->getType() << *BEF;
1999 return Sema::FRS_DiagnosticIssued;
2002 // - otherwise, begin-expr and end-expr are begin(__range) and
2003 // end(__range), respectively, where begin and end are looked up with
2004 // argument-dependent lookup (3.4.2). For the purposes of this name
2005 // lookup, namespace std is an associated namespace.
2009 *BEF = Sema::BEF_begin;
2010 Sema::ForRangeStatus RangeStatus =
2011 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2012 Sema::BEF_begin, BeginNameInfo,
2013 BeginMemberLookup, CandidateSet,
2014 BeginRange, BeginExpr);
2016 if (RangeStatus != Sema::FRS_Success)
2018 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2019 diag::err_for_range_iter_deduction_failure)) {
2020 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2021 return Sema::FRS_DiagnosticIssued;
2024 *BEF = Sema::BEF_end;
2026 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2027 Sema::BEF_end, EndNameInfo,
2028 EndMemberLookup, CandidateSet,
2030 if (RangeStatus != Sema::FRS_Success)
2032 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2033 diag::err_for_range_iter_deduction_failure)) {
2034 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2035 return Sema::FRS_DiagnosticIssued;
2037 return Sema::FRS_Success;
2040 /// Speculatively attempt to dereference an invalid range expression.
2041 /// If the attempt fails, this function will return a valid, null StmtResult
2042 /// and emit no diagnostics.
2043 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2044 SourceLocation ForLoc,
2046 SourceLocation ColonLoc,
2048 SourceLocation RangeLoc,
2049 SourceLocation RParenLoc) {
2050 // Determine whether we can rebuild the for-range statement with a
2051 // dereferenced range expression.
2052 ExprResult AdjustedRange;
2054 Sema::SFINAETrap Trap(SemaRef);
2056 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2057 if (AdjustedRange.isInvalid())
2058 return StmtResult();
2061 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2062 AdjustedRange.get(), RParenLoc,
2065 return StmtResult();
2068 // The attempt to dereference worked well enough that it could produce a valid
2069 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2070 // case there are any other (non-fatal) problems with it.
2071 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2072 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2073 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2074 AdjustedRange.get(), RParenLoc,
2075 Sema::BFRK_Rebuild);
2079 /// RAII object to automatically invalidate a declaration if an error occurs.
2080 struct InvalidateOnErrorScope {
2081 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2082 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2083 ~InvalidateOnErrorScope() {
2084 if (Enabled && Trap.hasErrorOccurred())
2085 D->setInvalidDecl();
2088 DiagnosticErrorTrap Trap;
2094 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2096 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2097 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2098 Expr *Inc, Stmt *LoopVarDecl,
2099 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2100 Scope *S = getCurScope();
2102 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2103 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2104 QualType RangeVarType = RangeVar->getType();
2106 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2107 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2109 // If we hit any errors, mark the loop variable as invalid if its type
2111 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2112 LoopVar->getType()->isUndeducedType());
2114 StmtResult BeginEndDecl = BeginEnd;
2115 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2117 if (RangeVarType->isDependentType()) {
2118 // The range is implicitly used as a placeholder when it is dependent.
2119 RangeVar->markUsed(Context);
2121 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2122 // them in properly when we instantiate the loop.
2123 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2124 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2125 } else if (!BeginEndDecl.get()) {
2126 SourceLocation RangeLoc = RangeVar->getLocation();
2128 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2130 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2131 VK_LValue, ColonLoc);
2132 if (BeginRangeRef.isInvalid())
2135 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2136 VK_LValue, ColonLoc);
2137 if (EndRangeRef.isInvalid())
2140 QualType AutoType = Context.getAutoDeductType();
2141 Expr *Range = RangeVar->getInit();
2144 QualType RangeType = Range->getType();
2146 if (RequireCompleteType(RangeLoc, RangeType,
2147 diag::err_for_range_incomplete_type))
2150 // Build auto __begin = begin-expr, __end = end-expr.
2151 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2153 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2156 // Build begin-expr and end-expr and attach to __begin and __end variables.
2157 ExprResult BeginExpr, EndExpr;
2158 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2159 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2160 // __range + __bound, respectively, where __bound is the array bound. If
2161 // _RangeT is an array of unknown size or an array of incomplete type,
2162 // the program is ill-formed;
2164 // begin-expr is __range.
2165 BeginExpr = BeginRangeRef;
2166 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2167 diag::err_for_range_iter_deduction_failure)) {
2168 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2172 // Find the array bound.
2173 ExprResult BoundExpr;
2174 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2175 BoundExpr = IntegerLiteral::Create(
2176 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2177 else if (const VariableArrayType *VAT =
2178 dyn_cast<VariableArrayType>(UnqAT))
2179 BoundExpr = VAT->getSizeExpr();
2181 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2182 // UnqAT is not incomplete and Range is not type-dependent.
2183 llvm_unreachable("Unexpected array type in for-range");
2186 // end-expr is __range + __bound.
2187 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2189 if (EndExpr.isInvalid())
2191 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2192 diag::err_for_range_iter_deduction_failure)) {
2193 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2197 OverloadCandidateSet CandidateSet(RangeLoc,
2198 OverloadCandidateSet::CSK_Normal);
2199 Sema::BeginEndFunction BEFFailure;
2200 ForRangeStatus RangeStatus =
2201 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2202 EndRangeRef.get(), RangeType,
2203 BeginVar, EndVar, ColonLoc, &CandidateSet,
2204 &BeginExpr, &EndExpr, &BEFFailure);
2206 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2207 BEFFailure == BEF_begin) {
2208 // If the range is being built from an array parameter, emit a
2209 // a diagnostic that it is being treated as a pointer.
2210 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2211 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2212 QualType ArrayTy = PVD->getOriginalType();
2213 QualType PointerTy = PVD->getType();
2214 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2215 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2216 << RangeLoc << PVD << ArrayTy << PointerTy;
2217 Diag(PVD->getLocation(), diag::note_declared_at);
2223 // If building the range failed, try dereferencing the range expression
2224 // unless a diagnostic was issued or the end function is problematic.
2225 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2226 LoopVarDecl, ColonLoc,
2229 if (SR.isInvalid() || SR.isUsable())
2233 // Otherwise, emit diagnostics if we haven't already.
2234 if (RangeStatus == FRS_NoViableFunction) {
2235 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2236 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2237 << RangeLoc << Range->getType() << BEFFailure;
2238 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2240 // Return an error if no fix was discovered.
2241 if (RangeStatus != FRS_Success)
2245 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2246 "invalid range expression in for loop");
2248 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2249 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2250 if (!Context.hasSameType(BeginType, EndType)) {
2251 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2252 << BeginType << EndType;
2253 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2254 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2257 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2258 // Claim the type doesn't contain auto: we've already done the checking.
2259 DeclGroupPtrTy BeginEndGroup =
2260 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
2261 /*TypeMayContainAuto=*/ false);
2262 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2264 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2265 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2266 VK_LValue, ColonLoc);
2267 if (BeginRef.isInvalid())
2270 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2271 VK_LValue, ColonLoc);
2272 if (EndRef.isInvalid())
2275 // Build and check __begin != __end expression.
2276 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2277 BeginRef.get(), EndRef.get());
2278 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2279 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2280 if (NotEqExpr.isInvalid()) {
2281 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2282 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2283 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2284 if (!Context.hasSameType(BeginType, EndType))
2285 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2289 // Build and check ++__begin expression.
2290 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2291 VK_LValue, ColonLoc);
2292 if (BeginRef.isInvalid())
2295 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2296 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2297 if (IncrExpr.isInvalid()) {
2298 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2299 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2300 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2304 // Build and check *__begin expression.
2305 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2306 VK_LValue, ColonLoc);
2307 if (BeginRef.isInvalid())
2310 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2311 if (DerefExpr.isInvalid()) {
2312 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2313 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2314 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2318 // Attach *__begin as initializer for VD. Don't touch it if we're just
2319 // trying to determine whether this would be a valid range.
2320 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2321 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2322 /*TypeMayContainAuto=*/true);
2323 if (LoopVar->isInvalidDecl())
2324 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2328 // Don't bother to actually allocate the result if we're just trying to
2329 // determine whether it would be valid.
2330 if (Kind == BFRK_Check)
2331 return StmtResult();
2333 return new (Context) CXXForRangeStmt(
2334 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2335 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
2338 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2340 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2343 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2345 ForStmt->setBody(B);
2349 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2350 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2351 /// body cannot be performed until after the type of the range variable is
2353 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2357 if (isa<ObjCForCollectionStmt>(S))
2358 return FinishObjCForCollectionStmt(S, B);
2360 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2361 ForStmt->setBody(B);
2363 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2364 diag::warn_empty_range_based_for_body);
2369 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2370 SourceLocation LabelLoc,
2371 LabelDecl *TheDecl) {
2372 getCurFunction()->setHasBranchIntoScope();
2373 TheDecl->markUsed(Context);
2374 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2378 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2380 // Convert operand to void*
2381 if (!E->isTypeDependent()) {
2382 QualType ETy = E->getType();
2383 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2384 ExprResult ExprRes = E;
2385 AssignConvertType ConvTy =
2386 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2387 if (ExprRes.isInvalid())
2390 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2394 ExprResult ExprRes = ActOnFinishFullExpr(E);
2395 if (ExprRes.isInvalid())
2399 getCurFunction()->setHasIndirectGoto();
2401 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2405 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2406 Scope *S = CurScope->getContinueParent();
2408 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2409 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2412 return new (Context) ContinueStmt(ContinueLoc);
2416 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2417 Scope *S = CurScope->getBreakParent();
2419 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2420 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2422 if (S->isOpenMPLoopScope())
2423 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2426 return new (Context) BreakStmt(BreakLoc);
2429 /// \brief Determine whether the given expression is a candidate for
2430 /// copy elision in either a return statement or a throw expression.
2432 /// \param ReturnType If we're determining the copy elision candidate for
2433 /// a return statement, this is the return type of the function. If we're
2434 /// determining the copy elision candidate for a throw expression, this will
2437 /// \param E The expression being returned from the function or block, or
2440 /// \param AllowFunctionParameter Whether we allow function parameters to
2441 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2442 /// we re-use this logic to determine whether we should try to move as part of
2443 /// a return or throw (which does allow function parameters).
2445 /// \returns The NRVO candidate variable, if the return statement may use the
2446 /// NRVO, or NULL if there is no such candidate.
2447 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2449 bool AllowFunctionParameter) {
2450 if (!getLangOpts().CPlusPlus)
2453 // - in a return statement in a function [where] ...
2454 // ... the expression is the name of a non-volatile automatic object ...
2455 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2456 if (!DR || DR->refersToEnclosingLocal())
2458 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2462 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2467 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2468 bool AllowFunctionParameter) {
2469 QualType VDType = VD->getType();
2470 // - in a return statement in a function with ...
2471 // ... a class return type ...
2472 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2473 if (!ReturnType->isRecordType())
2475 // ... the same cv-unqualified type as the function return type ...
2476 if (!VDType->isDependentType() &&
2477 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2481 // ...object (other than a function or catch-clause parameter)...
2482 if (VD->getKind() != Decl::Var &&
2483 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2485 if (VD->isExceptionVariable()) return false;
2488 if (!VD->hasLocalStorage()) return false;
2490 // ...non-volatile...
2491 if (VD->getType().isVolatileQualified()) return false;
2493 // __block variables can't be allocated in a way that permits NRVO.
2494 if (VD->hasAttr<BlocksAttr>()) return false;
2496 // Variables with higher required alignment than their type's ABI
2497 // alignment cannot use NRVO.
2498 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2499 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2505 /// \brief Perform the initialization of a potentially-movable value, which
2506 /// is the result of return value.
2508 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2509 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2510 /// then falls back to treating them as lvalues if that failed.
2512 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2513 const VarDecl *NRVOCandidate,
2514 QualType ResultType,
2517 // C++0x [class.copy]p33:
2518 // When the criteria for elision of a copy operation are met or would
2519 // be met save for the fact that the source object is a function
2520 // parameter, and the object to be copied is designated by an lvalue,
2521 // overload resolution to select the constructor for the copy is first
2522 // performed as if the object were designated by an rvalue.
2523 ExprResult Res = ExprError();
2525 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2526 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2527 Value->getType(), CK_NoOp, Value, VK_XValue);
2529 Expr *InitExpr = &AsRvalue;
2530 InitializationKind Kind
2531 = InitializationKind::CreateCopy(Value->getLocStart(),
2532 Value->getLocStart());
2533 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2535 // [...] If overload resolution fails, or if the type of the first
2536 // parameter of the selected constructor is not an rvalue reference
2537 // to the object's type (possibly cv-qualified), overload resolution
2538 // is performed again, considering the object as an lvalue.
2540 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2541 StepEnd = Seq.step_end();
2542 Step != StepEnd; ++Step) {
2543 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2546 CXXConstructorDecl *Constructor
2547 = cast<CXXConstructorDecl>(Step->Function.Function);
2549 const RValueReferenceType *RRefType
2550 = Constructor->getParamDecl(0)->getType()
2551 ->getAs<RValueReferenceType>();
2553 // If we don't meet the criteria, break out now.
2555 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2556 Context.getTypeDeclType(Constructor->getParent())))
2559 // Promote "AsRvalue" to the heap, since we now need this
2560 // expression node to persist.
2561 Value = ImplicitCastExpr::Create(Context, Value->getType(),
2562 CK_NoOp, Value, nullptr, VK_XValue);
2564 // Complete type-checking the initialization of the return type
2565 // using the constructor we found.
2566 Res = Seq.Perform(*this, Entity, Kind, Value);
2571 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2572 // above, or overload resolution failed. Either way, we need to try
2573 // (again) now with the return value expression as written.
2574 if (Res.isInvalid())
2575 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2580 /// \brief Determine whether the declared return type of the specified function
2581 /// contains 'auto'.
2582 static bool hasDeducedReturnType(FunctionDecl *FD) {
2583 const FunctionProtoType *FPT =
2584 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2585 return FPT->getReturnType()->isUndeducedType();
2588 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2589 /// for capturing scopes.
2592 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2593 // If this is the first return we've seen, infer the return type.
2594 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2595 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2596 QualType FnRetType = CurCap->ReturnType;
2597 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2599 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2600 // In C++1y, the return type may involve 'auto'.
2601 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2602 FunctionDecl *FD = CurLambda->CallOperator;
2603 if (CurCap->ReturnType.isNull())
2604 CurCap->ReturnType = FD->getReturnType();
2606 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2607 assert(AT && "lost auto type from lambda return type");
2608 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2609 FD->setInvalidDecl();
2612 CurCap->ReturnType = FnRetType = FD->getReturnType();
2613 } else if (CurCap->HasImplicitReturnType) {
2614 // For blocks/lambdas with implicit return types, we check each return
2615 // statement individually, and deduce the common return type when the block
2616 // or lambda is completed.
2617 // FIXME: Fold this into the 'auto' codepath above.
2618 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2619 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2620 if (Result.isInvalid())
2622 RetValExp = Result.get();
2624 if (!CurContext->isDependentContext())
2625 FnRetType = RetValExp->getType();
2627 FnRetType = CurCap->ReturnType = Context.DependentTy;
2630 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2631 // initializer list, because it is not an expression (even
2632 // though we represent it as one). We still deduce 'void'.
2633 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2634 << RetValExp->getSourceRange();
2637 FnRetType = Context.VoidTy;
2640 // Although we'll properly infer the type of the block once it's completed,
2641 // make sure we provide a return type now for better error recovery.
2642 if (CurCap->ReturnType.isNull())
2643 CurCap->ReturnType = FnRetType;
2645 assert(!FnRetType.isNull());
2647 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2648 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2649 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2652 } else if (CapturedRegionScopeInfo *CurRegion =
2653 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2654 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2657 assert(CurLambda && "unknown kind of captured scope");
2658 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2659 ->getNoReturnAttr()) {
2660 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2665 // Otherwise, verify that this result type matches the previous one. We are
2666 // pickier with blocks than for normal functions because we don't have GCC
2667 // compatibility to worry about here.
2668 const VarDecl *NRVOCandidate = nullptr;
2669 if (FnRetType->isDependentType()) {
2670 // Delay processing for now. TODO: there are lots of dependent
2671 // types we can conclusively prove aren't void.
2672 } else if (FnRetType->isVoidType()) {
2673 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2674 !(getLangOpts().CPlusPlus &&
2675 (RetValExp->isTypeDependent() ||
2676 RetValExp->getType()->isVoidType()))) {
2677 if (!getLangOpts().CPlusPlus &&
2678 RetValExp->getType()->isVoidType())
2679 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2681 Diag(ReturnLoc, diag::err_return_block_has_expr);
2682 RetValExp = nullptr;
2685 } else if (!RetValExp) {
2686 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2687 } else if (!RetValExp->isTypeDependent()) {
2688 // we have a non-void block with an expression, continue checking
2690 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2691 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2694 // In C++ the return statement is handled via a copy initialization.
2695 // the C version of which boils down to CheckSingleAssignmentConstraints.
2696 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2697 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2699 NRVOCandidate != nullptr);
2700 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2701 FnRetType, RetValExp);
2702 if (Res.isInvalid()) {
2703 // FIXME: Cleanup temporaries here, anyway?
2706 RetValExp = Res.get();
2707 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2709 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2713 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2716 RetValExp = ER.get();
2718 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2721 // If we need to check for the named return value optimization,
2722 // or if we need to infer the return type,
2723 // save the return statement in our scope for later processing.
2724 if (CurCap->HasImplicitReturnType || NRVOCandidate)
2725 FunctionScopes.back()->Returns.push_back(Result);
2730 /// Deduce the return type for a function from a returned expression, per
2731 /// C++1y [dcl.spec.auto]p6.
2732 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2733 SourceLocation ReturnLoc,
2736 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2737 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
2740 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2741 // If the deduction is for a return statement and the initializer is
2742 // a braced-init-list, the program is ill-formed.
2743 Diag(RetExpr->getExprLoc(),
2744 getCurLambda() ? diag::err_lambda_return_init_list
2745 : diag::err_auto_fn_return_init_list)
2746 << RetExpr->getSourceRange();
2750 if (FD->isDependentContext()) {
2751 // C++1y [dcl.spec.auto]p12:
2752 // Return type deduction [...] occurs when the definition is
2753 // instantiated even if the function body contains a return
2754 // statement with a non-type-dependent operand.
2755 assert(AT->isDeduced() && "should have deduced to dependent type");
2757 } else if (RetExpr) {
2758 // If the deduction is for a return statement and the initializer is
2759 // a braced-init-list, the program is ill-formed.
2760 if (isa<InitListExpr>(RetExpr)) {
2761 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2765 // Otherwise, [...] deduce a value for U using the rules of template
2766 // argument deduction.
2767 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2769 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2770 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2771 << OrigResultType.getType() << RetExpr->getType();
2773 if (DAR != DAR_Succeeded)
2776 // In the case of a return with no operand, the initializer is considered
2779 // Deduction here can only succeed if the return type is exactly 'cv auto'
2780 // or 'decltype(auto)', so just check for that case directly.
2781 if (!OrigResultType.getType()->getAs<AutoType>()) {
2782 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2783 << OrigResultType.getType();
2786 // We always deduce U = void in this case.
2787 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2788 if (Deduced.isNull())
2792 // If a function with a declared return type that contains a placeholder type
2793 // has multiple return statements, the return type is deduced for each return
2794 // statement. [...] if the type deduced is not the same in each deduction,
2795 // the program is ill-formed.
2796 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2797 AutoType *NewAT = Deduced->getContainedAutoType();
2798 if (!FD->isDependentContext() &&
2799 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2800 const LambdaScopeInfo *LambdaSI = getCurLambda();
2801 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2802 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2803 << NewAT->getDeducedType() << AT->getDeducedType()
2804 << true /*IsLambda*/;
2806 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2807 << (AT->isDecltypeAuto() ? 1 : 0)
2808 << NewAT->getDeducedType() << AT->getDeducedType();
2812 } else if (!FD->isInvalidDecl()) {
2813 // Update all declarations of the function to have the deduced return type.
2814 Context.adjustDeducedFunctionResultType(FD, Deduced);
2821 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2823 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2824 if (R.isInvalid()) {
2829 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2830 CurScope->addNRVOCandidate(VD);
2832 CurScope->setNoNRVO();
2838 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2839 // Check for unexpanded parameter packs.
2840 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2843 if (isa<CapturingScopeInfo>(getCurFunction()))
2844 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2847 QualType RelatedRetType;
2848 const AttrVec *Attrs = nullptr;
2849 bool isObjCMethod = false;
2851 if (const FunctionDecl *FD = getCurFunctionDecl()) {
2852 FnRetType = FD->getReturnType();
2854 Attrs = &FD->getAttrs();
2855 if (FD->isNoReturn())
2856 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2857 << FD->getDeclName();
2858 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2859 FnRetType = MD->getReturnType();
2860 isObjCMethod = true;
2862 Attrs = &MD->getAttrs();
2863 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2864 // In the implementation of a method with a related return type, the
2865 // type used to type-check the validity of return statements within the
2866 // method body is a pointer to the type of the class being implemented.
2867 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2868 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2870 } else // If we don't have a function/method context, bail.
2873 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2875 if (getLangOpts().CPlusPlus1y) {
2876 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2877 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2878 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2879 FD->setInvalidDecl();
2882 FnRetType = FD->getReturnType();
2887 bool HasDependentReturnType = FnRetType->isDependentType();
2889 ReturnStmt *Result = nullptr;
2890 if (FnRetType->isVoidType()) {
2892 if (isa<InitListExpr>(RetValExp)) {
2893 // We simply never allow init lists as the return value of void
2894 // functions. This is compatible because this was never allowed before,
2895 // so there's no legacy code to deal with.
2896 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2897 int FunctionKind = 0;
2898 if (isa<ObjCMethodDecl>(CurDecl))
2900 else if (isa<CXXConstructorDecl>(CurDecl))
2902 else if (isa<CXXDestructorDecl>(CurDecl))
2905 Diag(ReturnLoc, diag::err_return_init_list)
2906 << CurDecl->getDeclName() << FunctionKind
2907 << RetValExp->getSourceRange();
2909 // Drop the expression.
2910 RetValExp = nullptr;
2911 } else if (!RetValExp->isTypeDependent()) {
2912 // C99 6.8.6.4p1 (ext_ since GCC warns)
2913 unsigned D = diag::ext_return_has_expr;
2914 if (RetValExp->getType()->isVoidType()) {
2915 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2916 if (isa<CXXConstructorDecl>(CurDecl) ||
2917 isa<CXXDestructorDecl>(CurDecl))
2918 D = diag::err_ctor_dtor_returns_void;
2920 D = diag::ext_return_has_void_expr;
2923 ExprResult Result = RetValExp;
2924 Result = IgnoredValueConversions(Result.get());
2925 if (Result.isInvalid())
2927 RetValExp = Result.get();
2928 RetValExp = ImpCastExprToType(RetValExp,
2929 Context.VoidTy, CK_ToVoid).get();
2931 // return of void in constructor/destructor is illegal in C++.
2932 if (D == diag::err_ctor_dtor_returns_void) {
2933 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2935 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2936 << RetValExp->getSourceRange();
2938 // return (some void expression); is legal in C++.
2939 else if (D != diag::ext_return_has_void_expr ||
2940 !getLangOpts().CPlusPlus) {
2941 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2943 int FunctionKind = 0;
2944 if (isa<ObjCMethodDecl>(CurDecl))
2946 else if (isa<CXXConstructorDecl>(CurDecl))
2948 else if (isa<CXXDestructorDecl>(CurDecl))
2952 << CurDecl->getDeclName() << FunctionKind
2953 << RetValExp->getSourceRange();
2958 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2961 RetValExp = ER.get();
2965 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2966 } else if (!RetValExp && !HasDependentReturnType) {
2967 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2968 // C99 6.8.6.4p1 (ext_ since GCC warns)
2969 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2971 if (FunctionDecl *FD = getCurFunctionDecl())
2972 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2974 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2975 Result = new (Context) ReturnStmt(ReturnLoc);
2977 assert(RetValExp || HasDependentReturnType);
2978 const VarDecl *NRVOCandidate = nullptr;
2980 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
2982 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2983 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2986 // In C++ the return statement is handled via a copy initialization,
2987 // the C version of which boils down to CheckSingleAssignmentConstraints.
2989 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2990 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
2991 // we have a non-void function with an expression, continue checking
2992 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2994 NRVOCandidate != nullptr);
2995 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2996 RetType, RetValExp);
2997 if (Res.isInvalid()) {
2998 // FIXME: Clean up temporaries here anyway?
3001 RetValExp = Res.getAs<Expr>();
3003 // If we have a related result type, we need to implicitly
3004 // convert back to the formal result type. We can't pretend to
3005 // initialize the result again --- we might end double-retaining
3006 // --- so instead we initialize a notional temporary.
3007 if (!RelatedRetType.isNull()) {
3008 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3010 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3011 if (Res.isInvalid()) {
3012 // FIXME: Clean up temporaries here anyway?
3015 RetValExp = Res.getAs<Expr>();
3018 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3019 getCurFunctionDecl());
3023 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3026 RetValExp = ER.get();
3028 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3031 // If we need to check for the named return value optimization, save the
3032 // return statement in our scope for later processing.
3033 if (Result->getNRVOCandidate())
3034 FunctionScopes.back()->Returns.push_back(Result);
3040 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3041 SourceLocation RParen, Decl *Parm,
3043 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3044 if (Var && Var->isInvalidDecl())
3047 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3051 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3052 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3056 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3057 MultiStmtArg CatchStmts, Stmt *Finally) {
3058 if (!getLangOpts().ObjCExceptions)
3059 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3061 getCurFunction()->setHasBranchProtectedScope();
3062 unsigned NumCatchStmts = CatchStmts.size();
3063 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3064 NumCatchStmts, Finally);
3067 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3069 ExprResult Result = DefaultLvalueConversion(Throw);
3070 if (Result.isInvalid())
3073 Result = ActOnFinishFullExpr(Result.get());
3074 if (Result.isInvalid())
3076 Throw = Result.get();
3078 QualType ThrowType = Throw->getType();
3079 // Make sure the expression type is an ObjC pointer or "void *".
3080 if (!ThrowType->isDependentType() &&
3081 !ThrowType->isObjCObjectPointerType()) {
3082 const PointerType *PT = ThrowType->getAs<PointerType>();
3083 if (!PT || !PT->getPointeeType()->isVoidType())
3084 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3085 << Throw->getType() << Throw->getSourceRange());
3089 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3093 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3095 if (!getLangOpts().ObjCExceptions)
3096 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3099 // @throw without an expression designates a rethrow (which much occur
3100 // in the context of an @catch clause).
3101 Scope *AtCatchParent = CurScope;
3102 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3103 AtCatchParent = AtCatchParent->getParent();
3105 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3107 return BuildObjCAtThrowStmt(AtLoc, Throw);
3111 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3112 ExprResult result = DefaultLvalueConversion(operand);
3113 if (result.isInvalid())
3115 operand = result.get();
3117 // Make sure the expression type is an ObjC pointer or "void *".
3118 QualType type = operand->getType();
3119 if (!type->isDependentType() &&
3120 !type->isObjCObjectPointerType()) {
3121 const PointerType *pointerType = type->getAs<PointerType>();
3122 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3123 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3124 << type << operand->getSourceRange();
3127 // The operand to @synchronized is a full-expression.
3128 return ActOnFinishFullExpr(operand);
3132 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3134 // We can't jump into or indirect-jump out of a @synchronized block.
3135 getCurFunction()->setHasBranchProtectedScope();
3136 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3139 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3140 /// and creates a proper catch handler from them.
3142 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3143 Stmt *HandlerBlock) {
3144 // There's nothing to test that ActOnExceptionDecl didn't already test.
3145 return new (Context)
3146 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3150 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3151 getCurFunction()->setHasBranchProtectedScope();
3152 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3157 class TypeWithHandler {
3161 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3162 : t(type), stmt(statement) {}
3164 // An arbitrary order is fine as long as it places identical
3165 // types next to each other.
3166 bool operator<(const TypeWithHandler &y) const {
3167 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3169 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3172 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3175 bool operator==(const TypeWithHandler& other) const {
3176 return t == other.t;
3179 CXXCatchStmt *getCatchStmt() const { return stmt; }
3180 SourceLocation getTypeSpecStartLoc() const {
3181 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3187 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3188 /// handlers and creates a try statement from them.
3189 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3190 ArrayRef<Stmt *> Handlers) {
3191 // Don't report an error if 'try' is used in system headers.
3192 if (!getLangOpts().CXXExceptions &&
3193 !getSourceManager().isInSystemHeader(TryLoc))
3194 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3196 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3197 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3199 const unsigned NumHandlers = Handlers.size();
3200 assert(NumHandlers > 0 &&
3201 "The parser shouldn't call this if there are no handlers.");
3203 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3205 for (unsigned i = 0; i < NumHandlers; ++i) {
3206 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3207 if (!Handler->getExceptionDecl()) {
3208 if (i < NumHandlers - 1)
3209 return StmtError(Diag(Handler->getLocStart(),
3210 diag::err_early_catch_all));
3215 const QualType CaughtType = Handler->getCaughtType();
3216 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3217 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3220 // Detect handlers for the same type as an earlier one.
3221 if (NumHandlers > 1) {
3222 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3224 TypeWithHandler prev = TypesWithHandlers[0];
3225 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3226 TypeWithHandler curr = TypesWithHandlers[i];
3229 Diag(curr.getTypeSpecStartLoc(),
3230 diag::warn_exception_caught_by_earlier_handler)
3231 << curr.getCatchStmt()->getCaughtType().getAsString();
3232 Diag(prev.getTypeSpecStartLoc(),
3233 diag::note_previous_exception_handler)
3234 << prev.getCatchStmt()->getCaughtType().getAsString();
3241 getCurFunction()->setHasBranchProtectedScope();
3243 // FIXME: We should detect handlers that cannot catch anything because an
3244 // earlier handler catches a superclass. Need to find a method that is not
3245 // quadratic for this.
3246 // Neither of these are explicitly forbidden, but every compiler detects them
3249 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3252 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3253 Stmt *TryBlock, Stmt *Handler,
3254 int HandlerIndex, int HandlerParentIndex) {
3255 assert(TryBlock && Handler);
3257 getCurFunction()->setHasBranchProtectedScope();
3259 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler,
3260 HandlerIndex, HandlerParentIndex);
3264 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3267 assert(FilterExpr && Block);
3269 if(!FilterExpr->getType()->isIntegerType()) {
3270 return StmtError(Diag(FilterExpr->getExprLoc(),
3271 diag::err_filter_expression_integral)
3272 << FilterExpr->getType());
3275 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3279 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3282 return SEHFinallyStmt::Create(Context,Loc,Block);
3286 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3287 Scope *SEHTryParent = CurScope;
3288 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3289 SEHTryParent = SEHTryParent->getParent();
3291 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3293 return new (Context) SEHLeaveStmt(Loc);
3296 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3298 NestedNameSpecifierLoc QualifierLoc,
3299 DeclarationNameInfo NameInfo,
3302 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3303 QualifierLoc, NameInfo,
3304 cast<CompoundStmt>(Nested));
3308 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3311 UnqualifiedId &Name,
3313 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3314 SS.getWithLocInContext(Context),
3315 GetNameFromUnqualifiedId(Name),
3320 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3321 unsigned NumParams) {
3322 DeclContext *DC = CurContext;
3323 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3324 DC = DC->getParent();
3326 RecordDecl *RD = nullptr;
3327 if (getLangOpts().CPlusPlus)
3328 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3331 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3335 RD->startDefinition();
3337 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3338 CD = CapturedDecl::Create(Context, CurContext, NumParams);
3343 static void buildCapturedStmtCaptureList(
3344 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3345 SmallVectorImpl<Expr *> &CaptureInits,
3346 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3348 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3349 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3351 if (Cap->isThisCapture()) {
3352 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3353 CapturedStmt::VCK_This));
3354 CaptureInits.push_back(Cap->getInitExpr());
3358 assert(Cap->isReferenceCapture() &&
3359 "non-reference capture not yet implemented");
3361 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3362 CapturedStmt::VCK_ByRef,
3363 Cap->getVariable()));
3364 CaptureInits.push_back(Cap->getInitExpr());
3368 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3369 CapturedRegionKind Kind,
3370 unsigned NumParams) {
3371 CapturedDecl *CD = nullptr;
3372 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3374 // Build the context parameter
3375 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3376 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3377 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3378 ImplicitParamDecl *Param
3379 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3382 CD->setContextParam(0, Param);
3384 // Enter the capturing scope for this captured region.
3385 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3388 PushDeclContext(CurScope, CD);
3392 PushExpressionEvaluationContext(PotentiallyEvaluated);
3395 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3396 CapturedRegionKind Kind,
3397 ArrayRef<CapturedParamNameType> Params) {
3398 CapturedDecl *CD = nullptr;
3399 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3401 // Build the context parameter
3402 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3403 bool ContextIsFound = false;
3404 unsigned ParamNum = 0;
3405 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3407 I != E; ++I, ++ParamNum) {
3408 if (I->second.isNull()) {
3409 assert(!ContextIsFound &&
3410 "null type has been found already for '__context' parameter");
3411 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3412 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3413 ImplicitParamDecl *Param
3414 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3416 CD->setContextParam(ParamNum, Param);
3417 ContextIsFound = true;
3419 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3420 ImplicitParamDecl *Param
3421 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3423 CD->setParam(ParamNum, Param);
3426 assert(ContextIsFound && "no null type for '__context' parameter");
3427 if (!ContextIsFound) {
3428 // Add __context implicitly if it is not specified.
3429 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3430 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3431 ImplicitParamDecl *Param =
3432 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3434 CD->setContextParam(ParamNum, Param);
3436 // Enter the capturing scope for this captured region.
3437 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3440 PushDeclContext(CurScope, CD);
3444 PushExpressionEvaluationContext(PotentiallyEvaluated);
3447 void Sema::ActOnCapturedRegionError() {
3448 DiscardCleanupsInEvaluationContext();
3449 PopExpressionEvaluationContext();
3451 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3452 RecordDecl *Record = RSI->TheRecordDecl;
3453 Record->setInvalidDecl();
3455 SmallVector<Decl*, 4> Fields(Record->fields());
3456 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3457 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3460 PopFunctionScopeInfo();
3463 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3464 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3466 SmallVector<CapturedStmt::Capture, 4> Captures;
3467 SmallVector<Expr *, 4> CaptureInits;
3468 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3470 CapturedDecl *CD = RSI->TheCapturedDecl;
3471 RecordDecl *RD = RSI->TheRecordDecl;
3473 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3474 RSI->CapRegionKind, Captures,
3475 CaptureInits, CD, RD);
3477 CD->setBody(Res->getCapturedStmt());
3478 RD->completeDefinition();
3480 DiscardCleanupsInEvaluationContext();
3481 PopExpressionEvaluationContext();
3484 PopFunctionScopeInfo();