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/RecursiveASTVisitor.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/AST/StmtObjC.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 using namespace clang;
39 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
48 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
52 // Same thing in for stmt first clause (when expr) and third clause.
53 return StmtResult(FE.getAs<Stmt>());
57 StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
62 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
63 bool HasLeadingEmptyMacro) {
64 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
67 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
69 DeclGroupRef DG = dg.get();
71 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
74 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
77 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
78 DeclGroupRef DG = dg.get();
80 // If we don't have a declaration, or we have an invalid declaration,
82 if (DG.isNull() || !DG.isSingleDecl())
85 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
97 // foreach variables are never actually initialized in the way that
98 // the parser came up with.
99 var->setInit(nullptr);
101 // In ARC, we don't need to retain the iteration variable of a fast
102 // enumeration loop. Rather than actually trying to catch that
103 // during declaration processing, we remove the consequences here.
104 if (getLangOpts().ObjCAutoRefCount) {
105 QualType type = var->getType();
107 // Only do this if we inferred the lifetime. Inferred lifetime
108 // will show up as a local qualifier because explicit lifetime
109 // should have shown up as an AttributedType instead.
110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
111 // Add 'const' and mark the variable as pseudo-strong.
112 var->setType(type.withConst());
113 var->setARCPseudoStrong(true);
118 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
119 /// For '==' and '!=', suggest fixits for '=' or '|='.
121 /// Adding a cast to void (or other expression wrappers) will prevent the
122 /// warning from firing.
123 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
125 bool IsNotEqual, CanAssign, IsRelational;
127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
128 if (!Op->isComparisonOp())
131 IsRelational = Op->isRelationalOp();
132 Loc = Op->getOperatorLoc();
133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
136 switch (Op->getOperator()) {
140 case OO_ExclaimEqual:
141 IsRelational = false;
145 case OO_GreaterEqual:
151 Loc = Op->getOperatorLoc();
152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
155 // Not a typo-prone comparison.
159 // Suppress warnings when the operator, suspicious as it may be, comes from
160 // a macro expansion.
161 if (S.SourceMgr.isMacroBodyExpansion(Loc))
164 S.Diag(Loc, diag::warn_unused_comparison)
165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
167 // If the LHS is a plausible entity to assign to, provide a fixit hint to
168 // correct common typos.
169 if (!IsRelational && CanAssign) {
171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
172 << FixItHint::CreateReplacement(Loc, "|=");
174 S.Diag(Loc, diag::note_equality_comparison_to_assign)
175 << FixItHint::CreateReplacement(Loc, "=");
181 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
183 return DiagnoseUnusedExprResult(Label->getSubStmt());
185 const Expr *E = dyn_cast_or_null<Expr>(S);
189 // If we are in an unevaluated expression context, then there can be no unused
190 // results because the results aren't expected to be used in the first place.
191 if (isUnevaluatedContext())
194 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
195 // In most cases, we don't want to warn if the expression is written in a
196 // macro body, or if the macro comes from a system header. If the offending
197 // expression is a call to a function with the warn_unused_result attribute,
198 // we warn no matter the location. Because of the order in which the various
199 // checks need to happen, we factor out the macro-related test here.
200 bool ShouldSuppress =
201 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
202 SourceMgr.isInSystemMacro(ExprLoc);
204 const Expr *WarnExpr;
207 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
210 // If this is a GNU statement expression expanded from a macro, it is probably
211 // unused because it is a function-like macro that can be used as either an
212 // expression or statement. Don't warn, because it is almost certainly a
214 if (isa<StmtExpr>(E) && Loc.isMacroID())
217 // Okay, we have an unused result. Depending on what the base expression is,
218 // we might want to make a more specific diagnostic. Check for one of these
220 unsigned DiagID = diag::warn_unused_expr;
221 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
222 E = Temps->getSubExpr();
223 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
224 E = TempExpr->getSubExpr();
226 if (DiagnoseUnusedComparison(*this, E))
230 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
231 if (E->getType()->isVoidType())
234 // If the callee has attribute pure, const, or warn_unused_result, warn with
235 // a more specific message to make it clear what is happening. If the call
236 // is written in a macro body, only warn if it has the warn_unused_result
238 if (const Decl *FD = CE->getCalleeDecl()) {
239 if (FD->hasAttr<WarnUnusedResultAttr>()) {
240 Diag(Loc, diag::warn_unused_result) << R1 << R2;
245 if (FD->hasAttr<PureAttr>()) {
246 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
249 if (FD->hasAttr<ConstAttr>()) {
250 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
254 } else if (ShouldSuppress)
257 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
258 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
259 Diag(Loc, diag::err_arc_unused_init_message) << R1;
262 const ObjCMethodDecl *MD = ME->getMethodDecl();
264 if (MD->hasAttr<WarnUnusedResultAttr>()) {
265 Diag(Loc, diag::warn_unused_result) << R1 << R2;
268 if (MD->isPropertyAccessor()) {
269 Diag(Loc, diag::warn_unused_property_expr);
273 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
274 const Expr *Source = POE->getSyntacticForm();
275 if (isa<ObjCSubscriptRefExpr>(Source))
276 DiagID = diag::warn_unused_container_subscript_expr;
278 DiagID = diag::warn_unused_property_expr;
279 } else if (const CXXFunctionalCastExpr *FC
280 = dyn_cast<CXXFunctionalCastExpr>(E)) {
281 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
282 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
285 // Diagnose "(void*) blah" as a typo for "(void) blah".
286 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
287 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
288 QualType T = TI->getType();
290 // We really do want to use the non-canonical type here.
291 if (T == Context.VoidPtrTy) {
292 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
294 Diag(Loc, diag::warn_unused_voidptr)
295 << FixItHint::CreateRemoval(TL.getStarLoc());
300 if (E->isGLValue() && E->getType().isVolatileQualified()) {
301 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
305 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
308 void Sema::ActOnStartOfCompoundStmt() {
312 void Sema::ActOnFinishOfCompoundStmt() {
316 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
317 return getCurFunction()->CompoundScopes.back();
320 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
321 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
322 const unsigned NumElts = Elts.size();
324 // If we're in C89 mode, check that we don't have any decls after stmts. If
325 // so, emit an extension diagnostic.
326 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
327 // Note that __extension__ can be around a decl.
329 // Skip over all declarations.
330 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
333 // We found the end of the list or a statement. Scan for another declstmt.
334 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
338 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
339 Diag(D->getLocation(), diag::ext_mixed_decls_code);
342 // Warn about unused expressions in statements.
343 for (unsigned i = 0; i != NumElts; ++i) {
344 // Ignore statements that are last in a statement expression.
345 if (isStmtExpr && i == NumElts - 1)
348 DiagnoseUnusedExprResult(Elts[i]);
351 // Check for suspicious empty body (null statement) in `for' and `while'
352 // statements. Don't do anything for template instantiations, this just adds
354 if (NumElts != 0 && !CurrentInstantiationScope &&
355 getCurCompoundScope().HasEmptyLoopBodies) {
356 for (unsigned i = 0; i != NumElts - 1; ++i)
357 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
360 return new (Context) CompoundStmt(Context, Elts, L, R);
364 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
365 SourceLocation DotDotDotLoc, Expr *RHSVal,
366 SourceLocation ColonLoc) {
367 assert(LHSVal && "missing expression in case statement");
369 if (getCurFunction()->SwitchStack.empty()) {
370 Diag(CaseLoc, diag::err_case_not_in_switch);
375 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
376 if (!getLangOpts().CPlusPlus11)
377 return VerifyIntegerConstantExpression(E);
379 getCurFunction()->SwitchStack.back()->getCond()) {
380 QualType CondType = CondExpr->getType();
381 llvm::APSInt TempVal;
382 return CheckConvertedConstantExpression(E, CondType, TempVal,
391 if (!getLangOpts().CPlusPlus11) {
392 // C99 6.8.4.2p3: The expression shall be an integer constant.
393 // However, GCC allows any evaluatable integer expression.
394 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
395 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
400 // GCC extension: The expression shall be an integer constant.
402 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
403 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
404 // Recover from an error by just forgetting about it.
408 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
409 getLangOpts().CPlusPlus11);
413 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
414 getLangOpts().CPlusPlus11)
419 CaseStmt *CS = new (Context)
420 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
421 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
425 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
426 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
427 DiagnoseUnusedExprResult(SubStmt);
429 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
430 CS->setSubStmt(SubStmt);
434 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
435 Stmt *SubStmt, Scope *CurScope) {
436 DiagnoseUnusedExprResult(SubStmt);
438 if (getCurFunction()->SwitchStack.empty()) {
439 Diag(DefaultLoc, diag::err_default_not_in_switch);
443 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
444 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
449 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
450 SourceLocation ColonLoc, Stmt *SubStmt) {
451 // If the label was multiply defined, reject it now.
452 if (TheDecl->getStmt()) {
453 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
454 Diag(TheDecl->getLocation(), diag::note_previous_definition);
458 // Otherwise, things are good. Fill in the declaration and return it.
459 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
460 TheDecl->setStmt(LS);
461 if (!TheDecl->isGnuLocal()) {
462 TheDecl->setLocStart(IdentLoc);
463 if (!TheDecl->isMSAsmLabel()) {
464 // Don't update the location of MS ASM labels. These will result in
465 // a diagnostic, and changing the location here will mess that up.
466 TheDecl->setLocation(IdentLoc);
472 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
473 ArrayRef<const Attr*> Attrs,
475 // Fill in the declaration and return it.
476 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
481 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
482 Stmt *thenStmt, SourceLocation ElseLoc,
484 // If the condition was invalid, discard the if statement. We could recover
485 // better by replacing it with a valid expr, but don't do that yet.
486 if (!CondVal.get() && !CondVar) {
487 getCurFunction()->setHasDroppedStmt();
491 ExprResult CondResult(CondVal.release());
493 VarDecl *ConditionVar = nullptr;
495 ConditionVar = cast<VarDecl>(CondVar);
496 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
497 if (CondResult.isInvalid())
500 Expr *ConditionExpr = CondResult.getAs<Expr>();
504 DiagnoseUnusedExprResult(thenStmt);
507 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
508 diag::warn_empty_if_body);
511 DiagnoseUnusedExprResult(elseStmt);
513 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
514 thenStmt, ElseLoc, elseStmt);
518 struct CaseCompareFunctor {
519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const llvm::APSInt &RHS) {
521 return LHS.first < RHS;
523 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS.first < RHS.first;
527 bool operator()(const llvm::APSInt &LHS,
528 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
529 return LHS < RHS.first;
534 /// CmpCaseVals - Comparison predicate for sorting case values.
536 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
537 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
538 if (lhs.first < rhs.first)
541 if (lhs.first == rhs.first &&
542 lhs.second->getCaseLoc().getRawEncoding()
543 < rhs.second->getCaseLoc().getRawEncoding())
548 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
550 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
551 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
553 return lhs.first < rhs.first;
556 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
558 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
559 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
561 return lhs.first == rhs.first;
564 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
565 /// potentially integral-promoted expression @p expr.
566 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
567 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
568 expr = cleanups->getSubExpr();
569 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
570 if (impcast->getCastKind() != CK_IntegralCast) break;
571 expr = impcast->getSubExpr();
573 return expr->getType();
577 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
579 ExprResult CondResult;
581 VarDecl *ConditionVar = nullptr;
583 ConditionVar = cast<VarDecl>(CondVar);
584 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
585 if (CondResult.isInvalid())
588 Cond = CondResult.get();
594 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
598 SwitchConvertDiagnoser(Expr *Cond)
599 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
602 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
603 QualType T) override {
604 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
607 SemaDiagnosticBuilder diagnoseIncomplete(
608 Sema &S, SourceLocation Loc, QualType T) override {
609 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
610 << T << Cond->getSourceRange();
613 SemaDiagnosticBuilder diagnoseExplicitConv(
614 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
615 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
618 SemaDiagnosticBuilder noteExplicitConv(
619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
620 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
621 << ConvTy->isEnumeralType() << ConvTy;
624 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
625 QualType T) override {
626 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
629 SemaDiagnosticBuilder noteAmbiguous(
630 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
631 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
632 << ConvTy->isEnumeralType() << ConvTy;
635 SemaDiagnosticBuilder diagnoseConversion(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
637 llvm_unreachable("conversion functions are permitted");
639 } SwitchDiagnoser(Cond);
642 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
643 if (CondResult.isInvalid()) return StmtError();
644 Cond = CondResult.get();
646 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
647 CondResult = UsualUnaryConversions(Cond);
648 if (CondResult.isInvalid()) return StmtError();
649 Cond = CondResult.get();
652 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
653 if (CondResult.isInvalid())
655 Cond = CondResult.get();
658 getCurFunction()->setHasBranchIntoScope();
660 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
661 getCurFunction()->SwitchStack.push_back(SS);
665 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
666 Val = Val.extOrTrunc(BitWidth);
667 Val.setIsSigned(IsSigned);
670 /// Check the specified case value is in range for the given unpromoted switch
672 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
673 unsigned UnpromotedWidth, bool UnpromotedSign) {
674 // If the case value was signed and negative and the switch expression is
675 // unsigned, don't bother to warn: this is implementation-defined behavior.
676 // FIXME: Introduce a second, default-ignored warning for this case?
677 if (UnpromotedWidth < Val.getBitWidth()) {
678 llvm::APSInt ConvVal(Val);
679 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
680 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
681 // FIXME: Use different diagnostics for overflow in conversion to promoted
682 // type versus "switch expression cannot have this value". Use proper
683 // IntRange checking rather than just looking at the unpromoted type here.
685 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
686 << ConvVal.toString(10);
690 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
692 /// Returns true if we should emit a diagnostic about this case expression not
693 /// being a part of the enum used in the switch controlling expression.
694 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
696 const Expr *CaseExpr,
697 EnumValsTy::iterator &EI,
698 EnumValsTy::iterator &EIEnd,
699 const llvm::APSInt &Val) {
700 bool FlagType = ED->hasAttr<FlagEnumAttr>();
702 if (const DeclRefExpr *DRE =
703 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
704 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
705 QualType VarType = VD->getType();
706 QualType EnumType = S.Context.getTypeDeclType(ED);
707 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
708 S.Context.hasSameUnqualifiedType(EnumType, VarType))
714 return !S.IsValueInFlagEnum(ED, Val, false);
716 while (EI != EIEnd && EI->first < Val)
719 if (EI != EIEnd && EI->first == Val)
727 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
729 SwitchStmt *SS = cast<SwitchStmt>(Switch);
730 assert(SS == getCurFunction()->SwitchStack.back() &&
731 "switch stack missing push/pop!");
733 getCurFunction()->SwitchStack.pop_back();
735 if (!BodyStmt) return StmtError();
736 SS->setBody(BodyStmt, SwitchLoc);
738 Expr *CondExpr = SS->getCond();
739 if (!CondExpr) return StmtError();
741 QualType CondType = CondExpr->getType();
743 Expr *CondExprBeforePromotion = CondExpr;
744 QualType CondTypeBeforePromotion =
745 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
748 // Integral promotions are performed (on the switch condition).
750 // A case value unrepresentable by the original switch condition
751 // type (before the promotion) doesn't make sense, even when it can
752 // be represented by the promoted type. Therefore we need to find
753 // the pre-promotion type of the switch condition.
754 if (!CondExpr->isTypeDependent()) {
755 // We have already converted the expression to an integral or enumeration
756 // type, when we started the switch statement. If we don't have an
757 // appropriate type now, just return an error.
758 if (!CondType->isIntegralOrEnumerationType())
761 if (CondExpr->isKnownToHaveBooleanValue()) {
762 // switch(bool_expr) {...} is often a programmer error, e.g.
763 // switch(n && mask) { ... } // Doh - should be "n & mask".
764 // One can always use an if statement instead of switch(bool_expr).
765 Diag(SwitchLoc, diag::warn_bool_switch_condition)
766 << CondExpr->getSourceRange();
770 // Get the bitwidth of the switched-on value after promotions. We must
771 // convert the integer case values to this width before comparison.
772 bool HasDependentValue
773 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
774 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
775 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
777 // Get the width and signedness that the condition might actually have, for
779 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
781 unsigned CondWidthBeforePromotion
782 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
783 bool CondIsSignedBeforePromotion
784 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
786 // Accumulate all of the case values in a vector so that we can sort them
787 // and detect duplicates. This vector contains the APInt for the case after
788 // it has been converted to the condition type.
789 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
792 // Keep track of any GNU case ranges we see. The APSInt is the low value.
793 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
794 CaseRangesTy CaseRanges;
796 DefaultStmt *TheDefaultStmt = nullptr;
798 bool CaseListIsErroneous = false;
800 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
801 SC = SC->getNextSwitchCase()) {
803 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
804 if (TheDefaultStmt) {
805 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
806 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
808 // FIXME: Remove the default statement from the switch block so that
809 // we'll return a valid AST. This requires recursing down the AST and
810 // finding it, not something we are set up to do right now. For now,
811 // just lop the entire switch stmt out of the AST.
812 CaseListIsErroneous = true;
817 CaseStmt *CS = cast<CaseStmt>(SC);
819 Expr *Lo = CS->getLHS();
821 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
822 HasDependentValue = true;
828 if (getLangOpts().CPlusPlus11) {
829 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
830 // constant expression of the promoted type of the switch condition.
832 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
833 if (ConvLo.isInvalid()) {
834 CaseListIsErroneous = true;
839 // We already verified that the expression has a i-c-e value (C99
840 // 6.8.4.2p3) - get that value now.
841 LoVal = Lo->EvaluateKnownConstInt(Context);
843 // If the LHS is not the same type as the condition, insert an implicit
845 Lo = DefaultLvalueConversion(Lo).get();
846 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
849 // Check the unconverted value is within the range of possible values of
850 // the switch expression.
851 checkCaseValue(*this, Lo->getLocStart(), LoVal,
852 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
854 // Convert the value to the same width/sign as the condition.
855 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
859 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
861 if (CS->getRHS()->isTypeDependent() ||
862 CS->getRHS()->isValueDependent()) {
863 HasDependentValue = true;
866 CaseRanges.push_back(std::make_pair(LoVal, CS));
868 CaseVals.push_back(std::make_pair(LoVal, CS));
872 if (!HasDependentValue) {
873 // If we don't have a default statement, check whether the
874 // condition is constant.
875 llvm::APSInt ConstantCondValue;
876 bool HasConstantCond = false;
877 if (!HasDependentValue && !TheDefaultStmt) {
878 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
879 Expr::SE_AllowSideEffects);
880 assert(!HasConstantCond ||
881 (ConstantCondValue.getBitWidth() == CondWidth &&
882 ConstantCondValue.isSigned() == CondIsSigned));
884 bool ShouldCheckConstantCond = HasConstantCond;
886 // Sort all the scalar case values so we can easily detect duplicates.
887 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
889 if (!CaseVals.empty()) {
890 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
891 if (ShouldCheckConstantCond &&
892 CaseVals[i].first == ConstantCondValue)
893 ShouldCheckConstantCond = false;
895 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
896 // If we have a duplicate, report it.
897 // First, determine if either case value has a name
898 StringRef PrevString, CurrString;
899 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
900 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
901 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
902 PrevString = DeclRef->getDecl()->getName();
904 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
905 CurrString = DeclRef->getDecl()->getName();
907 SmallString<16> CaseValStr;
908 CaseVals[i-1].first.toString(CaseValStr);
910 if (PrevString == CurrString)
911 Diag(CaseVals[i].second->getLHS()->getLocStart(),
912 diag::err_duplicate_case) <<
913 (PrevString.empty() ? CaseValStr.str() : PrevString);
915 Diag(CaseVals[i].second->getLHS()->getLocStart(),
916 diag::err_duplicate_case_differing_expr) <<
917 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
918 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
921 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
922 diag::note_duplicate_case_prev);
923 // FIXME: We really want to remove the bogus case stmt from the
924 // substmt, but we have no way to do this right now.
925 CaseListIsErroneous = true;
930 // Detect duplicate case ranges, which usually don't exist at all in
932 if (!CaseRanges.empty()) {
933 // Sort all the case ranges by their low value so we can easily detect
934 // overlaps between ranges.
935 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
937 // Scan the ranges, computing the high values and removing empty ranges.
938 std::vector<llvm::APSInt> HiVals;
939 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
940 llvm::APSInt &LoVal = CaseRanges[i].first;
941 CaseStmt *CR = CaseRanges[i].second;
942 Expr *Hi = CR->getRHS();
945 if (getLangOpts().CPlusPlus11) {
946 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
947 // constant expression of the promoted type of the switch condition.
949 CheckConvertedConstantExpression(Hi, CondType, HiVal,
951 if (ConvHi.isInvalid()) {
952 CaseListIsErroneous = true;
957 HiVal = Hi->EvaluateKnownConstInt(Context);
959 // If the RHS is not the same type as the condition, insert an
961 Hi = DefaultLvalueConversion(Hi).get();
962 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
965 // Check the unconverted value is within the range of possible values of
966 // the switch expression.
967 checkCaseValue(*this, Hi->getLocStart(), HiVal,
968 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
970 // Convert the value to the same width/sign as the condition.
971 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
975 // If the low value is bigger than the high value, the case is empty.
977 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
978 << SourceRange(CR->getLHS()->getLocStart(),
980 CaseRanges.erase(CaseRanges.begin()+i);
985 if (ShouldCheckConstantCond &&
986 LoVal <= ConstantCondValue &&
987 ConstantCondValue <= HiVal)
988 ShouldCheckConstantCond = false;
990 HiVals.push_back(HiVal);
993 // Rescan the ranges, looking for overlap with singleton values and other
994 // ranges. Since the range list is sorted, we only need to compare case
995 // ranges with their neighbors.
996 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
997 llvm::APSInt &CRLo = CaseRanges[i].first;
998 llvm::APSInt &CRHi = HiVals[i];
999 CaseStmt *CR = CaseRanges[i].second;
1001 // Check to see whether the case range overlaps with any
1003 CaseStmt *OverlapStmt = nullptr;
1004 llvm::APSInt OverlapVal(32);
1006 // Find the smallest value >= the lower bound. If I is in the
1007 // case range, then we have overlap.
1008 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1009 CaseVals.end(), CRLo,
1010 CaseCompareFunctor());
1011 if (I != CaseVals.end() && I->first < CRHi) {
1012 OverlapVal = I->first; // Found overlap with scalar.
1013 OverlapStmt = I->second;
1016 // Find the smallest value bigger than the upper bound.
1017 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1018 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1019 OverlapVal = (I-1)->first; // Found overlap with scalar.
1020 OverlapStmt = (I-1)->second;
1023 // Check to see if this case stmt overlaps with the subsequent
1025 if (i && CRLo <= HiVals[i-1]) {
1026 OverlapVal = HiVals[i-1]; // Found overlap with range.
1027 OverlapStmt = CaseRanges[i-1].second;
1031 // If we have a duplicate, report it.
1032 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1033 << OverlapVal.toString(10);
1034 Diag(OverlapStmt->getLHS()->getLocStart(),
1035 diag::note_duplicate_case_prev);
1036 // FIXME: We really want to remove the bogus case stmt from the
1037 // substmt, but we have no way to do this right now.
1038 CaseListIsErroneous = true;
1043 // Complain if we have a constant condition and we didn't find a match.
1044 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1045 // TODO: it would be nice if we printed enums as enums, chars as
1047 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1048 << ConstantCondValue.toString(10)
1049 << CondExpr->getSourceRange();
1052 // Check to see if switch is over an Enum and handles all of its
1053 // values. We only issue a warning if there is not 'default:', but
1054 // we still do the analysis to preserve this information in the AST
1055 // (which can be used by flow-based analyes).
1057 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1059 // If switch has default case, then ignore it.
1060 if (!CaseListIsErroneous && !HasConstantCond && ET) {
1061 const EnumDecl *ED = ET->getDecl();
1062 EnumValsTy EnumVals;
1064 // Gather all enum values, set their type and sort them,
1065 // allowing easier comparison with CaseVals.
1066 for (auto *EDI : ED->enumerators()) {
1067 llvm::APSInt Val = EDI->getInitVal();
1068 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1069 EnumVals.push_back(std::make_pair(Val, EDI));
1071 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1072 auto EI = EnumVals.begin(), EIEnd =
1073 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1075 // See which case values aren't in enum.
1076 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1077 CI != CaseVals.end(); CI++) {
1078 Expr *CaseExpr = CI->second->getLHS();
1079 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1081 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1082 << CondTypeBeforePromotion;
1085 // See which of case ranges aren't in enum
1086 EI = EnumVals.begin();
1087 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1088 RI != CaseRanges.end(); RI++) {
1089 Expr *CaseExpr = RI->second->getLHS();
1090 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1092 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1093 << CondTypeBeforePromotion;
1096 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1097 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1099 CaseExpr = RI->second->getRHS();
1100 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1102 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1103 << CondTypeBeforePromotion;
1106 // Check which enum vals aren't in switch
1107 auto CI = CaseVals.begin();
1108 auto RI = CaseRanges.begin();
1109 bool hasCasesNotInSwitch = false;
1111 SmallVector<DeclarationName,8> UnhandledNames;
1113 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1114 // Drop unneeded case values
1115 while (CI != CaseVals.end() && CI->first < EI->first)
1118 if (CI != CaseVals.end() && CI->first == EI->first)
1121 // Drop unneeded case ranges
1122 for (; RI != CaseRanges.end(); RI++) {
1124 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1125 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1126 if (EI->first <= Hi)
1130 if (RI == CaseRanges.end() || EI->first < RI->first) {
1131 hasCasesNotInSwitch = true;
1132 UnhandledNames.push_back(EI->second->getDeclName());
1136 if (TheDefaultStmt && UnhandledNames.empty())
1137 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1139 // Produce a nice diagnostic if multiple values aren't handled.
1140 switch (UnhandledNames.size()) {
1143 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1144 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1145 << UnhandledNames[0];
1148 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1149 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1150 << UnhandledNames[0] << UnhandledNames[1];
1153 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1154 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1155 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1158 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1159 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1160 << (unsigned)UnhandledNames.size()
1161 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1165 if (!hasCasesNotInSwitch)
1166 SS->setAllEnumCasesCovered();
1171 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1172 diag::warn_empty_switch_body);
1174 // FIXME: If the case list was broken is some way, we don't have a good system
1175 // to patch it up. Instead, just return the whole substmt as broken.
1176 if (CaseListIsErroneous)
1183 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1185 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1188 if (const EnumType *ET = DstType->getAs<EnumType>())
1189 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1190 SrcType->isIntegerType()) {
1191 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1192 SrcExpr->isIntegerConstantExpr(Context)) {
1193 // Get the bitwidth of the enum value before promotions.
1194 unsigned DstWidth = Context.getIntWidth(DstType);
1195 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1197 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1198 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1199 const EnumDecl *ED = ET->getDecl();
1201 if (ED->hasAttr<FlagEnumAttr>()) {
1202 if (!IsValueInFlagEnum(ED, RhsVal, true))
1203 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1204 << DstType.getUnqualifiedType();
1206 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1208 EnumValsTy EnumVals;
1210 // Gather all enum values, set their type and sort them,
1211 // allowing easier comparison with rhs constant.
1212 for (auto *EDI : ED->enumerators()) {
1213 llvm::APSInt Val = EDI->getInitVal();
1214 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1215 EnumVals.push_back(std::make_pair(Val, EDI));
1217 if (EnumVals.empty())
1219 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1220 EnumValsTy::iterator EIend =
1221 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1223 // See which values aren't in the enum.
1224 EnumValsTy::const_iterator EI = EnumVals.begin();
1225 while (EI != EIend && EI->first < RhsVal)
1227 if (EI == EIend || EI->first != RhsVal) {
1228 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1229 << DstType.getUnqualifiedType();
1237 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1238 Decl *CondVar, Stmt *Body) {
1239 ExprResult CondResult(Cond.release());
1241 VarDecl *ConditionVar = nullptr;
1243 ConditionVar = cast<VarDecl>(CondVar);
1244 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1245 if (CondResult.isInvalid())
1248 Expr *ConditionExpr = CondResult.get();
1251 CheckBreakContinueBinding(ConditionExpr);
1253 DiagnoseUnusedExprResult(Body);
1255 if (isa<NullStmt>(Body))
1256 getCurCompoundScope().setHasEmptyLoopBodies();
1258 return new (Context)
1259 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
1263 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1264 SourceLocation WhileLoc, SourceLocation CondLParen,
1265 Expr *Cond, SourceLocation CondRParen) {
1266 assert(Cond && "ActOnDoStmt(): missing expression");
1268 CheckBreakContinueBinding(Cond);
1269 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1270 if (CondResult.isInvalid())
1272 Cond = CondResult.get();
1274 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1275 if (CondResult.isInvalid())
1277 Cond = CondResult.get();
1279 DiagnoseUnusedExprResult(Body);
1281 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1285 // This visitor will traverse a conditional statement and store all
1286 // the evaluated decls into a vector. Simple is set to true if none
1287 // of the excluded constructs are used.
1288 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1289 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1290 SmallVectorImpl<SourceRange> &Ranges;
1293 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1295 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1296 SmallVectorImpl<SourceRange> &Ranges) :
1297 Inherited(S.Context),
1302 bool isSimple() { return Simple; }
1304 // Replaces the method in EvaluatedExprVisitor.
1305 void VisitMemberExpr(MemberExpr* E) {
1309 // Any Stmt not whitelisted will cause the condition to be marked complex.
1310 void VisitStmt(Stmt *S) {
1314 void VisitBinaryOperator(BinaryOperator *E) {
1319 void VisitCastExpr(CastExpr *E) {
1320 Visit(E->getSubExpr());
1323 void VisitUnaryOperator(UnaryOperator *E) {
1324 // Skip checking conditionals with derefernces.
1325 if (E->getOpcode() == UO_Deref)
1328 Visit(E->getSubExpr());
1331 void VisitConditionalOperator(ConditionalOperator *E) {
1332 Visit(E->getCond());
1333 Visit(E->getTrueExpr());
1334 Visit(E->getFalseExpr());
1337 void VisitParenExpr(ParenExpr *E) {
1338 Visit(E->getSubExpr());
1341 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1342 Visit(E->getOpaqueValue()->getSourceExpr());
1343 Visit(E->getFalseExpr());
1346 void VisitIntegerLiteral(IntegerLiteral *E) { }
1347 void VisitFloatingLiteral(FloatingLiteral *E) { }
1348 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1349 void VisitCharacterLiteral(CharacterLiteral *E) { }
1350 void VisitGNUNullExpr(GNUNullExpr *E) { }
1351 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1353 void VisitDeclRefExpr(DeclRefExpr *E) {
1354 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1357 Ranges.push_back(E->getSourceRange());
1362 }; // end class DeclExtractor
1364 // DeclMatcher checks to see if the decls are used in a non-evauluated
1366 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1367 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1371 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1373 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1375 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1376 if (!Statement) return;
1381 void VisitReturnStmt(ReturnStmt *S) {
1385 void VisitBreakStmt(BreakStmt *S) {
1389 void VisitGotoStmt(GotoStmt *S) {
1393 void VisitCastExpr(CastExpr *E) {
1394 if (E->getCastKind() == CK_LValueToRValue)
1395 CheckLValueToRValueCast(E->getSubExpr());
1397 Visit(E->getSubExpr());
1400 void CheckLValueToRValueCast(Expr *E) {
1401 E = E->IgnoreParenImpCasts();
1403 if (isa<DeclRefExpr>(E)) {
1407 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1408 Visit(CO->getCond());
1409 CheckLValueToRValueCast(CO->getTrueExpr());
1410 CheckLValueToRValueCast(CO->getFalseExpr());
1414 if (BinaryConditionalOperator *BCO =
1415 dyn_cast<BinaryConditionalOperator>(E)) {
1416 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1417 CheckLValueToRValueCast(BCO->getFalseExpr());
1424 void VisitDeclRefExpr(DeclRefExpr *E) {
1425 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1426 if (Decls.count(VD))
1430 bool FoundDeclInUse() { return FoundDecl; }
1432 }; // end class DeclMatcher
1434 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1435 Expr *Third, Stmt *Body) {
1436 // Condition is empty
1437 if (!Second) return;
1439 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1440 Second->getLocStart()))
1443 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1444 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1445 SmallVector<SourceRange, 10> Ranges;
1446 DeclExtractor DE(S, Decls, Ranges);
1449 // Don't analyze complex conditionals.
1450 if (!DE.isSimple()) return;
1453 if (Decls.size() == 0) return;
1455 // Don't warn on volatile, static, or global variables.
1456 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1459 if ((*I)->getType().isVolatileQualified() ||
1460 (*I)->hasGlobalStorage()) return;
1462 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1463 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1464 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1467 // Load decl names into diagnostic.
1468 if (Decls.size() > 4)
1471 PDiag << Decls.size();
1472 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1475 PDiag << (*I)->getDeclName();
1478 // Load SourceRanges into diagnostic if there is room.
1479 // Otherwise, load the SourceRange of the conditional expression.
1480 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1481 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1486 PDiag << Second->getSourceRange();
1488 S.Diag(Ranges.begin()->getBegin(), PDiag);
1491 // If Statement is an incemement or decrement, return true and sets the
1492 // variables Increment and DRE.
1493 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1494 DeclRefExpr *&DRE) {
1495 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1496 switch (UO->getOpcode()) {
1497 default: return false;
1507 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1511 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1512 FunctionDecl *FD = Call->getDirectCallee();
1513 if (!FD || !FD->isOverloadedOperator()) return false;
1514 switch (FD->getOverloadedOperator()) {
1515 default: return false;
1523 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1530 // A visitor to determine if a continue or break statement is a
1532 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1533 SourceLocation BreakLoc;
1534 SourceLocation ContinueLoc;
1536 BreakContinueFinder(Sema &S, Stmt* Body) :
1537 Inherited(S.Context) {
1541 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1543 void VisitContinueStmt(ContinueStmt* E) {
1544 ContinueLoc = E->getContinueLoc();
1547 void VisitBreakStmt(BreakStmt* E) {
1548 BreakLoc = E->getBreakLoc();
1551 bool ContinueFound() { return ContinueLoc.isValid(); }
1552 bool BreakFound() { return BreakLoc.isValid(); }
1553 SourceLocation GetContinueLoc() { return ContinueLoc; }
1554 SourceLocation GetBreakLoc() { return BreakLoc; }
1556 }; // end class BreakContinueFinder
1558 // Emit a warning when a loop increment/decrement appears twice per loop
1559 // iteration. The conditions which trigger this warning are:
1560 // 1) The last statement in the loop body and the third expression in the
1561 // for loop are both increment or both decrement of the same variable
1562 // 2) No continue statements in the loop body.
1563 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1564 // Return when there is nothing to check.
1565 if (!Body || !Third) return;
1567 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1568 Third->getLocStart()))
1571 // Get the last statement from the loop body.
1572 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1573 if (!CS || CS->body_empty()) return;
1574 Stmt *LastStmt = CS->body_back();
1575 if (!LastStmt) return;
1577 bool LoopIncrement, LastIncrement;
1578 DeclRefExpr *LoopDRE, *LastDRE;
1580 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1581 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1583 // Check that the two statements are both increments or both decrements
1584 // on the same variable.
1585 if (LoopIncrement != LastIncrement ||
1586 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1588 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1590 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1591 << LastDRE->getDecl() << LastIncrement;
1592 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1599 void Sema::CheckBreakContinueBinding(Expr *E) {
1600 if (!E || getLangOpts().CPlusPlus)
1602 BreakContinueFinder BCFinder(*this, E);
1603 Scope *BreakParent = CurScope->getBreakParent();
1604 if (BCFinder.BreakFound() && BreakParent) {
1605 if (BreakParent->getFlags() & Scope::SwitchScope) {
1606 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1608 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1611 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1612 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1618 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1619 Stmt *First, FullExprArg second, Decl *secondVar,
1621 SourceLocation RParenLoc, Stmt *Body) {
1622 if (!getLangOpts().CPlusPlus) {
1623 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1624 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1625 // declare identifiers for objects having storage class 'auto' or
1627 for (auto *DI : DS->decls()) {
1628 VarDecl *VD = dyn_cast<VarDecl>(DI);
1629 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1632 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1633 DI->setInvalidDecl();
1639 CheckBreakContinueBinding(second.get());
1640 CheckBreakContinueBinding(third.get());
1642 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1643 CheckForRedundantIteration(*this, third.get(), Body);
1645 ExprResult SecondResult(second.release());
1646 VarDecl *ConditionVar = nullptr;
1648 ConditionVar = cast<VarDecl>(secondVar);
1649 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1650 if (SecondResult.isInvalid())
1654 Expr *Third = third.release().getAs<Expr>();
1656 DiagnoseUnusedExprResult(First);
1657 DiagnoseUnusedExprResult(Third);
1658 DiagnoseUnusedExprResult(Body);
1660 if (isa<NullStmt>(Body))
1661 getCurCompoundScope().setHasEmptyLoopBodies();
1663 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1664 Third, Body, ForLoc, LParenLoc, RParenLoc);
1667 /// In an Objective C collection iteration statement:
1669 /// x can be an arbitrary l-value expression. Bind it up as a
1670 /// full-expression.
1671 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1672 // Reduce placeholder expressions here. Note that this rejects the
1673 // use of pseudo-object l-values in this position.
1674 ExprResult result = CheckPlaceholderExpr(E);
1675 if (result.isInvalid()) return StmtError();
1678 ExprResult FullExpr = ActOnFinishFullExpr(E);
1679 if (FullExpr.isInvalid())
1681 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1685 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1689 ExprResult result = CorrectDelayedTyposInExpr(collection);
1690 if (!result.isUsable())
1692 collection = result.get();
1694 // Bail out early if we've got a type-dependent expression.
1695 if (collection->isTypeDependent()) return collection;
1697 // Perform normal l-value conversion.
1698 result = DefaultFunctionArrayLvalueConversion(collection);
1699 if (result.isInvalid())
1701 collection = result.get();
1703 // The operand needs to have object-pointer type.
1704 // TODO: should we do a contextual conversion?
1705 const ObjCObjectPointerType *pointerType =
1706 collection->getType()->getAs<ObjCObjectPointerType>();
1708 return Diag(forLoc, diag::err_collection_expr_type)
1709 << collection->getType() << collection->getSourceRange();
1711 // Check that the operand provides
1712 // - countByEnumeratingWithState:objects:count:
1713 const ObjCObjectType *objectType = pointerType->getObjectType();
1714 ObjCInterfaceDecl *iface = objectType->getInterface();
1716 // If we have a forward-declared type, we can't do this check.
1717 // Under ARC, it is an error not to have a forward-declared class.
1719 RequireCompleteType(forLoc, QualType(objectType, 0),
1720 getLangOpts().ObjCAutoRefCount
1721 ? diag::err_arc_collection_forward
1724 // Otherwise, if we have any useful type information, check that
1725 // the type declares the appropriate method.
1726 } else if (iface || !objectType->qual_empty()) {
1727 IdentifierInfo *selectorIdents[] = {
1728 &Context.Idents.get("countByEnumeratingWithState"),
1729 &Context.Idents.get("objects"),
1730 &Context.Idents.get("count")
1732 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1734 ObjCMethodDecl *method = nullptr;
1736 // If there's an interface, look in both the public and private APIs.
1738 method = iface->lookupInstanceMethod(selector);
1739 if (!method) method = iface->lookupPrivateMethod(selector);
1742 // Also check protocol qualifiers.
1744 method = LookupMethodInQualifiedType(selector, pointerType,
1747 // If we didn't find it anywhere, give up.
1749 Diag(forLoc, diag::warn_collection_expr_type)
1750 << collection->getType() << selector << collection->getSourceRange();
1753 // TODO: check for an incompatible signature?
1756 // Wrap up any cleanups in the expression.
1761 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1762 Stmt *First, Expr *collection,
1763 SourceLocation RParenLoc) {
1765 ExprResult CollectionExprResult =
1766 CheckObjCForCollectionOperand(ForLoc, collection);
1770 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1771 if (!DS->isSingleDecl())
1772 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1773 diag::err_toomany_element_decls));
1775 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1776 if (!D || D->isInvalidDecl())
1779 FirstType = D->getType();
1780 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1781 // declare identifiers for objects having storage class 'auto' or
1783 if (!D->hasLocalStorage())
1784 return StmtError(Diag(D->getLocation(),
1785 diag::err_non_local_variable_decl_in_for));
1787 // If the type contained 'auto', deduce the 'auto' to 'id'.
1788 if (FirstType->getContainedAutoType()) {
1789 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1791 Expr *DeducedInit = &OpaqueId;
1792 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1794 DiagnoseAutoDeductionFailure(D, DeducedInit);
1795 if (FirstType.isNull()) {
1796 D->setInvalidDecl();
1800 D->setType(FirstType);
1802 if (ActiveTemplateInstantiations.empty()) {
1803 SourceLocation Loc =
1804 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1805 Diag(Loc, diag::warn_auto_var_is_id)
1806 << D->getDeclName();
1811 Expr *FirstE = cast<Expr>(First);
1812 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1813 return StmtError(Diag(First->getLocStart(),
1814 diag::err_selector_element_not_lvalue)
1815 << First->getSourceRange());
1817 FirstType = static_cast<Expr*>(First)->getType();
1818 if (FirstType.isConstQualified())
1819 Diag(ForLoc, diag::err_selector_element_const_type)
1820 << FirstType << First->getSourceRange();
1822 if (!FirstType->isDependentType() &&
1823 !FirstType->isObjCObjectPointerType() &&
1824 !FirstType->isBlockPointerType())
1825 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1826 << FirstType << First->getSourceRange());
1829 if (CollectionExprResult.isInvalid())
1832 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1833 if (CollectionExprResult.isInvalid())
1836 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1837 nullptr, ForLoc, RParenLoc);
1840 /// Finish building a variable declaration for a for-range statement.
1841 /// \return true if an error occurs.
1842 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1843 SourceLocation Loc, int DiagID) {
1844 // Deduce the type for the iterator variable now rather than leaving it to
1845 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1847 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1848 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1850 SemaRef.Diag(Loc, DiagID) << Init->getType();
1851 if (InitType.isNull()) {
1852 Decl->setInvalidDecl();
1855 Decl->setType(InitType);
1857 // In ARC, infer lifetime.
1858 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1859 // we're doing the equivalent of fast iteration.
1860 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1861 SemaRef.inferObjCARCLifetime(Decl))
1862 Decl->setInvalidDecl();
1864 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1865 /*TypeMayContainAuto=*/false);
1866 SemaRef.FinalizeDeclaration(Decl);
1867 SemaRef.CurContext->addHiddenDecl(Decl);
1873 /// Produce a note indicating which begin/end function was implicitly called
1874 /// by a C++11 for-range statement. This is often not obvious from the code,
1875 /// nor from the diagnostics produced when analysing the implicit expressions
1876 /// required in a for-range statement.
1877 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1878 Sema::BeginEndFunction BEF) {
1879 CallExpr *CE = dyn_cast<CallExpr>(E);
1882 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1885 SourceLocation Loc = D->getLocation();
1887 std::string Description;
1888 bool IsTemplate = false;
1889 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1890 Description = SemaRef.getTemplateArgumentBindingsText(
1891 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1895 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1896 << BEF << IsTemplate << Description << E->getType();
1899 /// Build a variable declaration for a for-range statement.
1900 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1901 QualType Type, const char *Name) {
1902 DeclContext *DC = SemaRef.CurContext;
1903 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1904 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1905 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1907 Decl->setImplicit();
1913 static bool ObjCEnumerationCollection(Expr *Collection) {
1914 return !Collection->isTypeDependent()
1915 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1918 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1920 /// C++11 [stmt.ranged]:
1921 /// A range-based for statement is equivalent to
1924 /// auto && __range = range-init;
1925 /// for ( auto __begin = begin-expr,
1926 /// __end = end-expr;
1927 /// __begin != __end;
1929 /// for-range-declaration = *__begin;
1934 /// The body of the loop is not available yet, since it cannot be analysed until
1935 /// we have determined the type of the for-range-declaration.
1937 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1938 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1939 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1943 if (Range && ObjCEnumerationCollection(Range))
1944 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1946 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1947 assert(DS && "first part of for range not a decl stmt");
1949 if (!DS->isSingleDecl()) {
1950 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1954 Decl *LoopVar = DS->getSingleDecl();
1955 if (LoopVar->isInvalidDecl() || !Range ||
1956 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1957 LoopVar->setInvalidDecl();
1961 // Build auto && __range = range-init
1962 SourceLocation RangeLoc = Range->getLocStart();
1963 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1964 Context.getAutoRRefDeductType(),
1966 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1967 diag::err_for_range_deduction_failure)) {
1968 LoopVar->setInvalidDecl();
1972 // Claim the type doesn't contain auto: we've already done the checking.
1973 DeclGroupPtrTy RangeGroup =
1974 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1975 /*TypeMayContainAuto=*/ false);
1976 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1977 if (RangeDecl.isInvalid()) {
1978 LoopVar->setInvalidDecl();
1982 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1983 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1984 /*Inc=*/nullptr, DS, RParenLoc, Kind);
1987 /// \brief Create the initialization, compare, and increment steps for
1988 /// the range-based for loop expression.
1989 /// This function does not handle array-based for loops,
1990 /// which are created in Sema::BuildCXXForRangeStmt.
1992 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1993 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1994 /// CandidateSet and BEF are set and some non-success value is returned on
1996 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1997 Expr *BeginRange, Expr *EndRange,
2001 SourceLocation ColonLoc,
2002 OverloadCandidateSet *CandidateSet,
2003 ExprResult *BeginExpr,
2004 ExprResult *EndExpr,
2005 Sema::BeginEndFunction *BEF) {
2006 DeclarationNameInfo BeginNameInfo(
2007 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2008 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2011 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2012 Sema::LookupMemberName);
2013 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2015 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2016 // - if _RangeT is a class type, the unqualified-ids begin and end are
2017 // looked up in the scope of class _RangeT as if by class member access
2018 // lookup (3.4.5), and if either (or both) finds at least one
2019 // declaration, begin-expr and end-expr are __range.begin() and
2020 // __range.end(), respectively;
2021 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2022 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2024 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2025 SourceLocation RangeLoc = BeginVar->getLocation();
2026 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2028 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2029 << RangeLoc << BeginRange->getType() << *BEF;
2030 return Sema::FRS_DiagnosticIssued;
2033 // - otherwise, begin-expr and end-expr are begin(__range) and
2034 // end(__range), respectively, where begin and end are looked up with
2035 // argument-dependent lookup (3.4.2). For the purposes of this name
2036 // lookup, namespace std is an associated namespace.
2040 *BEF = Sema::BEF_begin;
2041 Sema::ForRangeStatus RangeStatus =
2042 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2043 Sema::BEF_begin, BeginNameInfo,
2044 BeginMemberLookup, CandidateSet,
2045 BeginRange, BeginExpr);
2047 if (RangeStatus != Sema::FRS_Success)
2049 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2050 diag::err_for_range_iter_deduction_failure)) {
2051 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2052 return Sema::FRS_DiagnosticIssued;
2055 *BEF = Sema::BEF_end;
2057 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2058 Sema::BEF_end, EndNameInfo,
2059 EndMemberLookup, CandidateSet,
2061 if (RangeStatus != Sema::FRS_Success)
2063 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2064 diag::err_for_range_iter_deduction_failure)) {
2065 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2066 return Sema::FRS_DiagnosticIssued;
2068 return Sema::FRS_Success;
2071 /// Speculatively attempt to dereference an invalid range expression.
2072 /// If the attempt fails, this function will return a valid, null StmtResult
2073 /// and emit no diagnostics.
2074 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2075 SourceLocation ForLoc,
2077 SourceLocation ColonLoc,
2079 SourceLocation RangeLoc,
2080 SourceLocation RParenLoc) {
2081 // Determine whether we can rebuild the for-range statement with a
2082 // dereferenced range expression.
2083 ExprResult AdjustedRange;
2085 Sema::SFINAETrap Trap(SemaRef);
2087 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2088 if (AdjustedRange.isInvalid())
2089 return StmtResult();
2092 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2093 AdjustedRange.get(), RParenLoc,
2096 return StmtResult();
2099 // The attempt to dereference worked well enough that it could produce a valid
2100 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2101 // case there are any other (non-fatal) problems with it.
2102 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2103 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2104 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2105 AdjustedRange.get(), RParenLoc,
2106 Sema::BFRK_Rebuild);
2110 /// RAII object to automatically invalidate a declaration if an error occurs.
2111 struct InvalidateOnErrorScope {
2112 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2113 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2114 ~InvalidateOnErrorScope() {
2115 if (Enabled && Trap.hasErrorOccurred())
2116 D->setInvalidDecl();
2119 DiagnosticErrorTrap Trap;
2125 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2127 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2128 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2129 Expr *Inc, Stmt *LoopVarDecl,
2130 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2131 Scope *S = getCurScope();
2133 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2134 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2135 QualType RangeVarType = RangeVar->getType();
2137 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2138 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2140 // If we hit any errors, mark the loop variable as invalid if its type
2142 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2143 LoopVar->getType()->isUndeducedType());
2145 StmtResult BeginEndDecl = BeginEnd;
2146 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2148 if (RangeVarType->isDependentType()) {
2149 // The range is implicitly used as a placeholder when it is dependent.
2150 RangeVar->markUsed(Context);
2152 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2153 // them in properly when we instantiate the loop.
2154 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2155 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2156 } else if (!BeginEndDecl.get()) {
2157 SourceLocation RangeLoc = RangeVar->getLocation();
2159 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2161 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2162 VK_LValue, ColonLoc);
2163 if (BeginRangeRef.isInvalid())
2166 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2167 VK_LValue, ColonLoc);
2168 if (EndRangeRef.isInvalid())
2171 QualType AutoType = Context.getAutoDeductType();
2172 Expr *Range = RangeVar->getInit();
2175 QualType RangeType = Range->getType();
2177 if (RequireCompleteType(RangeLoc, RangeType,
2178 diag::err_for_range_incomplete_type))
2181 // Build auto __begin = begin-expr, __end = end-expr.
2182 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2184 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2187 // Build begin-expr and end-expr and attach to __begin and __end variables.
2188 ExprResult BeginExpr, EndExpr;
2189 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2190 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2191 // __range + __bound, respectively, where __bound is the array bound. If
2192 // _RangeT is an array of unknown size or an array of incomplete type,
2193 // the program is ill-formed;
2195 // begin-expr is __range.
2196 BeginExpr = BeginRangeRef;
2197 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2198 diag::err_for_range_iter_deduction_failure)) {
2199 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2203 // Find the array bound.
2204 ExprResult BoundExpr;
2205 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2206 BoundExpr = IntegerLiteral::Create(
2207 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2208 else if (const VariableArrayType *VAT =
2209 dyn_cast<VariableArrayType>(UnqAT))
2210 BoundExpr = VAT->getSizeExpr();
2212 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2213 // UnqAT is not incomplete and Range is not type-dependent.
2214 llvm_unreachable("Unexpected array type in for-range");
2217 // end-expr is __range + __bound.
2218 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2220 if (EndExpr.isInvalid())
2222 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2223 diag::err_for_range_iter_deduction_failure)) {
2224 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2228 OverloadCandidateSet CandidateSet(RangeLoc,
2229 OverloadCandidateSet::CSK_Normal);
2230 Sema::BeginEndFunction BEFFailure;
2231 ForRangeStatus RangeStatus =
2232 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2233 EndRangeRef.get(), RangeType,
2234 BeginVar, EndVar, ColonLoc, &CandidateSet,
2235 &BeginExpr, &EndExpr, &BEFFailure);
2237 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2238 BEFFailure == BEF_begin) {
2239 // If the range is being built from an array parameter, emit a
2240 // a diagnostic that it is being treated as a pointer.
2241 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2242 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2243 QualType ArrayTy = PVD->getOriginalType();
2244 QualType PointerTy = PVD->getType();
2245 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2246 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2247 << RangeLoc << PVD << ArrayTy << PointerTy;
2248 Diag(PVD->getLocation(), diag::note_declared_at);
2254 // If building the range failed, try dereferencing the range expression
2255 // unless a diagnostic was issued or the end function is problematic.
2256 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2257 LoopVarDecl, ColonLoc,
2260 if (SR.isInvalid() || SR.isUsable())
2264 // Otherwise, emit diagnostics if we haven't already.
2265 if (RangeStatus == FRS_NoViableFunction) {
2266 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2267 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2268 << RangeLoc << Range->getType() << BEFFailure;
2269 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2271 // Return an error if no fix was discovered.
2272 if (RangeStatus != FRS_Success)
2276 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2277 "invalid range expression in for loop");
2279 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2280 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2281 if (!Context.hasSameType(BeginType, EndType)) {
2282 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2283 << BeginType << EndType;
2284 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2285 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2288 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2289 // Claim the type doesn't contain auto: we've already done the checking.
2290 DeclGroupPtrTy BeginEndGroup =
2291 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
2292 /*TypeMayContainAuto=*/ false);
2293 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2295 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2296 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2297 VK_LValue, ColonLoc);
2298 if (BeginRef.isInvalid())
2301 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2302 VK_LValue, ColonLoc);
2303 if (EndRef.isInvalid())
2306 // Build and check __begin != __end expression.
2307 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2308 BeginRef.get(), EndRef.get());
2309 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2310 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2311 if (NotEqExpr.isInvalid()) {
2312 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2313 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2314 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2315 if (!Context.hasSameType(BeginType, EndType))
2316 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2320 // Build and check ++__begin expression.
2321 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2322 VK_LValue, ColonLoc);
2323 if (BeginRef.isInvalid())
2326 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2327 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2328 if (IncrExpr.isInvalid()) {
2329 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2330 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2331 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2335 // Build and check *__begin expression.
2336 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2337 VK_LValue, ColonLoc);
2338 if (BeginRef.isInvalid())
2341 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2342 if (DerefExpr.isInvalid()) {
2343 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2344 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2345 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2349 // Attach *__begin as initializer for VD. Don't touch it if we're just
2350 // trying to determine whether this would be a valid range.
2351 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2352 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2353 /*TypeMayContainAuto=*/true);
2354 if (LoopVar->isInvalidDecl())
2355 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2359 // Don't bother to actually allocate the result if we're just trying to
2360 // determine whether it would be valid.
2361 if (Kind == BFRK_Check)
2362 return StmtResult();
2364 return new (Context) CXXForRangeStmt(
2365 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2366 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
2369 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2371 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2374 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2376 ForStmt->setBody(B);
2380 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2381 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2382 /// body cannot be performed until after the type of the range variable is
2384 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2388 if (isa<ObjCForCollectionStmt>(S))
2389 return FinishObjCForCollectionStmt(S, B);
2391 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2392 ForStmt->setBody(B);
2394 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2395 diag::warn_empty_range_based_for_body);
2400 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2401 SourceLocation LabelLoc,
2402 LabelDecl *TheDecl) {
2403 getCurFunction()->setHasBranchIntoScope();
2404 TheDecl->markUsed(Context);
2405 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2409 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2411 // Convert operand to void*
2412 if (!E->isTypeDependent()) {
2413 QualType ETy = E->getType();
2414 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2415 ExprResult ExprRes = E;
2416 AssignConvertType ConvTy =
2417 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2418 if (ExprRes.isInvalid())
2421 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2425 ExprResult ExprRes = ActOnFinishFullExpr(E);
2426 if (ExprRes.isInvalid())
2430 getCurFunction()->setHasIndirectGoto();
2432 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2436 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2437 Scope *S = CurScope->getContinueParent();
2439 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2440 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2443 return new (Context) ContinueStmt(ContinueLoc);
2447 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2448 Scope *S = CurScope->getBreakParent();
2450 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2451 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2453 if (S->isOpenMPLoopScope())
2454 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2457 return new (Context) BreakStmt(BreakLoc);
2460 /// \brief Determine whether the given expression is a candidate for
2461 /// copy elision in either a return statement or a throw expression.
2463 /// \param ReturnType If we're determining the copy elision candidate for
2464 /// a return statement, this is the return type of the function. If we're
2465 /// determining the copy elision candidate for a throw expression, this will
2468 /// \param E The expression being returned from the function or block, or
2471 /// \param AllowFunctionParameter Whether we allow function parameters to
2472 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2473 /// we re-use this logic to determine whether we should try to move as part of
2474 /// a return or throw (which does allow function parameters).
2476 /// \returns The NRVO candidate variable, if the return statement may use the
2477 /// NRVO, or NULL if there is no such candidate.
2478 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2480 bool AllowFunctionParameter) {
2481 if (!getLangOpts().CPlusPlus)
2484 // - in a return statement in a function [where] ...
2485 // ... the expression is the name of a non-volatile automatic object ...
2486 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2487 if (!DR || DR->refersToEnclosingVariableOrCapture())
2489 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2493 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2498 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2499 bool AllowFunctionParameter) {
2500 QualType VDType = VD->getType();
2501 // - in a return statement in a function with ...
2502 // ... a class return type ...
2503 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2504 if (!ReturnType->isRecordType())
2506 // ... the same cv-unqualified type as the function return type ...
2507 if (!VDType->isDependentType() &&
2508 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2512 // ...object (other than a function or catch-clause parameter)...
2513 if (VD->getKind() != Decl::Var &&
2514 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2516 if (VD->isExceptionVariable()) return false;
2519 if (!VD->hasLocalStorage()) return false;
2521 // ...non-volatile...
2522 if (VD->getType().isVolatileQualified()) return false;
2524 // __block variables can't be allocated in a way that permits NRVO.
2525 if (VD->hasAttr<BlocksAttr>()) return false;
2527 // Variables with higher required alignment than their type's ABI
2528 // alignment cannot use NRVO.
2529 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2530 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2536 /// \brief Perform the initialization of a potentially-movable value, which
2537 /// is the result of return value.
2539 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2540 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2541 /// then falls back to treating them as lvalues if that failed.
2543 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2544 const VarDecl *NRVOCandidate,
2545 QualType ResultType,
2548 // C++0x [class.copy]p33:
2549 // When the criteria for elision of a copy operation are met or would
2550 // be met save for the fact that the source object is a function
2551 // parameter, and the object to be copied is designated by an lvalue,
2552 // overload resolution to select the constructor for the copy is first
2553 // performed as if the object were designated by an rvalue.
2554 ExprResult Res = ExprError();
2556 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2557 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2558 Value->getType(), CK_NoOp, Value, VK_XValue);
2560 Expr *InitExpr = &AsRvalue;
2561 InitializationKind Kind
2562 = InitializationKind::CreateCopy(Value->getLocStart(),
2563 Value->getLocStart());
2564 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2566 // [...] If overload resolution fails, or if the type of the first
2567 // parameter of the selected constructor is not an rvalue reference
2568 // to the object's type (possibly cv-qualified), overload resolution
2569 // is performed again, considering the object as an lvalue.
2571 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2572 StepEnd = Seq.step_end();
2573 Step != StepEnd; ++Step) {
2574 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2577 CXXConstructorDecl *Constructor
2578 = cast<CXXConstructorDecl>(Step->Function.Function);
2580 const RValueReferenceType *RRefType
2581 = Constructor->getParamDecl(0)->getType()
2582 ->getAs<RValueReferenceType>();
2584 // If we don't meet the criteria, break out now.
2586 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2587 Context.getTypeDeclType(Constructor->getParent())))
2590 // Promote "AsRvalue" to the heap, since we now need this
2591 // expression node to persist.
2592 Value = ImplicitCastExpr::Create(Context, Value->getType(),
2593 CK_NoOp, Value, nullptr, VK_XValue);
2595 // Complete type-checking the initialization of the return type
2596 // using the constructor we found.
2597 Res = Seq.Perform(*this, Entity, Kind, Value);
2602 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2603 // above, or overload resolution failed. Either way, we need to try
2604 // (again) now with the return value expression as written.
2605 if (Res.isInvalid())
2606 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2611 /// \brief Determine whether the declared return type of the specified function
2612 /// contains 'auto'.
2613 static bool hasDeducedReturnType(FunctionDecl *FD) {
2614 const FunctionProtoType *FPT =
2615 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2616 return FPT->getReturnType()->isUndeducedType();
2619 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2620 /// for capturing scopes.
2623 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2624 // If this is the first return we've seen, infer the return type.
2625 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2626 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2627 QualType FnRetType = CurCap->ReturnType;
2628 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2630 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2631 // In C++1y, the return type may involve 'auto'.
2632 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2633 FunctionDecl *FD = CurLambda->CallOperator;
2634 if (CurCap->ReturnType.isNull())
2635 CurCap->ReturnType = FD->getReturnType();
2637 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2638 assert(AT && "lost auto type from lambda return type");
2639 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2640 FD->setInvalidDecl();
2643 CurCap->ReturnType = FnRetType = FD->getReturnType();
2644 } else if (CurCap->HasImplicitReturnType) {
2645 // For blocks/lambdas with implicit return types, we check each return
2646 // statement individually, and deduce the common return type when the block
2647 // or lambda is completed.
2648 // FIXME: Fold this into the 'auto' codepath above.
2649 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2650 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2651 if (Result.isInvalid())
2653 RetValExp = Result.get();
2655 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2656 // when deducing a return type for a lambda-expression (or by extension
2657 // for a block). These rules differ from the stated C++11 rules only in
2658 // that they remove top-level cv-qualifiers.
2659 if (!CurContext->isDependentContext())
2660 FnRetType = RetValExp->getType().getUnqualifiedType();
2662 FnRetType = CurCap->ReturnType = Context.DependentTy;
2665 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2666 // initializer list, because it is not an expression (even
2667 // though we represent it as one). We still deduce 'void'.
2668 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2669 << RetValExp->getSourceRange();
2672 FnRetType = Context.VoidTy;
2675 // Although we'll properly infer the type of the block once it's completed,
2676 // make sure we provide a return type now for better error recovery.
2677 if (CurCap->ReturnType.isNull())
2678 CurCap->ReturnType = FnRetType;
2680 assert(!FnRetType.isNull());
2682 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2683 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2684 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2687 } else if (CapturedRegionScopeInfo *CurRegion =
2688 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2689 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2692 assert(CurLambda && "unknown kind of captured scope");
2693 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2694 ->getNoReturnAttr()) {
2695 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2700 // Otherwise, verify that this result type matches the previous one. We are
2701 // pickier with blocks than for normal functions because we don't have GCC
2702 // compatibility to worry about here.
2703 const VarDecl *NRVOCandidate = nullptr;
2704 if (FnRetType->isDependentType()) {
2705 // Delay processing for now. TODO: there are lots of dependent
2706 // types we can conclusively prove aren't void.
2707 } else if (FnRetType->isVoidType()) {
2708 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2709 !(getLangOpts().CPlusPlus &&
2710 (RetValExp->isTypeDependent() ||
2711 RetValExp->getType()->isVoidType()))) {
2712 if (!getLangOpts().CPlusPlus &&
2713 RetValExp->getType()->isVoidType())
2714 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2716 Diag(ReturnLoc, diag::err_return_block_has_expr);
2717 RetValExp = nullptr;
2720 } else if (!RetValExp) {
2721 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2722 } else if (!RetValExp->isTypeDependent()) {
2723 // we have a non-void block with an expression, continue checking
2725 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2726 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2729 // In C++ the return statement is handled via a copy initialization.
2730 // the C version of which boils down to CheckSingleAssignmentConstraints.
2731 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2732 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2734 NRVOCandidate != nullptr);
2735 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2736 FnRetType, RetValExp);
2737 if (Res.isInvalid()) {
2738 // FIXME: Cleanup temporaries here, anyway?
2741 RetValExp = Res.get();
2742 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2744 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2748 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2751 RetValExp = ER.get();
2753 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2756 // If we need to check for the named return value optimization,
2757 // or if we need to infer the return type,
2758 // save the return statement in our scope for later processing.
2759 if (CurCap->HasImplicitReturnType || NRVOCandidate)
2760 FunctionScopes.back()->Returns.push_back(Result);
2766 /// \brief Marks all typedefs in all local classes in a type referenced.
2768 /// In a function like
2770 /// struct S { typedef int a; };
2774 /// the local type escapes and could be referenced in some TUs but not in
2775 /// others. Pretend that all local typedefs are always referenced, to not warn
2776 /// on this. This isn't necessary if f has internal linkage, or the typedef
2778 class LocalTypedefNameReferencer
2779 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2781 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2782 bool VisitRecordType(const RecordType *RT);
2786 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2787 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2788 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2789 R->isDependentType())
2791 for (auto *TmpD : R->decls())
2792 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2793 if (T->getAccess() != AS_private || R->hasFriends())
2794 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2799 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
2800 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
2801 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2802 TL = ATL.getModifiedLoc().IgnoreParens();
2803 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
2806 /// Deduce the return type for a function from a returned expression, per
2807 /// C++1y [dcl.spec.auto]p6.
2808 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2809 SourceLocation ReturnLoc,
2812 TypeLoc OrigResultType = getReturnTypeLoc(FD);
2815 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2816 // If the deduction is for a return statement and the initializer is
2817 // a braced-init-list, the program is ill-formed.
2818 Diag(RetExpr->getExprLoc(),
2819 getCurLambda() ? diag::err_lambda_return_init_list
2820 : diag::err_auto_fn_return_init_list)
2821 << RetExpr->getSourceRange();
2825 if (FD->isDependentContext()) {
2826 // C++1y [dcl.spec.auto]p12:
2827 // Return type deduction [...] occurs when the definition is
2828 // instantiated even if the function body contains a return
2829 // statement with a non-type-dependent operand.
2830 assert(AT->isDeduced() && "should have deduced to dependent type");
2832 } else if (RetExpr) {
2833 // If the deduction is for a return statement and the initializer is
2834 // a braced-init-list, the program is ill-formed.
2835 if (isa<InitListExpr>(RetExpr)) {
2836 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2840 // Otherwise, [...] deduce a value for U using the rules of template
2841 // argument deduction.
2842 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2844 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2845 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2846 << OrigResultType.getType() << RetExpr->getType();
2848 if (DAR != DAR_Succeeded)
2851 // If a local type is part of the returned type, mark its fields as
2853 LocalTypedefNameReferencer Referencer(*this);
2854 Referencer.TraverseType(RetExpr->getType());
2856 // In the case of a return with no operand, the initializer is considered
2859 // Deduction here can only succeed if the return type is exactly 'cv auto'
2860 // or 'decltype(auto)', so just check for that case directly.
2861 if (!OrigResultType.getType()->getAs<AutoType>()) {
2862 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2863 << OrigResultType.getType();
2866 // We always deduce U = void in this case.
2867 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2868 if (Deduced.isNull())
2872 // If a function with a declared return type that contains a placeholder type
2873 // has multiple return statements, the return type is deduced for each return
2874 // statement. [...] if the type deduced is not the same in each deduction,
2875 // the program is ill-formed.
2876 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2877 AutoType *NewAT = Deduced->getContainedAutoType();
2878 if (!FD->isDependentContext() &&
2879 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2880 const LambdaScopeInfo *LambdaSI = getCurLambda();
2881 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2882 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2883 << NewAT->getDeducedType() << AT->getDeducedType()
2884 << true /*IsLambda*/;
2886 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2887 << (AT->isDecltypeAuto() ? 1 : 0)
2888 << NewAT->getDeducedType() << AT->getDeducedType();
2892 } else if (!FD->isInvalidDecl()) {
2893 // Update all declarations of the function to have the deduced return type.
2894 Context.adjustDeducedFunctionResultType(FD, Deduced);
2901 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2903 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2904 if (R.isInvalid()) {
2909 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2910 CurScope->addNRVOCandidate(VD);
2912 CurScope->setNoNRVO();
2918 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2919 // Check for unexpanded parameter packs.
2920 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2923 if (isa<CapturingScopeInfo>(getCurFunction()))
2924 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2927 QualType RelatedRetType;
2928 const AttrVec *Attrs = nullptr;
2929 bool isObjCMethod = false;
2931 if (const FunctionDecl *FD = getCurFunctionDecl()) {
2932 FnRetType = FD->getReturnType();
2934 Attrs = &FD->getAttrs();
2935 if (FD->isNoReturn())
2936 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2937 << FD->getDeclName();
2938 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2939 FnRetType = MD->getReturnType();
2940 isObjCMethod = true;
2942 Attrs = &MD->getAttrs();
2943 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2944 // In the implementation of a method with a related return type, the
2945 // type used to type-check the validity of return statements within the
2946 // method body is a pointer to the type of the class being implemented.
2947 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2948 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2950 } else // If we don't have a function/method context, bail.
2953 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2955 if (getLangOpts().CPlusPlus14) {
2956 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2957 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2958 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2959 FD->setInvalidDecl();
2962 FnRetType = FD->getReturnType();
2967 bool HasDependentReturnType = FnRetType->isDependentType();
2969 ReturnStmt *Result = nullptr;
2970 if (FnRetType->isVoidType()) {
2972 if (isa<InitListExpr>(RetValExp)) {
2973 // We simply never allow init lists as the return value of void
2974 // functions. This is compatible because this was never allowed before,
2975 // so there's no legacy code to deal with.
2976 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2977 int FunctionKind = 0;
2978 if (isa<ObjCMethodDecl>(CurDecl))
2980 else if (isa<CXXConstructorDecl>(CurDecl))
2982 else if (isa<CXXDestructorDecl>(CurDecl))
2985 Diag(ReturnLoc, diag::err_return_init_list)
2986 << CurDecl->getDeclName() << FunctionKind
2987 << RetValExp->getSourceRange();
2989 // Drop the expression.
2990 RetValExp = nullptr;
2991 } else if (!RetValExp->isTypeDependent()) {
2992 // C99 6.8.6.4p1 (ext_ since GCC warns)
2993 unsigned D = diag::ext_return_has_expr;
2994 if (RetValExp->getType()->isVoidType()) {
2995 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2996 if (isa<CXXConstructorDecl>(CurDecl) ||
2997 isa<CXXDestructorDecl>(CurDecl))
2998 D = diag::err_ctor_dtor_returns_void;
3000 D = diag::ext_return_has_void_expr;
3003 ExprResult Result = RetValExp;
3004 Result = IgnoredValueConversions(Result.get());
3005 if (Result.isInvalid())
3007 RetValExp = Result.get();
3008 RetValExp = ImpCastExprToType(RetValExp,
3009 Context.VoidTy, CK_ToVoid).get();
3011 // return of void in constructor/destructor is illegal in C++.
3012 if (D == diag::err_ctor_dtor_returns_void) {
3013 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3015 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3016 << RetValExp->getSourceRange();
3018 // return (some void expression); is legal in C++.
3019 else if (D != diag::ext_return_has_void_expr ||
3020 !getLangOpts().CPlusPlus) {
3021 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3023 int FunctionKind = 0;
3024 if (isa<ObjCMethodDecl>(CurDecl))
3026 else if (isa<CXXConstructorDecl>(CurDecl))
3028 else if (isa<CXXDestructorDecl>(CurDecl))
3032 << CurDecl->getDeclName() << FunctionKind
3033 << RetValExp->getSourceRange();
3038 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3041 RetValExp = ER.get();
3045 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3046 } else if (!RetValExp && !HasDependentReturnType) {
3047 FunctionDecl *FD = getCurFunctionDecl();
3050 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3051 // C++11 [stmt.return]p2
3052 DiagID = diag::err_constexpr_return_missing_expr;
3053 FD->setInvalidDecl();
3054 } else if (getLangOpts().C99) {
3055 // C99 6.8.6.4p1 (ext_ since GCC warns)
3056 DiagID = diag::ext_return_missing_expr;
3059 DiagID = diag::warn_return_missing_expr;
3063 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3065 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3067 Result = new (Context) ReturnStmt(ReturnLoc);
3069 assert(RetValExp || HasDependentReturnType);
3070 const VarDecl *NRVOCandidate = nullptr;
3072 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3074 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3075 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3078 // In C++ the return statement is handled via a copy initialization,
3079 // the C version of which boils down to CheckSingleAssignmentConstraints.
3081 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3082 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3083 // we have a non-void function with an expression, continue checking
3084 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3086 NRVOCandidate != nullptr);
3087 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3088 RetType, RetValExp);
3089 if (Res.isInvalid()) {
3090 // FIXME: Clean up temporaries here anyway?
3093 RetValExp = Res.getAs<Expr>();
3095 // If we have a related result type, we need to implicitly
3096 // convert back to the formal result type. We can't pretend to
3097 // initialize the result again --- we might end double-retaining
3098 // --- so instead we initialize a notional temporary.
3099 if (!RelatedRetType.isNull()) {
3100 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3102 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3103 if (Res.isInvalid()) {
3104 // FIXME: Clean up temporaries here anyway?
3107 RetValExp = Res.getAs<Expr>();
3110 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3111 getCurFunctionDecl());
3115 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3118 RetValExp = ER.get();
3120 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3123 // If we need to check for the named return value optimization, save the
3124 // return statement in our scope for later processing.
3125 if (Result->getNRVOCandidate())
3126 FunctionScopes.back()->Returns.push_back(Result);
3132 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3133 SourceLocation RParen, Decl *Parm,
3135 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3136 if (Var && Var->isInvalidDecl())
3139 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3143 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3144 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3148 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3149 MultiStmtArg CatchStmts, Stmt *Finally) {
3150 if (!getLangOpts().ObjCExceptions)
3151 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3153 getCurFunction()->setHasBranchProtectedScope();
3154 unsigned NumCatchStmts = CatchStmts.size();
3155 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3156 NumCatchStmts, Finally);
3159 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3161 ExprResult Result = DefaultLvalueConversion(Throw);
3162 if (Result.isInvalid())
3165 Result = ActOnFinishFullExpr(Result.get());
3166 if (Result.isInvalid())
3168 Throw = Result.get();
3170 QualType ThrowType = Throw->getType();
3171 // Make sure the expression type is an ObjC pointer or "void *".
3172 if (!ThrowType->isDependentType() &&
3173 !ThrowType->isObjCObjectPointerType()) {
3174 const PointerType *PT = ThrowType->getAs<PointerType>();
3175 if (!PT || !PT->getPointeeType()->isVoidType())
3176 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3177 << Throw->getType() << Throw->getSourceRange());
3181 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3185 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3187 if (!getLangOpts().ObjCExceptions)
3188 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3191 // @throw without an expression designates a rethrow (which much occur
3192 // in the context of an @catch clause).
3193 Scope *AtCatchParent = CurScope;
3194 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3195 AtCatchParent = AtCatchParent->getParent();
3197 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3199 return BuildObjCAtThrowStmt(AtLoc, Throw);
3203 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3204 ExprResult result = DefaultLvalueConversion(operand);
3205 if (result.isInvalid())
3207 operand = result.get();
3209 // Make sure the expression type is an ObjC pointer or "void *".
3210 QualType type = operand->getType();
3211 if (!type->isDependentType() &&
3212 !type->isObjCObjectPointerType()) {
3213 const PointerType *pointerType = type->getAs<PointerType>();
3214 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3215 if (getLangOpts().CPlusPlus) {
3216 if (RequireCompleteType(atLoc, type,
3217 diag::err_incomplete_receiver_type))
3218 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3219 << type << operand->getSourceRange();
3221 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3222 if (!result.isUsable())
3223 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3224 << type << operand->getSourceRange();
3226 operand = result.get();
3228 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3229 << type << operand->getSourceRange();
3234 // The operand to @synchronized is a full-expression.
3235 return ActOnFinishFullExpr(operand);
3239 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3241 // We can't jump into or indirect-jump out of a @synchronized block.
3242 getCurFunction()->setHasBranchProtectedScope();
3243 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3246 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3247 /// and creates a proper catch handler from them.
3249 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3250 Stmt *HandlerBlock) {
3251 // There's nothing to test that ActOnExceptionDecl didn't already test.
3252 return new (Context)
3253 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3257 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3258 getCurFunction()->setHasBranchProtectedScope();
3259 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3264 class TypeWithHandler {
3268 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3269 : t(type), stmt(statement) {}
3271 // An arbitrary order is fine as long as it places identical
3272 // types next to each other.
3273 bool operator<(const TypeWithHandler &y) const {
3274 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3276 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3279 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3282 bool operator==(const TypeWithHandler& other) const {
3283 return t == other.t;
3286 CXXCatchStmt *getCatchStmt() const { return stmt; }
3287 SourceLocation getTypeSpecStartLoc() const {
3288 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3294 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3295 /// handlers and creates a try statement from them.
3296 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3297 ArrayRef<Stmt *> Handlers) {
3298 // Don't report an error if 'try' is used in system headers.
3299 if (!getLangOpts().CXXExceptions &&
3300 !getSourceManager().isInSystemHeader(TryLoc))
3301 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3303 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3304 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3306 const unsigned NumHandlers = Handlers.size();
3307 assert(NumHandlers > 0 &&
3308 "The parser shouldn't call this if there are no handlers.");
3310 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3312 for (unsigned i = 0; i < NumHandlers; ++i) {
3313 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3314 if (!Handler->getExceptionDecl()) {
3315 if (i < NumHandlers - 1)
3316 return StmtError(Diag(Handler->getLocStart(),
3317 diag::err_early_catch_all));
3322 const QualType CaughtType = Handler->getCaughtType();
3323 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3324 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3327 // Detect handlers for the same type as an earlier one.
3328 if (NumHandlers > 1) {
3329 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3331 TypeWithHandler prev = TypesWithHandlers[0];
3332 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3333 TypeWithHandler curr = TypesWithHandlers[i];
3336 Diag(curr.getTypeSpecStartLoc(),
3337 diag::warn_exception_caught_by_earlier_handler)
3338 << curr.getCatchStmt()->getCaughtType().getAsString();
3339 Diag(prev.getTypeSpecStartLoc(),
3340 diag::note_previous_exception_handler)
3341 << prev.getCatchStmt()->getCaughtType().getAsString();
3348 getCurFunction()->setHasBranchProtectedScope();
3350 // FIXME: We should detect handlers that cannot catch anything because an
3351 // earlier handler catches a superclass. Need to find a method that is not
3352 // quadratic for this.
3353 // Neither of these are explicitly forbidden, but every compiler detects them
3356 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3360 Sema::ActOnSEHTryBlock(bool IsCXXTry,
3361 SourceLocation TryLoc,
3364 assert(TryBlock && Handler);
3366 getCurFunction()->setHasBranchProtectedScope();
3368 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
3372 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3375 assert(FilterExpr && Block);
3377 if(!FilterExpr->getType()->isIntegerType()) {
3378 return StmtError(Diag(FilterExpr->getExprLoc(),
3379 diag::err_filter_expression_integral)
3380 << FilterExpr->getType());
3383 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3387 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3390 return SEHFinallyStmt::Create(Context,Loc,Block);
3394 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3395 Scope *SEHTryParent = CurScope;
3396 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3397 SEHTryParent = SEHTryParent->getParent();
3399 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3401 return new (Context) SEHLeaveStmt(Loc);
3404 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3406 NestedNameSpecifierLoc QualifierLoc,
3407 DeclarationNameInfo NameInfo,
3410 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3411 QualifierLoc, NameInfo,
3412 cast<CompoundStmt>(Nested));
3416 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3419 UnqualifiedId &Name,
3421 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3422 SS.getWithLocInContext(Context),
3423 GetNameFromUnqualifiedId(Name),
3428 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3429 unsigned NumParams) {
3430 DeclContext *DC = CurContext;
3431 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3432 DC = DC->getParent();
3434 RecordDecl *RD = nullptr;
3435 if (getLangOpts().CPlusPlus)
3436 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3439 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3441 RD->setCapturedRecord();
3444 RD->startDefinition();
3446 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3447 CD = CapturedDecl::Create(Context, CurContext, NumParams);
3452 static void buildCapturedStmtCaptureList(
3453 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3454 SmallVectorImpl<Expr *> &CaptureInits,
3455 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3457 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3458 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3460 if (Cap->isThisCapture()) {
3461 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3462 CapturedStmt::VCK_This));
3463 CaptureInits.push_back(Cap->getInitExpr());
3465 } else if (Cap->isVLATypeCapture()) {
3467 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3468 CaptureInits.push_back(nullptr);
3472 assert(Cap->isReferenceCapture() &&
3473 "non-reference capture not yet implemented");
3475 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3476 CapturedStmt::VCK_ByRef,
3477 Cap->getVariable()));
3478 CaptureInits.push_back(Cap->getInitExpr());
3482 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3483 CapturedRegionKind Kind,
3484 unsigned NumParams) {
3485 CapturedDecl *CD = nullptr;
3486 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3488 // Build the context parameter
3489 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3490 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3491 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3492 ImplicitParamDecl *Param
3493 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3496 CD->setContextParam(0, Param);
3498 // Enter the capturing scope for this captured region.
3499 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3502 PushDeclContext(CurScope, CD);
3506 PushExpressionEvaluationContext(PotentiallyEvaluated);
3509 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3510 CapturedRegionKind Kind,
3511 ArrayRef<CapturedParamNameType> Params) {
3512 CapturedDecl *CD = nullptr;
3513 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3515 // Build the context parameter
3516 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3517 bool ContextIsFound = false;
3518 unsigned ParamNum = 0;
3519 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3521 I != E; ++I, ++ParamNum) {
3522 if (I->second.isNull()) {
3523 assert(!ContextIsFound &&
3524 "null type has been found already for '__context' parameter");
3525 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3526 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3527 ImplicitParamDecl *Param
3528 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3530 CD->setContextParam(ParamNum, Param);
3531 ContextIsFound = true;
3533 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3534 ImplicitParamDecl *Param
3535 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3537 CD->setParam(ParamNum, Param);
3540 assert(ContextIsFound && "no null type for '__context' parameter");
3541 if (!ContextIsFound) {
3542 // Add __context implicitly if it is not specified.
3543 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3544 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3545 ImplicitParamDecl *Param =
3546 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3548 CD->setContextParam(ParamNum, Param);
3550 // Enter the capturing scope for this captured region.
3551 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3554 PushDeclContext(CurScope, CD);
3558 PushExpressionEvaluationContext(PotentiallyEvaluated);
3561 void Sema::ActOnCapturedRegionError() {
3562 DiscardCleanupsInEvaluationContext();
3563 PopExpressionEvaluationContext();
3565 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3566 RecordDecl *Record = RSI->TheRecordDecl;
3567 Record->setInvalidDecl();
3569 SmallVector<Decl*, 4> Fields(Record->fields());
3570 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3571 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3574 PopFunctionScopeInfo();
3577 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3578 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3580 SmallVector<CapturedStmt::Capture, 4> Captures;
3581 SmallVector<Expr *, 4> CaptureInits;
3582 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3584 CapturedDecl *CD = RSI->TheCapturedDecl;
3585 RecordDecl *RD = RSI->TheRecordDecl;
3587 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3588 RSI->CapRegionKind, Captures,
3589 CaptureInits, CD, RD);
3591 CD->setBody(Res->getCapturedStmt());
3592 RD->completeDefinition();
3594 DiscardCleanupsInEvaluationContext();
3595 PopExpressionEvaluationContext();
3598 PopFunctionScopeInfo();