xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaStmt.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
10b57cec5SDimitry Andric //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file implements semantic analysis for statements.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/Sema/Ownership.h"
140b57cec5SDimitry Andric #include "clang/Sema/SemaInternal.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
160b57cec5SDimitry Andric #include "clang/AST/ASTDiagnostic.h"
170b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
180b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
190b57cec5SDimitry Andric #include "clang/AST/CXXInheritance.h"
200b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
210b57cec5SDimitry Andric #include "clang/AST/EvaluatedExprVisitor.h"
220b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
230b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h"
240b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
250b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
260b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h"
270b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
280b57cec5SDimitry Andric #include "clang/AST/TypeOrdering.h"
290b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
300b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
310b57cec5SDimitry Andric #include "clang/Sema/Initialization.h"
320b57cec5SDimitry Andric #include "clang/Sema/Lookup.h"
330b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
340b57cec5SDimitry Andric #include "clang/Sema/ScopeInfo.h"
350b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
360b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
370b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
380b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
390b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
400b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric using namespace clang;
430b57cec5SDimitry Andric using namespace sema;
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
460b57cec5SDimitry Andric   if (FE.isInvalid())
470b57cec5SDimitry Andric     return StmtError();
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric   FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
500b57cec5SDimitry Andric   if (FE.isInvalid())
510b57cec5SDimitry Andric     return StmtError();
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
540b57cec5SDimitry Andric   // void expression for its side effects.  Conversion to void allows any
550b57cec5SDimitry Andric   // operand, even incomplete types.
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric   // Same thing in for stmt first clause (when expr) and third clause.
580b57cec5SDimitry Andric   return StmtResult(FE.getAs<Stmt>());
590b57cec5SDimitry Andric }
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric StmtResult Sema::ActOnExprStmtError() {
630b57cec5SDimitry Andric   DiscardCleanupsInEvaluationContext();
640b57cec5SDimitry Andric   return StmtError();
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
680b57cec5SDimitry Andric                                bool HasLeadingEmptyMacro) {
690b57cec5SDimitry Andric   return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
700b57cec5SDimitry Andric }
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
730b57cec5SDimitry Andric                                SourceLocation EndLoc) {
740b57cec5SDimitry Andric   DeclGroupRef DG = dg.get();
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric   // If we have an invalid decl, just return an error.
770b57cec5SDimitry Andric   if (DG.isNull()) return StmtError();
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   return new (Context) DeclStmt(DG, StartLoc, EndLoc);
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
830b57cec5SDimitry Andric   DeclGroupRef DG = dg.get();
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric   // If we don't have a declaration, or we have an invalid declaration,
860b57cec5SDimitry Andric   // just return.
870b57cec5SDimitry Andric   if (DG.isNull() || !DG.isSingleDecl())
880b57cec5SDimitry Andric     return;
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   Decl *decl = DG.getSingleDecl();
910b57cec5SDimitry Andric   if (!decl || decl->isInvalidDecl())
920b57cec5SDimitry Andric     return;
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   // Only variable declarations are permitted.
950b57cec5SDimitry Andric   VarDecl *var = dyn_cast<VarDecl>(decl);
960b57cec5SDimitry Andric   if (!var) {
970b57cec5SDimitry Andric     Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
980b57cec5SDimitry Andric     decl->setInvalidDecl();
990b57cec5SDimitry Andric     return;
1000b57cec5SDimitry Andric   }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   // foreach variables are never actually initialized in the way that
1030b57cec5SDimitry Andric   // the parser came up with.
1040b57cec5SDimitry Andric   var->setInit(nullptr);
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   // In ARC, we don't need to retain the iteration variable of a fast
1070b57cec5SDimitry Andric   // enumeration loop.  Rather than actually trying to catch that
1080b57cec5SDimitry Andric   // during declaration processing, we remove the consequences here.
1090b57cec5SDimitry Andric   if (getLangOpts().ObjCAutoRefCount) {
1100b57cec5SDimitry Andric     QualType type = var->getType();
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric     // Only do this if we inferred the lifetime.  Inferred lifetime
1130b57cec5SDimitry Andric     // will show up as a local qualifier because explicit lifetime
1140b57cec5SDimitry Andric     // should have shown up as an AttributedType instead.
1150b57cec5SDimitry Andric     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
1160b57cec5SDimitry Andric       // Add 'const' and mark the variable as pseudo-strong.
1170b57cec5SDimitry Andric       var->setType(type.withConst());
1180b57cec5SDimitry Andric       var->setARCPseudoStrong(true);
1190b57cec5SDimitry Andric     }
1200b57cec5SDimitry Andric   }
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric /// Diagnose unused comparisons, both builtin and overloaded operators.
1240b57cec5SDimitry Andric /// For '==' and '!=', suggest fixits for '=' or '|='.
1250b57cec5SDimitry Andric ///
1260b57cec5SDimitry Andric /// Adding a cast to void (or other expression wrappers) will prevent the
1270b57cec5SDimitry Andric /// warning from firing.
1280b57cec5SDimitry Andric static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
1290b57cec5SDimitry Andric   SourceLocation Loc;
1300b57cec5SDimitry Andric   bool CanAssign;
1310b57cec5SDimitry Andric   enum { Equality, Inequality, Relational, ThreeWay } Kind;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
1340b57cec5SDimitry Andric     if (!Op->isComparisonOp())
1350b57cec5SDimitry Andric       return false;
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric     if (Op->getOpcode() == BO_EQ)
1380b57cec5SDimitry Andric       Kind = Equality;
1390b57cec5SDimitry Andric     else if (Op->getOpcode() == BO_NE)
1400b57cec5SDimitry Andric       Kind = Inequality;
1410b57cec5SDimitry Andric     else if (Op->getOpcode() == BO_Cmp)
1420b57cec5SDimitry Andric       Kind = ThreeWay;
1430b57cec5SDimitry Andric     else {
1440b57cec5SDimitry Andric       assert(Op->isRelationalOp());
1450b57cec5SDimitry Andric       Kind = Relational;
1460b57cec5SDimitry Andric     }
1470b57cec5SDimitry Andric     Loc = Op->getOperatorLoc();
1480b57cec5SDimitry Andric     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
1490b57cec5SDimitry Andric   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
1500b57cec5SDimitry Andric     switch (Op->getOperator()) {
1510b57cec5SDimitry Andric     case OO_EqualEqual:
1520b57cec5SDimitry Andric       Kind = Equality;
1530b57cec5SDimitry Andric       break;
1540b57cec5SDimitry Andric     case OO_ExclaimEqual:
1550b57cec5SDimitry Andric       Kind = Inequality;
1560b57cec5SDimitry Andric       break;
1570b57cec5SDimitry Andric     case OO_Less:
1580b57cec5SDimitry Andric     case OO_Greater:
1590b57cec5SDimitry Andric     case OO_GreaterEqual:
1600b57cec5SDimitry Andric     case OO_LessEqual:
1610b57cec5SDimitry Andric       Kind = Relational;
1620b57cec5SDimitry Andric       break;
1630b57cec5SDimitry Andric     case OO_Spaceship:
1640b57cec5SDimitry Andric       Kind = ThreeWay;
1650b57cec5SDimitry Andric       break;
1660b57cec5SDimitry Andric     default:
1670b57cec5SDimitry Andric       return false;
1680b57cec5SDimitry Andric     }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric     Loc = Op->getOperatorLoc();
1710b57cec5SDimitry Andric     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
1720b57cec5SDimitry Andric   } else {
1730b57cec5SDimitry Andric     // Not a typo-prone comparison.
1740b57cec5SDimitry Andric     return false;
1750b57cec5SDimitry Andric   }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   // Suppress warnings when the operator, suspicious as it may be, comes from
1780b57cec5SDimitry Andric   // a macro expansion.
1790b57cec5SDimitry Andric   if (S.SourceMgr.isMacroBodyExpansion(Loc))
1800b57cec5SDimitry Andric     return false;
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   S.Diag(Loc, diag::warn_unused_comparison)
1830b57cec5SDimitry Andric     << (unsigned)Kind << E->getSourceRange();
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   // If the LHS is a plausible entity to assign to, provide a fixit hint to
1860b57cec5SDimitry Andric   // correct common typos.
1870b57cec5SDimitry Andric   if (CanAssign) {
1880b57cec5SDimitry Andric     if (Kind == Inequality)
1890b57cec5SDimitry Andric       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
1900b57cec5SDimitry Andric         << FixItHint::CreateReplacement(Loc, "|=");
1910b57cec5SDimitry Andric     else if (Kind == Equality)
1920b57cec5SDimitry Andric       S.Diag(Loc, diag::note_equality_comparison_to_assign)
1930b57cec5SDimitry Andric         << FixItHint::CreateReplacement(Loc, "=");
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   return true;
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric 
199a7dea167SDimitry Andric static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
200a7dea167SDimitry Andric                               SourceLocation Loc, SourceRange R1,
201a7dea167SDimitry Andric                               SourceRange R2, bool IsCtor) {
202a7dea167SDimitry Andric   if (!A)
203a7dea167SDimitry Andric     return false;
204a7dea167SDimitry Andric   StringRef Msg = A->getMessage();
205a7dea167SDimitry Andric 
206a7dea167SDimitry Andric   if (Msg.empty()) {
207a7dea167SDimitry Andric     if (IsCtor)
208a7dea167SDimitry Andric       return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
209a7dea167SDimitry Andric     return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
210a7dea167SDimitry Andric   }
211a7dea167SDimitry Andric 
212a7dea167SDimitry Andric   if (IsCtor)
213a7dea167SDimitry Andric     return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
214a7dea167SDimitry Andric                                                           << R2;
215a7dea167SDimitry Andric   return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
216a7dea167SDimitry Andric }
217a7dea167SDimitry Andric 
2180b57cec5SDimitry Andric void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
2190b57cec5SDimitry Andric   if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2200b57cec5SDimitry Andric     return DiagnoseUnusedExprResult(Label->getSubStmt());
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   const Expr *E = dyn_cast_or_null<Expr>(S);
2230b57cec5SDimitry Andric   if (!E)
2240b57cec5SDimitry Andric     return;
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   // If we are in an unevaluated expression context, then there can be no unused
2270b57cec5SDimitry Andric   // results because the results aren't expected to be used in the first place.
2280b57cec5SDimitry Andric   if (isUnevaluatedContext())
2290b57cec5SDimitry Andric     return;
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
2320b57cec5SDimitry Andric   // In most cases, we don't want to warn if the expression is written in a
2330b57cec5SDimitry Andric   // macro body, or if the macro comes from a system header. If the offending
2340b57cec5SDimitry Andric   // expression is a call to a function with the warn_unused_result attribute,
2350b57cec5SDimitry Andric   // we warn no matter the location. Because of the order in which the various
2360b57cec5SDimitry Andric   // checks need to happen, we factor out the macro-related test here.
2370b57cec5SDimitry Andric   bool ShouldSuppress =
2380b57cec5SDimitry Andric       SourceMgr.isMacroBodyExpansion(ExprLoc) ||
2390b57cec5SDimitry Andric       SourceMgr.isInSystemMacro(ExprLoc);
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   const Expr *WarnExpr;
2420b57cec5SDimitry Andric   SourceLocation Loc;
2430b57cec5SDimitry Andric   SourceRange R1, R2;
2440b57cec5SDimitry Andric   if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
2450b57cec5SDimitry Andric     return;
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric   // If this is a GNU statement expression expanded from a macro, it is probably
2480b57cec5SDimitry Andric   // unused because it is a function-like macro that can be used as either an
2490b57cec5SDimitry Andric   // expression or statement.  Don't warn, because it is almost certainly a
2500b57cec5SDimitry Andric   // false positive.
2510b57cec5SDimitry Andric   if (isa<StmtExpr>(E) && Loc.isMacroID())
2520b57cec5SDimitry Andric     return;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
2550b57cec5SDimitry Andric   // That macro is frequently used to suppress "unused parameter" warnings,
2560b57cec5SDimitry Andric   // but its implementation makes clang's -Wunused-value fire.  Prevent this.
2570b57cec5SDimitry Andric   if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
2580b57cec5SDimitry Andric     SourceLocation SpellLoc = Loc;
2590b57cec5SDimitry Andric     if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
2600b57cec5SDimitry Andric       return;
2610b57cec5SDimitry Andric   }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   // Okay, we have an unused result.  Depending on what the base expression is,
2640b57cec5SDimitry Andric   // we might want to make a more specific diagnostic.  Check for one of these
2650b57cec5SDimitry Andric   // cases now.
2660b57cec5SDimitry Andric   unsigned DiagID = diag::warn_unused_expr;
2670b57cec5SDimitry Andric   if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
2680b57cec5SDimitry Andric     E = Temps->getSubExpr();
2690b57cec5SDimitry Andric   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
2700b57cec5SDimitry Andric     E = TempExpr->getSubExpr();
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   if (DiagnoseUnusedComparison(*this, E))
2730b57cec5SDimitry Andric     return;
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   E = WarnExpr;
276a7dea167SDimitry Andric   if (const auto *Cast = dyn_cast<CastExpr>(E))
277a7dea167SDimitry Andric     if (Cast->getCastKind() == CK_NoOp ||
278a7dea167SDimitry Andric         Cast->getCastKind() == CK_ConstructorConversion)
279a7dea167SDimitry Andric       E = Cast->getSubExpr()->IgnoreImpCasts();
280a7dea167SDimitry Andric 
2810b57cec5SDimitry Andric   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2820b57cec5SDimitry Andric     if (E->getType()->isVoidType())
2830b57cec5SDimitry Andric       return;
2840b57cec5SDimitry Andric 
285a7dea167SDimitry Andric     if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
286a7dea167SDimitry Andric                                      CE->getUnusedResultAttr(Context)),
287a7dea167SDimitry Andric                           Loc, R1, R2, /*isCtor=*/false))
2880b57cec5SDimitry Andric       return;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric     // If the callee has attribute pure, const, or warn_unused_result, warn with
2910b57cec5SDimitry Andric     // a more specific message to make it clear what is happening. If the call
2920b57cec5SDimitry Andric     // is written in a macro body, only warn if it has the warn_unused_result
2930b57cec5SDimitry Andric     // attribute.
2940b57cec5SDimitry Andric     if (const Decl *FD = CE->getCalleeDecl()) {
2950b57cec5SDimitry Andric       if (ShouldSuppress)
2960b57cec5SDimitry Andric         return;
2970b57cec5SDimitry Andric       if (FD->hasAttr<PureAttr>()) {
2980b57cec5SDimitry Andric         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
2990b57cec5SDimitry Andric         return;
3000b57cec5SDimitry Andric       }
3010b57cec5SDimitry Andric       if (FD->hasAttr<ConstAttr>()) {
3020b57cec5SDimitry Andric         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
3030b57cec5SDimitry Andric         return;
3040b57cec5SDimitry Andric       }
3050b57cec5SDimitry Andric     }
306a7dea167SDimitry Andric   } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
307a7dea167SDimitry Andric     if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
308a7dea167SDimitry Andric       const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
309a7dea167SDimitry Andric       A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
310a7dea167SDimitry Andric       if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
311a7dea167SDimitry Andric         return;
312a7dea167SDimitry Andric     }
313a7dea167SDimitry Andric   } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
314a7dea167SDimitry Andric     if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
315a7dea167SDimitry Andric 
316a7dea167SDimitry Andric       if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
317a7dea167SDimitry Andric                             R2, /*isCtor=*/false))
318a7dea167SDimitry Andric         return;
319a7dea167SDimitry Andric     }
3200b57cec5SDimitry Andric   } else if (ShouldSuppress)
3210b57cec5SDimitry Andric     return;
3220b57cec5SDimitry Andric 
323a7dea167SDimitry Andric   E = WarnExpr;
3240b57cec5SDimitry Andric   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3250b57cec5SDimitry Andric     if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
3260b57cec5SDimitry Andric       Diag(Loc, diag::err_arc_unused_init_message) << R1;
3270b57cec5SDimitry Andric       return;
3280b57cec5SDimitry Andric     }
3290b57cec5SDimitry Andric     const ObjCMethodDecl *MD = ME->getMethodDecl();
3300b57cec5SDimitry Andric     if (MD) {
331a7dea167SDimitry Andric       if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
332a7dea167SDimitry Andric                             R2, /*isCtor=*/false))
3330b57cec5SDimitry Andric         return;
3340b57cec5SDimitry Andric     }
3350b57cec5SDimitry Andric   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
3360b57cec5SDimitry Andric     const Expr *Source = POE->getSyntacticForm();
337*5ffd83dbSDimitry Andric     // Handle the actually selected call of an OpenMP specialized call.
338*5ffd83dbSDimitry Andric     if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
339*5ffd83dbSDimitry Andric         POE->getNumSemanticExprs() == 1 &&
340*5ffd83dbSDimitry Andric         isa<CallExpr>(POE->getSemanticExpr(0)))
341*5ffd83dbSDimitry Andric       return DiagnoseUnusedExprResult(POE->getSemanticExpr(0));
3420b57cec5SDimitry Andric     if (isa<ObjCSubscriptRefExpr>(Source))
3430b57cec5SDimitry Andric       DiagID = diag::warn_unused_container_subscript_expr;
3440b57cec5SDimitry Andric     else
3450b57cec5SDimitry Andric       DiagID = diag::warn_unused_property_expr;
3460b57cec5SDimitry Andric   } else if (const CXXFunctionalCastExpr *FC
3470b57cec5SDimitry Andric                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
3480b57cec5SDimitry Andric     const Expr *E = FC->getSubExpr();
3490b57cec5SDimitry Andric     if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
3500b57cec5SDimitry Andric       E = TE->getSubExpr();
3510b57cec5SDimitry Andric     if (isa<CXXTemporaryObjectExpr>(E))
3520b57cec5SDimitry Andric       return;
3530b57cec5SDimitry Andric     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3540b57cec5SDimitry Andric       if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
3550b57cec5SDimitry Andric         if (!RD->getAttr<WarnUnusedAttr>())
3560b57cec5SDimitry Andric           return;
3570b57cec5SDimitry Andric   }
3580b57cec5SDimitry Andric   // Diagnose "(void*) blah" as a typo for "(void) blah".
3590b57cec5SDimitry Andric   else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
3600b57cec5SDimitry Andric     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
3610b57cec5SDimitry Andric     QualType T = TI->getType();
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     // We really do want to use the non-canonical type here.
3640b57cec5SDimitry Andric     if (T == Context.VoidPtrTy) {
3650b57cec5SDimitry Andric       PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric       Diag(Loc, diag::warn_unused_voidptr)
3680b57cec5SDimitry Andric         << FixItHint::CreateRemoval(TL.getStarLoc());
3690b57cec5SDimitry Andric       return;
3700b57cec5SDimitry Andric     }
3710b57cec5SDimitry Andric   }
3720b57cec5SDimitry Andric 
373*5ffd83dbSDimitry Andric   // Tell the user to assign it into a variable to force a volatile load if this
374*5ffd83dbSDimitry Andric   // isn't an array.
375*5ffd83dbSDimitry Andric   if (E->isGLValue() && E->getType().isVolatileQualified() &&
376*5ffd83dbSDimitry Andric       !E->getType()->isArrayType()) {
3770b57cec5SDimitry Andric     Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
3780b57cec5SDimitry Andric     return;
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
3850b57cec5SDimitry Andric   PushCompoundScope(IsStmtExpr);
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric void Sema::ActOnFinishOfCompoundStmt() {
3890b57cec5SDimitry Andric   PopCompoundScope();
3900b57cec5SDimitry Andric }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
3930b57cec5SDimitry Andric   return getCurFunction()->CompoundScopes.back();
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3970b57cec5SDimitry Andric                                    ArrayRef<Stmt *> Elts, bool isStmtExpr) {
3980b57cec5SDimitry Andric   const unsigned NumElts = Elts.size();
3990b57cec5SDimitry Andric 
400*5ffd83dbSDimitry Andric   // Mark the current function as usng floating point constrained intrinsics
401*5ffd83dbSDimitry Andric   if (getCurFPFeatures().isFPConstrained())
402*5ffd83dbSDimitry Andric     if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext))
403*5ffd83dbSDimitry Andric       F->setUsesFPIntrin(true);
404*5ffd83dbSDimitry Andric 
4050b57cec5SDimitry Andric   // If we're in C89 mode, check that we don't have any decls after stmts.  If
4060b57cec5SDimitry Andric   // so, emit an extension diagnostic.
4070b57cec5SDimitry Andric   if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
4080b57cec5SDimitry Andric     // Note that __extension__ can be around a decl.
4090b57cec5SDimitry Andric     unsigned i = 0;
4100b57cec5SDimitry Andric     // Skip over all declarations.
4110b57cec5SDimitry Andric     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
4120b57cec5SDimitry Andric       /*empty*/;
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric     // We found the end of the list or a statement.  Scan for another declstmt.
4150b57cec5SDimitry Andric     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
4160b57cec5SDimitry Andric       /*empty*/;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric     if (i != NumElts) {
4190b57cec5SDimitry Andric       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
4200b57cec5SDimitry Andric       Diag(D->getLocation(), diag::ext_mixed_decls_code);
4210b57cec5SDimitry Andric     }
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   // Check for suspicious empty body (null statement) in `for' and `while'
4250b57cec5SDimitry Andric   // statements.  Don't do anything for template instantiations, this just adds
4260b57cec5SDimitry Andric   // noise.
4270b57cec5SDimitry Andric   if (NumElts != 0 && !CurrentInstantiationScope &&
4280b57cec5SDimitry Andric       getCurCompoundScope().HasEmptyLoopBodies) {
4290b57cec5SDimitry Andric     for (unsigned i = 0; i != NumElts - 1; ++i)
4300b57cec5SDimitry Andric       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
4310b57cec5SDimitry Andric   }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   return CompoundStmt::Create(Context, Elts, L, R);
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric ExprResult
4370b57cec5SDimitry Andric Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
4380b57cec5SDimitry Andric   if (!Val.get())
4390b57cec5SDimitry Andric     return Val;
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   if (DiagnoseUnexpandedParameterPack(Val.get()))
4420b57cec5SDimitry Andric     return ExprError();
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // If we're not inside a switch, let the 'case' statement handling diagnose
4450b57cec5SDimitry Andric   // this. Just clean up after the expression as best we can.
446a7dea167SDimitry Andric   if (getCurFunction()->SwitchStack.empty())
447a7dea167SDimitry Andric     return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
448a7dea167SDimitry Andric                                getLangOpts().CPlusPlus11);
449a7dea167SDimitry Andric 
4500b57cec5SDimitry Andric   Expr *CondExpr =
4510b57cec5SDimitry Andric       getCurFunction()->SwitchStack.back().getPointer()->getCond();
4520b57cec5SDimitry Andric   if (!CondExpr)
4530b57cec5SDimitry Andric     return ExprError();
4540b57cec5SDimitry Andric   QualType CondType = CondExpr->getType();
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   auto CheckAndFinish = [&](Expr *E) {
4570b57cec5SDimitry Andric     if (CondType->isDependentType() || E->isTypeDependent())
4580b57cec5SDimitry Andric       return ExprResult(E);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus11) {
4610b57cec5SDimitry Andric       // C++11 [stmt.switch]p2: the constant-expression shall be a converted
4620b57cec5SDimitry Andric       // constant expression of the promoted type of the switch condition.
4630b57cec5SDimitry Andric       llvm::APSInt TempVal;
4640b57cec5SDimitry Andric       return CheckConvertedConstantExpression(E, CondType, TempVal,
4650b57cec5SDimitry Andric                                               CCEK_CaseValue);
4660b57cec5SDimitry Andric     }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric     ExprResult ER = E;
4690b57cec5SDimitry Andric     if (!E->isValueDependent())
4700b57cec5SDimitry Andric       ER = VerifyIntegerConstantExpression(E);
4710b57cec5SDimitry Andric     if (!ER.isInvalid())
4720b57cec5SDimitry Andric       ER = DefaultLvalueConversion(ER.get());
4730b57cec5SDimitry Andric     if (!ER.isInvalid())
4740b57cec5SDimitry Andric       ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
475a7dea167SDimitry Andric     if (!ER.isInvalid())
476a7dea167SDimitry Andric       ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
4770b57cec5SDimitry Andric     return ER;
4780b57cec5SDimitry Andric   };
4790b57cec5SDimitry Andric 
480*5ffd83dbSDimitry Andric   ExprResult Converted = CorrectDelayedTyposInExpr(
481*5ffd83dbSDimitry Andric       Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
482*5ffd83dbSDimitry Andric       CheckAndFinish);
4830b57cec5SDimitry Andric   if (Converted.get() == Val.get())
4840b57cec5SDimitry Andric     Converted = CheckAndFinish(Val.get());
485a7dea167SDimitry Andric   return Converted;
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric StmtResult
4890b57cec5SDimitry Andric Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
4900b57cec5SDimitry Andric                     SourceLocation DotDotDotLoc, ExprResult RHSVal,
4910b57cec5SDimitry Andric                     SourceLocation ColonLoc) {
4920b57cec5SDimitry Andric   assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
4930b57cec5SDimitry Andric   assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
4940b57cec5SDimitry Andric                                    : RHSVal.isInvalid() || RHSVal.get()) &&
4950b57cec5SDimitry Andric          "missing RHS value");
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   if (getCurFunction()->SwitchStack.empty()) {
4980b57cec5SDimitry Andric     Diag(CaseLoc, diag::err_case_not_in_switch);
4990b57cec5SDimitry Andric     return StmtError();
5000b57cec5SDimitry Andric   }
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
5030b57cec5SDimitry Andric     getCurFunction()->SwitchStack.back().setInt(true);
5040b57cec5SDimitry Andric     return StmtError();
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
5080b57cec5SDimitry Andric                               CaseLoc, DotDotDotLoc, ColonLoc);
5090b57cec5SDimitry Andric   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
5100b57cec5SDimitry Andric   return CS;
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric /// ActOnCaseStmtBody - This installs a statement as the body of a case.
5140b57cec5SDimitry Andric void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
5150b57cec5SDimitry Andric   cast<CaseStmt>(S)->setSubStmt(SubStmt);
5160b57cec5SDimitry Andric }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric StmtResult
5190b57cec5SDimitry Andric Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
5200b57cec5SDimitry Andric                        Stmt *SubStmt, Scope *CurScope) {
5210b57cec5SDimitry Andric   if (getCurFunction()->SwitchStack.empty()) {
5220b57cec5SDimitry Andric     Diag(DefaultLoc, diag::err_default_not_in_switch);
5230b57cec5SDimitry Andric     return SubStmt;
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
5270b57cec5SDimitry Andric   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
5280b57cec5SDimitry Andric   return DS;
5290b57cec5SDimitry Andric }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric StmtResult
5320b57cec5SDimitry Andric Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
5330b57cec5SDimitry Andric                      SourceLocation ColonLoc, Stmt *SubStmt) {
5340b57cec5SDimitry Andric   // If the label was multiply defined, reject it now.
5350b57cec5SDimitry Andric   if (TheDecl->getStmt()) {
5360b57cec5SDimitry Andric     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
5370b57cec5SDimitry Andric     Diag(TheDecl->getLocation(), diag::note_previous_definition);
5380b57cec5SDimitry Andric     return SubStmt;
5390b57cec5SDimitry Andric   }
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   // Otherwise, things are good.  Fill in the declaration and return it.
5420b57cec5SDimitry Andric   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
5430b57cec5SDimitry Andric   TheDecl->setStmt(LS);
5440b57cec5SDimitry Andric   if (!TheDecl->isGnuLocal()) {
5450b57cec5SDimitry Andric     TheDecl->setLocStart(IdentLoc);
5460b57cec5SDimitry Andric     if (!TheDecl->isMSAsmLabel()) {
5470b57cec5SDimitry Andric       // Don't update the location of MS ASM labels.  These will result in
5480b57cec5SDimitry Andric       // a diagnostic, and changing the location here will mess that up.
5490b57cec5SDimitry Andric       TheDecl->setLocation(IdentLoc);
5500b57cec5SDimitry Andric     }
5510b57cec5SDimitry Andric   }
5520b57cec5SDimitry Andric   return LS;
5530b57cec5SDimitry Andric }
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
5560b57cec5SDimitry Andric                                      ArrayRef<const Attr*> Attrs,
5570b57cec5SDimitry Andric                                      Stmt *SubStmt) {
5580b57cec5SDimitry Andric   // Fill in the declaration and return it.
5590b57cec5SDimitry Andric   AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
5600b57cec5SDimitry Andric   return LS;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric namespace {
5640b57cec5SDimitry Andric class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
5650b57cec5SDimitry Andric   typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
5660b57cec5SDimitry Andric   Sema &SemaRef;
5670b57cec5SDimitry Andric public:
5680b57cec5SDimitry Andric   CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
5690b57cec5SDimitry Andric   void VisitBinaryOperator(BinaryOperator *E) {
5700b57cec5SDimitry Andric     if (E->getOpcode() == BO_Comma)
5710b57cec5SDimitry Andric       SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
5720b57cec5SDimitry Andric     EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
5730b57cec5SDimitry Andric   }
5740b57cec5SDimitry Andric };
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric StmtResult
5780b57cec5SDimitry Andric Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
5790b57cec5SDimitry Andric                   ConditionResult Cond,
5800b57cec5SDimitry Andric                   Stmt *thenStmt, SourceLocation ElseLoc,
5810b57cec5SDimitry Andric                   Stmt *elseStmt) {
5820b57cec5SDimitry Andric   if (Cond.isInvalid())
5830b57cec5SDimitry Andric     Cond = ConditionResult(
5840b57cec5SDimitry Andric         *this, nullptr,
5850b57cec5SDimitry Andric         MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
5860b57cec5SDimitry Andric                                                    Context.BoolTy, VK_RValue),
5870b57cec5SDimitry Andric                      IfLoc),
5880b57cec5SDimitry Andric         false);
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   Expr *CondExpr = Cond.get().second;
5910b57cec5SDimitry Andric   // Only call the CommaVisitor when not C89 due to differences in scope flags.
5920b57cec5SDimitry Andric   if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
5930b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
5940b57cec5SDimitry Andric     CommaVisitor(*this).Visit(CondExpr);
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   if (!elseStmt)
5970b57cec5SDimitry Andric     DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
5980b57cec5SDimitry Andric                           diag::warn_empty_if_body);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
6010b57cec5SDimitry Andric                      elseStmt);
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
6050b57cec5SDimitry Andric                              Stmt *InitStmt, ConditionResult Cond,
6060b57cec5SDimitry Andric                              Stmt *thenStmt, SourceLocation ElseLoc,
6070b57cec5SDimitry Andric                              Stmt *elseStmt) {
6080b57cec5SDimitry Andric   if (Cond.isInvalid())
6090b57cec5SDimitry Andric     return StmtError();
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
6120b57cec5SDimitry Andric     setFunctionHasBranchProtectedScope();
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
6150b57cec5SDimitry Andric                         Cond.get().second, thenStmt, ElseLoc, elseStmt);
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric namespace {
6190b57cec5SDimitry Andric   struct CaseCompareFunctor {
6200b57cec5SDimitry Andric     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
6210b57cec5SDimitry Andric                     const llvm::APSInt &RHS) {
6220b57cec5SDimitry Andric       return LHS.first < RHS;
6230b57cec5SDimitry Andric     }
6240b57cec5SDimitry Andric     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
6250b57cec5SDimitry Andric                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
6260b57cec5SDimitry Andric       return LHS.first < RHS.first;
6270b57cec5SDimitry Andric     }
6280b57cec5SDimitry Andric     bool operator()(const llvm::APSInt &LHS,
6290b57cec5SDimitry Andric                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
6300b57cec5SDimitry Andric       return LHS < RHS.first;
6310b57cec5SDimitry Andric     }
6320b57cec5SDimitry Andric   };
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric /// CmpCaseVals - Comparison predicate for sorting case values.
6360b57cec5SDimitry Andric ///
6370b57cec5SDimitry Andric static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
6380b57cec5SDimitry Andric                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
6390b57cec5SDimitry Andric   if (lhs.first < rhs.first)
6400b57cec5SDimitry Andric     return true;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   if (lhs.first == rhs.first &&
6430b57cec5SDimitry Andric       lhs.second->getCaseLoc().getRawEncoding()
6440b57cec5SDimitry Andric        < rhs.second->getCaseLoc().getRawEncoding())
6450b57cec5SDimitry Andric     return true;
6460b57cec5SDimitry Andric   return false;
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric /// CmpEnumVals - Comparison predicate for sorting enumeration values.
6500b57cec5SDimitry Andric ///
6510b57cec5SDimitry Andric static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
6520b57cec5SDimitry Andric                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
6530b57cec5SDimitry Andric {
6540b57cec5SDimitry Andric   return lhs.first < rhs.first;
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric /// EqEnumVals - Comparison preficate for uniqing enumeration values.
6580b57cec5SDimitry Andric ///
6590b57cec5SDimitry Andric static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
6600b57cec5SDimitry Andric                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
6610b57cec5SDimitry Andric {
6620b57cec5SDimitry Andric   return lhs.first == rhs.first;
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
6660b57cec5SDimitry Andric /// potentially integral-promoted expression @p expr.
6670b57cec5SDimitry Andric static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
6680b57cec5SDimitry Andric   if (const auto *FE = dyn_cast<FullExpr>(E))
6690b57cec5SDimitry Andric     E = FE->getSubExpr();
6700b57cec5SDimitry Andric   while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
6710b57cec5SDimitry Andric     if (ImpCast->getCastKind() != CK_IntegralCast) break;
6720b57cec5SDimitry Andric     E = ImpCast->getSubExpr();
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric   return E->getType();
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
6780b57cec5SDimitry Andric   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
6790b57cec5SDimitry Andric     Expr *Cond;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   public:
6820b57cec5SDimitry Andric     SwitchConvertDiagnoser(Expr *Cond)
6830b57cec5SDimitry Andric         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
6840b57cec5SDimitry Andric           Cond(Cond) {}
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6870b57cec5SDimitry Andric                                          QualType T) override {
6880b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
6890b57cec5SDimitry Andric     }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseIncomplete(
6920b57cec5SDimitry Andric         Sema &S, SourceLocation Loc, QualType T) override {
6930b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
6940b57cec5SDimitry Andric                << T << Cond->getSourceRange();
6950b57cec5SDimitry Andric     }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseExplicitConv(
6980b57cec5SDimitry Andric         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
6990b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
7000b57cec5SDimitry Andric     }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     SemaDiagnosticBuilder noteExplicitConv(
7030b57cec5SDimitry Andric         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
7040b57cec5SDimitry Andric       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
7050b57cec5SDimitry Andric         << ConvTy->isEnumeralType() << ConvTy;
7060b57cec5SDimitry Andric     }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7090b57cec5SDimitry Andric                                             QualType T) override {
7100b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
7110b57cec5SDimitry Andric     }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric     SemaDiagnosticBuilder noteAmbiguous(
7140b57cec5SDimitry Andric         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
7150b57cec5SDimitry Andric       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
7160b57cec5SDimitry Andric       << ConvTy->isEnumeralType() << ConvTy;
7170b57cec5SDimitry Andric     }
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseConversion(
7200b57cec5SDimitry Andric         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
7210b57cec5SDimitry Andric       llvm_unreachable("conversion functions are permitted");
7220b57cec5SDimitry Andric     }
7230b57cec5SDimitry Andric   } SwitchDiagnoser(Cond);
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   ExprResult CondResult =
7260b57cec5SDimitry Andric       PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
7270b57cec5SDimitry Andric   if (CondResult.isInvalid())
7280b57cec5SDimitry Andric     return ExprError();
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
7310b57cec5SDimitry Andric   // failed and produced a diagnostic.
7320b57cec5SDimitry Andric   Cond = CondResult.get();
7330b57cec5SDimitry Andric   if (!Cond->isTypeDependent() &&
7340b57cec5SDimitry Andric       !Cond->getType()->isIntegralOrEnumerationType())
7350b57cec5SDimitry Andric     return ExprError();
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
7380b57cec5SDimitry Andric   return UsualUnaryConversions(Cond);
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
7420b57cec5SDimitry Andric                                         Stmt *InitStmt, ConditionResult Cond) {
7430b57cec5SDimitry Andric   Expr *CondExpr = Cond.get().second;
7440b57cec5SDimitry Andric   assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   if (CondExpr && !CondExpr->isTypeDependent()) {
7470b57cec5SDimitry Andric     // We have already converted the expression to an integral or enumeration
748*5ffd83dbSDimitry Andric     // type, when we parsed the switch condition. There are cases where we don't
749*5ffd83dbSDimitry Andric     // have an appropriate type, e.g. a typo-expr Cond was corrected to an
750*5ffd83dbSDimitry Andric     // inappropriate-type expr, we just return an error.
751*5ffd83dbSDimitry Andric     if (!CondExpr->getType()->isIntegralOrEnumerationType())
752*5ffd83dbSDimitry Andric       return StmtError();
7530b57cec5SDimitry Andric     if (CondExpr->isKnownToHaveBooleanValue()) {
7540b57cec5SDimitry Andric       // switch(bool_expr) {...} is often a programmer error, e.g.
7550b57cec5SDimitry Andric       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
7560b57cec5SDimitry Andric       // One can always use an if statement instead of switch(bool_expr).
7570b57cec5SDimitry Andric       Diag(SwitchLoc, diag::warn_bool_switch_condition)
7580b57cec5SDimitry Andric           << CondExpr->getSourceRange();
7590b57cec5SDimitry Andric     }
7600b57cec5SDimitry Andric   }
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   setFunctionHasBranchIntoScope();
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
7650b57cec5SDimitry Andric   getCurFunction()->SwitchStack.push_back(
7660b57cec5SDimitry Andric       FunctionScopeInfo::SwitchInfo(SS, false));
7670b57cec5SDimitry Andric   return SS;
7680b57cec5SDimitry Andric }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
7710b57cec5SDimitry Andric   Val = Val.extOrTrunc(BitWidth);
7720b57cec5SDimitry Andric   Val.setIsSigned(IsSigned);
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric /// Check the specified case value is in range for the given unpromoted switch
7760b57cec5SDimitry Andric /// type.
7770b57cec5SDimitry Andric static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
7780b57cec5SDimitry Andric                            unsigned UnpromotedWidth, bool UnpromotedSign) {
7790b57cec5SDimitry Andric   // In C++11 onwards, this is checked by the language rules.
7800b57cec5SDimitry Andric   if (S.getLangOpts().CPlusPlus11)
7810b57cec5SDimitry Andric     return;
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   // If the case value was signed and negative and the switch expression is
7840b57cec5SDimitry Andric   // unsigned, don't bother to warn: this is implementation-defined behavior.
7850b57cec5SDimitry Andric   // FIXME: Introduce a second, default-ignored warning for this case?
7860b57cec5SDimitry Andric   if (UnpromotedWidth < Val.getBitWidth()) {
7870b57cec5SDimitry Andric     llvm::APSInt ConvVal(Val);
7880b57cec5SDimitry Andric     AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
7890b57cec5SDimitry Andric     AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
7900b57cec5SDimitry Andric     // FIXME: Use different diagnostics for overflow  in conversion to promoted
7910b57cec5SDimitry Andric     // type versus "switch expression cannot have this value". Use proper
7920b57cec5SDimitry Andric     // IntRange checking rather than just looking at the unpromoted type here.
7930b57cec5SDimitry Andric     if (ConvVal != Val)
7940b57cec5SDimitry Andric       S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
7950b57cec5SDimitry Andric                                                   << ConvVal.toString(10);
7960b57cec5SDimitry Andric   }
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric /// Returns true if we should emit a diagnostic about this case expression not
8020b57cec5SDimitry Andric /// being a part of the enum used in the switch controlling expression.
8030b57cec5SDimitry Andric static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
8040b57cec5SDimitry Andric                                               const EnumDecl *ED,
8050b57cec5SDimitry Andric                                               const Expr *CaseExpr,
8060b57cec5SDimitry Andric                                               EnumValsTy::iterator &EI,
8070b57cec5SDimitry Andric                                               EnumValsTy::iterator &EIEnd,
8080b57cec5SDimitry Andric                                               const llvm::APSInt &Val) {
8090b57cec5SDimitry Andric   if (!ED->isClosed())
8100b57cec5SDimitry Andric     return false;
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   if (const DeclRefExpr *DRE =
8130b57cec5SDimitry Andric           dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
8140b57cec5SDimitry Andric     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
8150b57cec5SDimitry Andric       QualType VarType = VD->getType();
8160b57cec5SDimitry Andric       QualType EnumType = S.Context.getTypeDeclType(ED);
8170b57cec5SDimitry Andric       if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
8180b57cec5SDimitry Andric           S.Context.hasSameUnqualifiedType(EnumType, VarType))
8190b57cec5SDimitry Andric         return false;
8200b57cec5SDimitry Andric     }
8210b57cec5SDimitry Andric   }
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   if (ED->hasAttr<FlagEnumAttr>())
8240b57cec5SDimitry Andric     return !S.IsValueInFlagEnum(ED, Val, false);
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   while (EI != EIEnd && EI->first < Val)
8270b57cec5SDimitry Andric     EI++;
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   if (EI != EIEnd && EI->first == Val)
8300b57cec5SDimitry Andric     return false;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   return true;
8330b57cec5SDimitry Andric }
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
8360b57cec5SDimitry Andric                                        const Expr *Case) {
8370b57cec5SDimitry Andric   QualType CondType = Cond->getType();
8380b57cec5SDimitry Andric   QualType CaseType = Case->getType();
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   const EnumType *CondEnumType = CondType->getAs<EnumType>();
8410b57cec5SDimitry Andric   const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
8420b57cec5SDimitry Andric   if (!CondEnumType || !CaseEnumType)
8430b57cec5SDimitry Andric     return;
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   // Ignore anonymous enums.
8460b57cec5SDimitry Andric   if (!CondEnumType->getDecl()->getIdentifier() &&
8470b57cec5SDimitry Andric       !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
8480b57cec5SDimitry Andric     return;
8490b57cec5SDimitry Andric   if (!CaseEnumType->getDecl()->getIdentifier() &&
8500b57cec5SDimitry Andric       !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
8510b57cec5SDimitry Andric     return;
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
8540b57cec5SDimitry Andric     return;
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
8570b57cec5SDimitry Andric       << CondType << CaseType << Cond->getSourceRange()
8580b57cec5SDimitry Andric       << Case->getSourceRange();
8590b57cec5SDimitry Andric }
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric StmtResult
8620b57cec5SDimitry Andric Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
8630b57cec5SDimitry Andric                             Stmt *BodyStmt) {
8640b57cec5SDimitry Andric   SwitchStmt *SS = cast<SwitchStmt>(Switch);
8650b57cec5SDimitry Andric   bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
8660b57cec5SDimitry Andric   assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
8670b57cec5SDimitry Andric          "switch stack missing push/pop!");
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   getCurFunction()->SwitchStack.pop_back();
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric   if (!BodyStmt) return StmtError();
8720b57cec5SDimitry Andric   SS->setBody(BodyStmt, SwitchLoc);
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   Expr *CondExpr = SS->getCond();
8750b57cec5SDimitry Andric   if (!CondExpr) return StmtError();
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   QualType CondType = CondExpr->getType();
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   // C++ 6.4.2.p2:
8800b57cec5SDimitry Andric   // Integral promotions are performed (on the switch condition).
8810b57cec5SDimitry Andric   //
8820b57cec5SDimitry Andric   // A case value unrepresentable by the original switch condition
8830b57cec5SDimitry Andric   // type (before the promotion) doesn't make sense, even when it can
8840b57cec5SDimitry Andric   // be represented by the promoted type.  Therefore we need to find
8850b57cec5SDimitry Andric   // the pre-promotion type of the switch condition.
8860b57cec5SDimitry Andric   const Expr *CondExprBeforePromotion = CondExpr;
8870b57cec5SDimitry Andric   QualType CondTypeBeforePromotion =
8880b57cec5SDimitry Andric       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   // Get the bitwidth of the switched-on value after promotions. We must
8910b57cec5SDimitry Andric   // convert the integer case values to this width before comparison.
8920b57cec5SDimitry Andric   bool HasDependentValue
8930b57cec5SDimitry Andric     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
8940b57cec5SDimitry Andric   unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
8950b57cec5SDimitry Andric   bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   // Get the width and signedness that the condition might actually have, for
8980b57cec5SDimitry Andric   // warning purposes.
8990b57cec5SDimitry Andric   // FIXME: Grab an IntRange for the condition rather than using the unpromoted
9000b57cec5SDimitry Andric   // type.
9010b57cec5SDimitry Andric   unsigned CondWidthBeforePromotion
9020b57cec5SDimitry Andric     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
9030b57cec5SDimitry Andric   bool CondIsSignedBeforePromotion
9040b57cec5SDimitry Andric     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   // Accumulate all of the case values in a vector so that we can sort them
9070b57cec5SDimitry Andric   // and detect duplicates.  This vector contains the APInt for the case after
9080b57cec5SDimitry Andric   // it has been converted to the condition type.
9090b57cec5SDimitry Andric   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
9100b57cec5SDimitry Andric   CaseValsTy CaseVals;
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
9130b57cec5SDimitry Andric   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
9140b57cec5SDimitry Andric   CaseRangesTy CaseRanges;
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   DefaultStmt *TheDefaultStmt = nullptr;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   bool CaseListIsErroneous = false;
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
9210b57cec5SDimitry Andric        SC = SC->getNextSwitchCase()) {
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
9240b57cec5SDimitry Andric       if (TheDefaultStmt) {
9250b57cec5SDimitry Andric         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
9260b57cec5SDimitry Andric         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric         // FIXME: Remove the default statement from the switch block so that
9290b57cec5SDimitry Andric         // we'll return a valid AST.  This requires recursing down the AST and
9300b57cec5SDimitry Andric         // finding it, not something we are set up to do right now.  For now,
9310b57cec5SDimitry Andric         // just lop the entire switch stmt out of the AST.
9320b57cec5SDimitry Andric         CaseListIsErroneous = true;
9330b57cec5SDimitry Andric       }
9340b57cec5SDimitry Andric       TheDefaultStmt = DS;
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric     } else {
9370b57cec5SDimitry Andric       CaseStmt *CS = cast<CaseStmt>(SC);
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric       Expr *Lo = CS->getLHS();
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric       if (Lo->isValueDependent()) {
9420b57cec5SDimitry Andric         HasDependentValue = true;
9430b57cec5SDimitry Andric         break;
9440b57cec5SDimitry Andric       }
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric       // We already verified that the expression has a constant value;
9470b57cec5SDimitry Andric       // get that value (prior to conversions).
9480b57cec5SDimitry Andric       const Expr *LoBeforePromotion = Lo;
9490b57cec5SDimitry Andric       GetTypeBeforeIntegralPromotion(LoBeforePromotion);
9500b57cec5SDimitry Andric       llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric       // Check the unconverted value is within the range of possible values of
9530b57cec5SDimitry Andric       // the switch expression.
9540b57cec5SDimitry Andric       checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
9550b57cec5SDimitry Andric                      CondIsSignedBeforePromotion);
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric       // FIXME: This duplicates the check performed for warn_not_in_enum below.
9580b57cec5SDimitry Andric       checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
9590b57cec5SDimitry Andric                                  LoBeforePromotion);
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric       // Convert the value to the same width/sign as the condition.
9620b57cec5SDimitry Andric       AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
9650b57cec5SDimitry Andric       if (CS->getRHS()) {
9660b57cec5SDimitry Andric         if (CS->getRHS()->isValueDependent()) {
9670b57cec5SDimitry Andric           HasDependentValue = true;
9680b57cec5SDimitry Andric           break;
9690b57cec5SDimitry Andric         }
9700b57cec5SDimitry Andric         CaseRanges.push_back(std::make_pair(LoVal, CS));
9710b57cec5SDimitry Andric       } else
9720b57cec5SDimitry Andric         CaseVals.push_back(std::make_pair(LoVal, CS));
9730b57cec5SDimitry Andric     }
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   if (!HasDependentValue) {
9770b57cec5SDimitry Andric     // If we don't have a default statement, check whether the
9780b57cec5SDimitry Andric     // condition is constant.
9790b57cec5SDimitry Andric     llvm::APSInt ConstantCondValue;
9800b57cec5SDimitry Andric     bool HasConstantCond = false;
981a7dea167SDimitry Andric     if (!TheDefaultStmt) {
9820b57cec5SDimitry Andric       Expr::EvalResult Result;
9830b57cec5SDimitry Andric       HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
9840b57cec5SDimitry Andric                                                 Expr::SE_AllowSideEffects);
9850b57cec5SDimitry Andric       if (Result.Val.isInt())
9860b57cec5SDimitry Andric         ConstantCondValue = Result.Val.getInt();
9870b57cec5SDimitry Andric       assert(!HasConstantCond ||
9880b57cec5SDimitry Andric              (ConstantCondValue.getBitWidth() == CondWidth &&
9890b57cec5SDimitry Andric               ConstantCondValue.isSigned() == CondIsSigned));
9900b57cec5SDimitry Andric     }
9910b57cec5SDimitry Andric     bool ShouldCheckConstantCond = HasConstantCond;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     // Sort all the scalar case values so we can easily detect duplicates.
9940b57cec5SDimitry Andric     llvm::stable_sort(CaseVals, CmpCaseVals);
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric     if (!CaseVals.empty()) {
9970b57cec5SDimitry Andric       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
9980b57cec5SDimitry Andric         if (ShouldCheckConstantCond &&
9990b57cec5SDimitry Andric             CaseVals[i].first == ConstantCondValue)
10000b57cec5SDimitry Andric           ShouldCheckConstantCond = false;
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
10030b57cec5SDimitry Andric           // If we have a duplicate, report it.
10040b57cec5SDimitry Andric           // First, determine if either case value has a name
10050b57cec5SDimitry Andric           StringRef PrevString, CurrString;
10060b57cec5SDimitry Andric           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
10070b57cec5SDimitry Andric           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
10080b57cec5SDimitry Andric           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
10090b57cec5SDimitry Andric             PrevString = DeclRef->getDecl()->getName();
10100b57cec5SDimitry Andric           }
10110b57cec5SDimitry Andric           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
10120b57cec5SDimitry Andric             CurrString = DeclRef->getDecl()->getName();
10130b57cec5SDimitry Andric           }
10140b57cec5SDimitry Andric           SmallString<16> CaseValStr;
10150b57cec5SDimitry Andric           CaseVals[i-1].first.toString(CaseValStr);
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric           if (PrevString == CurrString)
10180b57cec5SDimitry Andric             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
10190b57cec5SDimitry Andric                  diag::err_duplicate_case)
10200b57cec5SDimitry Andric                 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
10210b57cec5SDimitry Andric           else
10220b57cec5SDimitry Andric             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
10230b57cec5SDimitry Andric                  diag::err_duplicate_case_differing_expr)
10240b57cec5SDimitry Andric                 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
10250b57cec5SDimitry Andric                 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
10260b57cec5SDimitry Andric                 << CaseValStr;
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric           Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
10290b57cec5SDimitry Andric                diag::note_duplicate_case_prev);
10300b57cec5SDimitry Andric           // FIXME: We really want to remove the bogus case stmt from the
10310b57cec5SDimitry Andric           // substmt, but we have no way to do this right now.
10320b57cec5SDimitry Andric           CaseListIsErroneous = true;
10330b57cec5SDimitry Andric         }
10340b57cec5SDimitry Andric       }
10350b57cec5SDimitry Andric     }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric     // Detect duplicate case ranges, which usually don't exist at all in
10380b57cec5SDimitry Andric     // the first place.
10390b57cec5SDimitry Andric     if (!CaseRanges.empty()) {
10400b57cec5SDimitry Andric       // Sort all the case ranges by their low value so we can easily detect
10410b57cec5SDimitry Andric       // overlaps between ranges.
10420b57cec5SDimitry Andric       llvm::stable_sort(CaseRanges);
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric       // Scan the ranges, computing the high values and removing empty ranges.
10450b57cec5SDimitry Andric       std::vector<llvm::APSInt> HiVals;
10460b57cec5SDimitry Andric       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
10470b57cec5SDimitry Andric         llvm::APSInt &LoVal = CaseRanges[i].first;
10480b57cec5SDimitry Andric         CaseStmt *CR = CaseRanges[i].second;
10490b57cec5SDimitry Andric         Expr *Hi = CR->getRHS();
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric         const Expr *HiBeforePromotion = Hi;
10520b57cec5SDimitry Andric         GetTypeBeforeIntegralPromotion(HiBeforePromotion);
10530b57cec5SDimitry Andric         llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric         // Check the unconverted value is within the range of possible values of
10560b57cec5SDimitry Andric         // the switch expression.
10570b57cec5SDimitry Andric         checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
10580b57cec5SDimitry Andric                        CondWidthBeforePromotion, CondIsSignedBeforePromotion);
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric         // Convert the value to the same width/sign as the condition.
10610b57cec5SDimitry Andric         AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric         // If the low value is bigger than the high value, the case is empty.
10640b57cec5SDimitry Andric         if (LoVal > HiVal) {
10650b57cec5SDimitry Andric           Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
10660b57cec5SDimitry Andric               << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
10670b57cec5SDimitry Andric           CaseRanges.erase(CaseRanges.begin()+i);
10680b57cec5SDimitry Andric           --i;
10690b57cec5SDimitry Andric           --e;
10700b57cec5SDimitry Andric           continue;
10710b57cec5SDimitry Andric         }
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric         if (ShouldCheckConstantCond &&
10740b57cec5SDimitry Andric             LoVal <= ConstantCondValue &&
10750b57cec5SDimitry Andric             ConstantCondValue <= HiVal)
10760b57cec5SDimitry Andric           ShouldCheckConstantCond = false;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric         HiVals.push_back(HiVal);
10790b57cec5SDimitry Andric       }
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric       // Rescan the ranges, looking for overlap with singleton values and other
10820b57cec5SDimitry Andric       // ranges.  Since the range list is sorted, we only need to compare case
10830b57cec5SDimitry Andric       // ranges with their neighbors.
10840b57cec5SDimitry Andric       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
10850b57cec5SDimitry Andric         llvm::APSInt &CRLo = CaseRanges[i].first;
10860b57cec5SDimitry Andric         llvm::APSInt &CRHi = HiVals[i];
10870b57cec5SDimitry Andric         CaseStmt *CR = CaseRanges[i].second;
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric         // Check to see whether the case range overlaps with any
10900b57cec5SDimitry Andric         // singleton cases.
10910b57cec5SDimitry Andric         CaseStmt *OverlapStmt = nullptr;
10920b57cec5SDimitry Andric         llvm::APSInt OverlapVal(32);
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric         // Find the smallest value >= the lower bound.  If I is in the
10950b57cec5SDimitry Andric         // case range, then we have overlap.
10960b57cec5SDimitry Andric         CaseValsTy::iterator I =
10970b57cec5SDimitry Andric             llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
10980b57cec5SDimitry Andric         if (I != CaseVals.end() && I->first < CRHi) {
10990b57cec5SDimitry Andric           OverlapVal  = I->first;   // Found overlap with scalar.
11000b57cec5SDimitry Andric           OverlapStmt = I->second;
11010b57cec5SDimitry Andric         }
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric         // Find the smallest value bigger than the upper bound.
11040b57cec5SDimitry Andric         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
11050b57cec5SDimitry Andric         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
11060b57cec5SDimitry Andric           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
11070b57cec5SDimitry Andric           OverlapStmt = (I-1)->second;
11080b57cec5SDimitry Andric         }
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric         // Check to see if this case stmt overlaps with the subsequent
11110b57cec5SDimitry Andric         // case range.
11120b57cec5SDimitry Andric         if (i && CRLo <= HiVals[i-1]) {
11130b57cec5SDimitry Andric           OverlapVal  = HiVals[i-1];       // Found overlap with range.
11140b57cec5SDimitry Andric           OverlapStmt = CaseRanges[i-1].second;
11150b57cec5SDimitry Andric         }
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric         if (OverlapStmt) {
11180b57cec5SDimitry Andric           // If we have a duplicate, report it.
11190b57cec5SDimitry Andric           Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
11200b57cec5SDimitry Andric               << OverlapVal.toString(10);
11210b57cec5SDimitry Andric           Diag(OverlapStmt->getLHS()->getBeginLoc(),
11220b57cec5SDimitry Andric                diag::note_duplicate_case_prev);
11230b57cec5SDimitry Andric           // FIXME: We really want to remove the bogus case stmt from the
11240b57cec5SDimitry Andric           // substmt, but we have no way to do this right now.
11250b57cec5SDimitry Andric           CaseListIsErroneous = true;
11260b57cec5SDimitry Andric         }
11270b57cec5SDimitry Andric       }
11280b57cec5SDimitry Andric     }
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric     // Complain if we have a constant condition and we didn't find a match.
11310b57cec5SDimitry Andric     if (!CaseListIsErroneous && !CaseListIsIncomplete &&
11320b57cec5SDimitry Andric         ShouldCheckConstantCond) {
11330b57cec5SDimitry Andric       // TODO: it would be nice if we printed enums as enums, chars as
11340b57cec5SDimitry Andric       // chars, etc.
11350b57cec5SDimitry Andric       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
11360b57cec5SDimitry Andric         << ConstantCondValue.toString(10)
11370b57cec5SDimitry Andric         << CondExpr->getSourceRange();
11380b57cec5SDimitry Andric     }
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric     // Check to see if switch is over an Enum and handles all of its
11410b57cec5SDimitry Andric     // values.  We only issue a warning if there is not 'default:', but
11420b57cec5SDimitry Andric     // we still do the analysis to preserve this information in the AST
11430b57cec5SDimitry Andric     // (which can be used by flow-based analyes).
11440b57cec5SDimitry Andric     //
11450b57cec5SDimitry Andric     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric     // If switch has default case, then ignore it.
11480b57cec5SDimitry Andric     if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
11490b57cec5SDimitry Andric         ET && ET->getDecl()->isCompleteDefinition()) {
11500b57cec5SDimitry Andric       const EnumDecl *ED = ET->getDecl();
11510b57cec5SDimitry Andric       EnumValsTy EnumVals;
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric       // Gather all enum values, set their type and sort them,
11540b57cec5SDimitry Andric       // allowing easier comparison with CaseVals.
11550b57cec5SDimitry Andric       for (auto *EDI : ED->enumerators()) {
11560b57cec5SDimitry Andric         llvm::APSInt Val = EDI->getInitVal();
11570b57cec5SDimitry Andric         AdjustAPSInt(Val, CondWidth, CondIsSigned);
11580b57cec5SDimitry Andric         EnumVals.push_back(std::make_pair(Val, EDI));
11590b57cec5SDimitry Andric       }
11600b57cec5SDimitry Andric       llvm::stable_sort(EnumVals, CmpEnumVals);
11610b57cec5SDimitry Andric       auto EI = EnumVals.begin(), EIEnd =
11620b57cec5SDimitry Andric         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric       // See which case values aren't in enum.
11650b57cec5SDimitry Andric       for (CaseValsTy::const_iterator CI = CaseVals.begin();
11660b57cec5SDimitry Andric           CI != CaseVals.end(); CI++) {
11670b57cec5SDimitry Andric         Expr *CaseExpr = CI->second->getLHS();
11680b57cec5SDimitry Andric         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
11690b57cec5SDimitry Andric                                               CI->first))
11700b57cec5SDimitry Andric           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
11710b57cec5SDimitry Andric             << CondTypeBeforePromotion;
11720b57cec5SDimitry Andric       }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric       // See which of case ranges aren't in enum
11750b57cec5SDimitry Andric       EI = EnumVals.begin();
11760b57cec5SDimitry Andric       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
11770b57cec5SDimitry Andric           RI != CaseRanges.end(); RI++) {
11780b57cec5SDimitry Andric         Expr *CaseExpr = RI->second->getLHS();
11790b57cec5SDimitry Andric         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
11800b57cec5SDimitry Andric                                               RI->first))
11810b57cec5SDimitry Andric           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
11820b57cec5SDimitry Andric             << CondTypeBeforePromotion;
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric         llvm::APSInt Hi =
11850b57cec5SDimitry Andric           RI->second->getRHS()->EvaluateKnownConstInt(Context);
11860b57cec5SDimitry Andric         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric         CaseExpr = RI->second->getRHS();
11890b57cec5SDimitry Andric         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
11900b57cec5SDimitry Andric                                               Hi))
11910b57cec5SDimitry Andric           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
11920b57cec5SDimitry Andric             << CondTypeBeforePromotion;
11930b57cec5SDimitry Andric       }
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric       // Check which enum vals aren't in switch
11960b57cec5SDimitry Andric       auto CI = CaseVals.begin();
11970b57cec5SDimitry Andric       auto RI = CaseRanges.begin();
11980b57cec5SDimitry Andric       bool hasCasesNotInSwitch = false;
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric       SmallVector<DeclarationName,8> UnhandledNames;
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric       for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
12030b57cec5SDimitry Andric         // Don't warn about omitted unavailable EnumConstantDecls.
12040b57cec5SDimitry Andric         switch (EI->second->getAvailability()) {
12050b57cec5SDimitry Andric         case AR_Deprecated:
12060b57cec5SDimitry Andric           // Omitting a deprecated constant is ok; it should never materialize.
12070b57cec5SDimitry Andric         case AR_Unavailable:
12080b57cec5SDimitry Andric           continue;
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric         case AR_NotYetIntroduced:
12110b57cec5SDimitry Andric           // Partially available enum constants should be present. Note that we
12120b57cec5SDimitry Andric           // suppress -Wunguarded-availability diagnostics for such uses.
12130b57cec5SDimitry Andric         case AR_Available:
12140b57cec5SDimitry Andric           break;
12150b57cec5SDimitry Andric         }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric         if (EI->second->hasAttr<UnusedAttr>())
12180b57cec5SDimitry Andric           continue;
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric         // Drop unneeded case values
12210b57cec5SDimitry Andric         while (CI != CaseVals.end() && CI->first < EI->first)
12220b57cec5SDimitry Andric           CI++;
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric         if (CI != CaseVals.end() && CI->first == EI->first)
12250b57cec5SDimitry Andric           continue;
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric         // Drop unneeded case ranges
12280b57cec5SDimitry Andric         for (; RI != CaseRanges.end(); RI++) {
12290b57cec5SDimitry Andric           llvm::APSInt Hi =
12300b57cec5SDimitry Andric             RI->second->getRHS()->EvaluateKnownConstInt(Context);
12310b57cec5SDimitry Andric           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
12320b57cec5SDimitry Andric           if (EI->first <= Hi)
12330b57cec5SDimitry Andric             break;
12340b57cec5SDimitry Andric         }
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric         if (RI == CaseRanges.end() || EI->first < RI->first) {
12370b57cec5SDimitry Andric           hasCasesNotInSwitch = true;
12380b57cec5SDimitry Andric           UnhandledNames.push_back(EI->second->getDeclName());
12390b57cec5SDimitry Andric         }
12400b57cec5SDimitry Andric       }
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric       if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
12430b57cec5SDimitry Andric         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric       // Produce a nice diagnostic if multiple values aren't handled.
12460b57cec5SDimitry Andric       if (!UnhandledNames.empty()) {
12470b57cec5SDimitry Andric         DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
12480b57cec5SDimitry Andric                                     TheDefaultStmt ? diag::warn_def_missing_case
12490b57cec5SDimitry Andric                                                    : diag::warn_missing_case)
12500b57cec5SDimitry Andric                                << (int)UnhandledNames.size();
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric         for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
12530b57cec5SDimitry Andric              I != E; ++I)
12540b57cec5SDimitry Andric           DB << UnhandledNames[I];
12550b57cec5SDimitry Andric       }
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric       if (!hasCasesNotInSwitch)
12580b57cec5SDimitry Andric         SS->setAllEnumCasesCovered();
12590b57cec5SDimitry Andric     }
12600b57cec5SDimitry Andric   }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   if (BodyStmt)
12630b57cec5SDimitry Andric     DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
12640b57cec5SDimitry Andric                           diag::warn_empty_switch_body);
12650b57cec5SDimitry Andric 
12660b57cec5SDimitry Andric   // FIXME: If the case list was broken is some way, we don't have a good system
12670b57cec5SDimitry Andric   // to patch it up.  Instead, just return the whole substmt as broken.
12680b57cec5SDimitry Andric   if (CaseListIsErroneous)
12690b57cec5SDimitry Andric     return StmtError();
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   return SS;
12720b57cec5SDimitry Andric }
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric void
12750b57cec5SDimitry Andric Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
12760b57cec5SDimitry Andric                              Expr *SrcExpr) {
12770b57cec5SDimitry Andric   if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
12780b57cec5SDimitry Andric     return;
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   if (const EnumType *ET = DstType->getAs<EnumType>())
12810b57cec5SDimitry Andric     if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
12820b57cec5SDimitry Andric         SrcType->isIntegerType()) {
12830b57cec5SDimitry Andric       if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
12840b57cec5SDimitry Andric           SrcExpr->isIntegerConstantExpr(Context)) {
12850b57cec5SDimitry Andric         // Get the bitwidth of the enum value before promotions.
12860b57cec5SDimitry Andric         unsigned DstWidth = Context.getIntWidth(DstType);
12870b57cec5SDimitry Andric         bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric         llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
12900b57cec5SDimitry Andric         AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
12910b57cec5SDimitry Andric         const EnumDecl *ED = ET->getDecl();
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric         if (!ED->isClosed())
12940b57cec5SDimitry Andric           return;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric         if (ED->hasAttr<FlagEnumAttr>()) {
12970b57cec5SDimitry Andric           if (!IsValueInFlagEnum(ED, RhsVal, true))
12980b57cec5SDimitry Andric             Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
12990b57cec5SDimitry Andric               << DstType.getUnqualifiedType();
13000b57cec5SDimitry Andric         } else {
13010b57cec5SDimitry Andric           typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
13020b57cec5SDimitry Andric               EnumValsTy;
13030b57cec5SDimitry Andric           EnumValsTy EnumVals;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric           // Gather all enum values, set their type and sort them,
13060b57cec5SDimitry Andric           // allowing easier comparison with rhs constant.
13070b57cec5SDimitry Andric           for (auto *EDI : ED->enumerators()) {
13080b57cec5SDimitry Andric             llvm::APSInt Val = EDI->getInitVal();
13090b57cec5SDimitry Andric             AdjustAPSInt(Val, DstWidth, DstIsSigned);
13100b57cec5SDimitry Andric             EnumVals.push_back(std::make_pair(Val, EDI));
13110b57cec5SDimitry Andric           }
13120b57cec5SDimitry Andric           if (EnumVals.empty())
13130b57cec5SDimitry Andric             return;
13140b57cec5SDimitry Andric           llvm::stable_sort(EnumVals, CmpEnumVals);
13150b57cec5SDimitry Andric           EnumValsTy::iterator EIend =
13160b57cec5SDimitry Andric               std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric           // See which values aren't in the enum.
13190b57cec5SDimitry Andric           EnumValsTy::const_iterator EI = EnumVals.begin();
13200b57cec5SDimitry Andric           while (EI != EIend && EI->first < RhsVal)
13210b57cec5SDimitry Andric             EI++;
13220b57cec5SDimitry Andric           if (EI == EIend || EI->first != RhsVal) {
13230b57cec5SDimitry Andric             Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
13240b57cec5SDimitry Andric                 << DstType.getUnqualifiedType();
13250b57cec5SDimitry Andric           }
13260b57cec5SDimitry Andric         }
13270b57cec5SDimitry Andric       }
13280b57cec5SDimitry Andric     }
13290b57cec5SDimitry Andric }
13300b57cec5SDimitry Andric 
1331*5ffd83dbSDimitry Andric StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
1332*5ffd83dbSDimitry Andric                                 SourceLocation LParenLoc, ConditionResult Cond,
1333*5ffd83dbSDimitry Andric                                 SourceLocation RParenLoc, Stmt *Body) {
13340b57cec5SDimitry Andric   if (Cond.isInvalid())
13350b57cec5SDimitry Andric     return StmtError();
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric   auto CondVal = Cond.get();
13380b57cec5SDimitry Andric   CheckBreakContinueBinding(CondVal.second);
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   if (CondVal.second &&
13410b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
13420b57cec5SDimitry Andric     CommaVisitor(*this).Visit(CondVal.second);
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric   if (isa<NullStmt>(Body))
13450b57cec5SDimitry Andric     getCurCompoundScope().setHasEmptyLoopBodies();
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1348*5ffd83dbSDimitry Andric                            WhileLoc, LParenLoc, RParenLoc);
13490b57cec5SDimitry Andric }
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric StmtResult
13520b57cec5SDimitry Andric Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
13530b57cec5SDimitry Andric                   SourceLocation WhileLoc, SourceLocation CondLParen,
13540b57cec5SDimitry Andric                   Expr *Cond, SourceLocation CondRParen) {
13550b57cec5SDimitry Andric   assert(Cond && "ActOnDoStmt(): missing expression");
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric   CheckBreakContinueBinding(Cond);
13580b57cec5SDimitry Andric   ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
13590b57cec5SDimitry Andric   if (CondResult.isInvalid())
13600b57cec5SDimitry Andric     return StmtError();
13610b57cec5SDimitry Andric   Cond = CondResult.get();
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric   CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
13640b57cec5SDimitry Andric   if (CondResult.isInvalid())
13650b57cec5SDimitry Andric     return StmtError();
13660b57cec5SDimitry Andric   Cond = CondResult.get();
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   // Only call the CommaVisitor for C89 due to differences in scope flags.
13690b57cec5SDimitry Andric   if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
13700b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
13710b57cec5SDimitry Andric     CommaVisitor(*this).Visit(Cond);
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric   return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
13740b57cec5SDimitry Andric }
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric namespace {
13770b57cec5SDimitry Andric   // Use SetVector since the diagnostic cares about the ordering of the Decl's.
13780b57cec5SDimitry Andric   using DeclSetVector =
13790b57cec5SDimitry Andric       llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
13800b57cec5SDimitry Andric                       llvm::SmallPtrSet<VarDecl *, 8>>;
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   // This visitor will traverse a conditional statement and store all
13830b57cec5SDimitry Andric   // the evaluated decls into a vector.  Simple is set to true if none
13840b57cec5SDimitry Andric   // of the excluded constructs are used.
13850b57cec5SDimitry Andric   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
13860b57cec5SDimitry Andric     DeclSetVector &Decls;
13870b57cec5SDimitry Andric     SmallVectorImpl<SourceRange> &Ranges;
13880b57cec5SDimitry Andric     bool Simple;
13890b57cec5SDimitry Andric   public:
13900b57cec5SDimitry Andric     typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric     DeclExtractor(Sema &S, DeclSetVector &Decls,
13930b57cec5SDimitry Andric                   SmallVectorImpl<SourceRange> &Ranges) :
13940b57cec5SDimitry Andric         Inherited(S.Context),
13950b57cec5SDimitry Andric         Decls(Decls),
13960b57cec5SDimitry Andric         Ranges(Ranges),
13970b57cec5SDimitry Andric         Simple(true) {}
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric     bool isSimple() { return Simple; }
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric     // Replaces the method in EvaluatedExprVisitor.
14020b57cec5SDimitry Andric     void VisitMemberExpr(MemberExpr* E) {
14030b57cec5SDimitry Andric       Simple = false;
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric 
1406*5ffd83dbSDimitry Andric     // Any Stmt not explicitly listed will cause the condition to be marked
1407*5ffd83dbSDimitry Andric     // complex.
1408*5ffd83dbSDimitry Andric     void VisitStmt(Stmt *S) { Simple = false; }
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric     void VisitBinaryOperator(BinaryOperator *E) {
14110b57cec5SDimitry Andric       Visit(E->getLHS());
14120b57cec5SDimitry Andric       Visit(E->getRHS());
14130b57cec5SDimitry Andric     }
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric     void VisitCastExpr(CastExpr *E) {
14160b57cec5SDimitry Andric       Visit(E->getSubExpr());
14170b57cec5SDimitry Andric     }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric     void VisitUnaryOperator(UnaryOperator *E) {
14200b57cec5SDimitry Andric       // Skip checking conditionals with derefernces.
14210b57cec5SDimitry Andric       if (E->getOpcode() == UO_Deref)
14220b57cec5SDimitry Andric         Simple = false;
14230b57cec5SDimitry Andric       else
14240b57cec5SDimitry Andric         Visit(E->getSubExpr());
14250b57cec5SDimitry Andric     }
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric     void VisitConditionalOperator(ConditionalOperator *E) {
14280b57cec5SDimitry Andric       Visit(E->getCond());
14290b57cec5SDimitry Andric       Visit(E->getTrueExpr());
14300b57cec5SDimitry Andric       Visit(E->getFalseExpr());
14310b57cec5SDimitry Andric     }
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric     void VisitParenExpr(ParenExpr *E) {
14340b57cec5SDimitry Andric       Visit(E->getSubExpr());
14350b57cec5SDimitry Andric     }
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
14380b57cec5SDimitry Andric       Visit(E->getOpaqueValue()->getSourceExpr());
14390b57cec5SDimitry Andric       Visit(E->getFalseExpr());
14400b57cec5SDimitry Andric     }
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric     void VisitIntegerLiteral(IntegerLiteral *E) { }
14430b57cec5SDimitry Andric     void VisitFloatingLiteral(FloatingLiteral *E) { }
14440b57cec5SDimitry Andric     void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
14450b57cec5SDimitry Andric     void VisitCharacterLiteral(CharacterLiteral *E) { }
14460b57cec5SDimitry Andric     void VisitGNUNullExpr(GNUNullExpr *E) { }
14470b57cec5SDimitry Andric     void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric     void VisitDeclRefExpr(DeclRefExpr *E) {
14500b57cec5SDimitry Andric       VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
14510b57cec5SDimitry Andric       if (!VD) {
14520b57cec5SDimitry Andric         // Don't allow unhandled Decl types.
14530b57cec5SDimitry Andric         Simple = false;
14540b57cec5SDimitry Andric         return;
14550b57cec5SDimitry Andric       }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric       Ranges.push_back(E->getSourceRange());
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric       Decls.insert(VD);
14600b57cec5SDimitry Andric     }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   }; // end class DeclExtractor
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   // DeclMatcher checks to see if the decls are used in a non-evaluated
14650b57cec5SDimitry Andric   // context.
14660b57cec5SDimitry Andric   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
14670b57cec5SDimitry Andric     DeclSetVector &Decls;
14680b57cec5SDimitry Andric     bool FoundDecl;
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   public:
14710b57cec5SDimitry Andric     typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric     DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
14740b57cec5SDimitry Andric         Inherited(S.Context), Decls(Decls), FoundDecl(false) {
14750b57cec5SDimitry Andric       if (!Statement) return;
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric       Visit(Statement);
14780b57cec5SDimitry Andric     }
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric     void VisitReturnStmt(ReturnStmt *S) {
14810b57cec5SDimitry Andric       FoundDecl = true;
14820b57cec5SDimitry Andric     }
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric     void VisitBreakStmt(BreakStmt *S) {
14850b57cec5SDimitry Andric       FoundDecl = true;
14860b57cec5SDimitry Andric     }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     void VisitGotoStmt(GotoStmt *S) {
14890b57cec5SDimitry Andric       FoundDecl = true;
14900b57cec5SDimitry Andric     }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric     void VisitCastExpr(CastExpr *E) {
14930b57cec5SDimitry Andric       if (E->getCastKind() == CK_LValueToRValue)
14940b57cec5SDimitry Andric         CheckLValueToRValueCast(E->getSubExpr());
14950b57cec5SDimitry Andric       else
14960b57cec5SDimitry Andric         Visit(E->getSubExpr());
14970b57cec5SDimitry Andric     }
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric     void CheckLValueToRValueCast(Expr *E) {
15000b57cec5SDimitry Andric       E = E->IgnoreParenImpCasts();
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric       if (isa<DeclRefExpr>(E)) {
15030b57cec5SDimitry Andric         return;
15040b57cec5SDimitry Andric       }
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
15070b57cec5SDimitry Andric         Visit(CO->getCond());
15080b57cec5SDimitry Andric         CheckLValueToRValueCast(CO->getTrueExpr());
15090b57cec5SDimitry Andric         CheckLValueToRValueCast(CO->getFalseExpr());
15100b57cec5SDimitry Andric         return;
15110b57cec5SDimitry Andric       }
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric       if (BinaryConditionalOperator *BCO =
15140b57cec5SDimitry Andric               dyn_cast<BinaryConditionalOperator>(E)) {
15150b57cec5SDimitry Andric         CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
15160b57cec5SDimitry Andric         CheckLValueToRValueCast(BCO->getFalseExpr());
15170b57cec5SDimitry Andric         return;
15180b57cec5SDimitry Andric       }
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric       Visit(E);
15210b57cec5SDimitry Andric     }
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric     void VisitDeclRefExpr(DeclRefExpr *E) {
15240b57cec5SDimitry Andric       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15250b57cec5SDimitry Andric         if (Decls.count(VD))
15260b57cec5SDimitry Andric           FoundDecl = true;
15270b57cec5SDimitry Andric     }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric     void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
15300b57cec5SDimitry Andric       // Only need to visit the semantics for POE.
15310b57cec5SDimitry Andric       // SyntaticForm doesn't really use the Decal.
15320b57cec5SDimitry Andric       for (auto *S : POE->semantics()) {
15330b57cec5SDimitry Andric         if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
15340b57cec5SDimitry Andric           // Look past the OVE into the expression it binds.
15350b57cec5SDimitry Andric           Visit(OVE->getSourceExpr());
15360b57cec5SDimitry Andric         else
15370b57cec5SDimitry Andric           Visit(S);
15380b57cec5SDimitry Andric       }
15390b57cec5SDimitry Andric     }
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric     bool FoundDeclInUse() { return FoundDecl; }
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric   };  // end class DeclMatcher
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
15460b57cec5SDimitry Andric                                         Expr *Third, Stmt *Body) {
15470b57cec5SDimitry Andric     // Condition is empty
15480b57cec5SDimitry Andric     if (!Second) return;
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric     if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
15510b57cec5SDimitry Andric                           Second->getBeginLoc()))
15520b57cec5SDimitry Andric       return;
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
15550b57cec5SDimitry Andric     DeclSetVector Decls;
15560b57cec5SDimitry Andric     SmallVector<SourceRange, 10> Ranges;
15570b57cec5SDimitry Andric     DeclExtractor DE(S, Decls, Ranges);
15580b57cec5SDimitry Andric     DE.Visit(Second);
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric     // Don't analyze complex conditionals.
15610b57cec5SDimitry Andric     if (!DE.isSimple()) return;
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric     // No decls found.
15640b57cec5SDimitry Andric     if (Decls.size() == 0) return;
15650b57cec5SDimitry Andric 
15660b57cec5SDimitry Andric     // Don't warn on volatile, static, or global variables.
15670b57cec5SDimitry Andric     for (auto *VD : Decls)
15680b57cec5SDimitry Andric       if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
15690b57cec5SDimitry Andric         return;
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
15720b57cec5SDimitry Andric         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
15730b57cec5SDimitry Andric         DeclMatcher(S, Decls, Body).FoundDeclInUse())
15740b57cec5SDimitry Andric       return;
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric     // Load decl names into diagnostic.
15770b57cec5SDimitry Andric     if (Decls.size() > 4) {
15780b57cec5SDimitry Andric       PDiag << 0;
15790b57cec5SDimitry Andric     } else {
15800b57cec5SDimitry Andric       PDiag << (unsigned)Decls.size();
15810b57cec5SDimitry Andric       for (auto *VD : Decls)
15820b57cec5SDimitry Andric         PDiag << VD->getDeclName();
15830b57cec5SDimitry Andric     }
15840b57cec5SDimitry Andric 
15850b57cec5SDimitry Andric     for (auto Range : Ranges)
15860b57cec5SDimitry Andric       PDiag << Range;
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric     S.Diag(Ranges.begin()->getBegin(), PDiag);
15890b57cec5SDimitry Andric   }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   // If Statement is an incemement or decrement, return true and sets the
15920b57cec5SDimitry Andric   // variables Increment and DRE.
15930b57cec5SDimitry Andric   bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
15940b57cec5SDimitry Andric                             DeclRefExpr *&DRE) {
15950b57cec5SDimitry Andric     if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
15960b57cec5SDimitry Andric       if (!Cleanups->cleanupsHaveSideEffects())
15970b57cec5SDimitry Andric         Statement = Cleanups->getSubExpr();
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
16000b57cec5SDimitry Andric       switch (UO->getOpcode()) {
16010b57cec5SDimitry Andric         default: return false;
16020b57cec5SDimitry Andric         case UO_PostInc:
16030b57cec5SDimitry Andric         case UO_PreInc:
16040b57cec5SDimitry Andric           Increment = true;
16050b57cec5SDimitry Andric           break;
16060b57cec5SDimitry Andric         case UO_PostDec:
16070b57cec5SDimitry Andric         case UO_PreDec:
16080b57cec5SDimitry Andric           Increment = false;
16090b57cec5SDimitry Andric           break;
16100b57cec5SDimitry Andric       }
16110b57cec5SDimitry Andric       DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
16120b57cec5SDimitry Andric       return DRE;
16130b57cec5SDimitry Andric     }
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric     if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
16160b57cec5SDimitry Andric       FunctionDecl *FD = Call->getDirectCallee();
16170b57cec5SDimitry Andric       if (!FD || !FD->isOverloadedOperator()) return false;
16180b57cec5SDimitry Andric       switch (FD->getOverloadedOperator()) {
16190b57cec5SDimitry Andric         default: return false;
16200b57cec5SDimitry Andric         case OO_PlusPlus:
16210b57cec5SDimitry Andric           Increment = true;
16220b57cec5SDimitry Andric           break;
16230b57cec5SDimitry Andric         case OO_MinusMinus:
16240b57cec5SDimitry Andric           Increment = false;
16250b57cec5SDimitry Andric           break;
16260b57cec5SDimitry Andric       }
16270b57cec5SDimitry Andric       DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
16280b57cec5SDimitry Andric       return DRE;
16290b57cec5SDimitry Andric     }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric     return false;
16320b57cec5SDimitry Andric   }
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric   // A visitor to determine if a continue or break statement is a
16350b57cec5SDimitry Andric   // subexpression.
16360b57cec5SDimitry Andric   class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
16370b57cec5SDimitry Andric     SourceLocation BreakLoc;
16380b57cec5SDimitry Andric     SourceLocation ContinueLoc;
16390b57cec5SDimitry Andric     bool InSwitch = false;
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   public:
16420b57cec5SDimitry Andric     BreakContinueFinder(Sema &S, const Stmt* Body) :
16430b57cec5SDimitry Andric         Inherited(S.Context) {
16440b57cec5SDimitry Andric       Visit(Body);
16450b57cec5SDimitry Andric     }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric     typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric     void VisitContinueStmt(const ContinueStmt* E) {
16500b57cec5SDimitry Andric       ContinueLoc = E->getContinueLoc();
16510b57cec5SDimitry Andric     }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric     void VisitBreakStmt(const BreakStmt* E) {
16540b57cec5SDimitry Andric       if (!InSwitch)
16550b57cec5SDimitry Andric         BreakLoc = E->getBreakLoc();
16560b57cec5SDimitry Andric     }
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric     void VisitSwitchStmt(const SwitchStmt* S) {
16590b57cec5SDimitry Andric       if (const Stmt *Init = S->getInit())
16600b57cec5SDimitry Andric         Visit(Init);
16610b57cec5SDimitry Andric       if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
16620b57cec5SDimitry Andric         Visit(CondVar);
16630b57cec5SDimitry Andric       if (const Stmt *Cond = S->getCond())
16640b57cec5SDimitry Andric         Visit(Cond);
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric       // Don't return break statements from the body of a switch.
16670b57cec5SDimitry Andric       InSwitch = true;
16680b57cec5SDimitry Andric       if (const Stmt *Body = S->getBody())
16690b57cec5SDimitry Andric         Visit(Body);
16700b57cec5SDimitry Andric       InSwitch = false;
16710b57cec5SDimitry Andric     }
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric     void VisitForStmt(const ForStmt *S) {
16740b57cec5SDimitry Andric       // Only visit the init statement of a for loop; the body
16750b57cec5SDimitry Andric       // has a different break/continue scope.
16760b57cec5SDimitry Andric       if (const Stmt *Init = S->getInit())
16770b57cec5SDimitry Andric         Visit(Init);
16780b57cec5SDimitry Andric     }
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric     void VisitWhileStmt(const WhileStmt *) {
16810b57cec5SDimitry Andric       // Do nothing; the children of a while loop have a different
16820b57cec5SDimitry Andric       // break/continue scope.
16830b57cec5SDimitry Andric     }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric     void VisitDoStmt(const DoStmt *) {
16860b57cec5SDimitry Andric       // Do nothing; the children of a while loop have a different
16870b57cec5SDimitry Andric       // break/continue scope.
16880b57cec5SDimitry Andric     }
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric     void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
16910b57cec5SDimitry Andric       // Only visit the initialization of a for loop; the body
16920b57cec5SDimitry Andric       // has a different break/continue scope.
16930b57cec5SDimitry Andric       if (const Stmt *Init = S->getInit())
16940b57cec5SDimitry Andric         Visit(Init);
16950b57cec5SDimitry Andric       if (const Stmt *Range = S->getRangeStmt())
16960b57cec5SDimitry Andric         Visit(Range);
16970b57cec5SDimitry Andric       if (const Stmt *Begin = S->getBeginStmt())
16980b57cec5SDimitry Andric         Visit(Begin);
16990b57cec5SDimitry Andric       if (const Stmt *End = S->getEndStmt())
17000b57cec5SDimitry Andric         Visit(End);
17010b57cec5SDimitry Andric     }
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric     void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
17040b57cec5SDimitry Andric       // Only visit the initialization of a for loop; the body
17050b57cec5SDimitry Andric       // has a different break/continue scope.
17060b57cec5SDimitry Andric       if (const Stmt *Element = S->getElement())
17070b57cec5SDimitry Andric         Visit(Element);
17080b57cec5SDimitry Andric       if (const Stmt *Collection = S->getCollection())
17090b57cec5SDimitry Andric         Visit(Collection);
17100b57cec5SDimitry Andric     }
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric     bool ContinueFound() { return ContinueLoc.isValid(); }
17130b57cec5SDimitry Andric     bool BreakFound() { return BreakLoc.isValid(); }
17140b57cec5SDimitry Andric     SourceLocation GetContinueLoc() { return ContinueLoc; }
17150b57cec5SDimitry Andric     SourceLocation GetBreakLoc() { return BreakLoc; }
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   };  // end class BreakContinueFinder
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   // Emit a warning when a loop increment/decrement appears twice per loop
17200b57cec5SDimitry Andric   // iteration.  The conditions which trigger this warning are:
17210b57cec5SDimitry Andric   // 1) The last statement in the loop body and the third expression in the
17220b57cec5SDimitry Andric   //    for loop are both increment or both decrement of the same variable
17230b57cec5SDimitry Andric   // 2) No continue statements in the loop body.
17240b57cec5SDimitry Andric   void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
17250b57cec5SDimitry Andric     // Return when there is nothing to check.
17260b57cec5SDimitry Andric     if (!Body || !Third) return;
17270b57cec5SDimitry Andric 
17280b57cec5SDimitry Andric     if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
17290b57cec5SDimitry Andric                           Third->getBeginLoc()))
17300b57cec5SDimitry Andric       return;
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric     // Get the last statement from the loop body.
17330b57cec5SDimitry Andric     CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
17340b57cec5SDimitry Andric     if (!CS || CS->body_empty()) return;
17350b57cec5SDimitry Andric     Stmt *LastStmt = CS->body_back();
17360b57cec5SDimitry Andric     if (!LastStmt) return;
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric     bool LoopIncrement, LastIncrement;
17390b57cec5SDimitry Andric     DeclRefExpr *LoopDRE, *LastDRE;
17400b57cec5SDimitry Andric 
17410b57cec5SDimitry Andric     if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
17420b57cec5SDimitry Andric     if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric     // Check that the two statements are both increments or both decrements
17450b57cec5SDimitry Andric     // on the same variable.
17460b57cec5SDimitry Andric     if (LoopIncrement != LastIncrement ||
17470b57cec5SDimitry Andric         LoopDRE->getDecl() != LastDRE->getDecl()) return;
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric     if (BreakContinueFinder(S, Body).ContinueFound()) return;
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric     S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
17520b57cec5SDimitry Andric          << LastDRE->getDecl() << LastIncrement;
17530b57cec5SDimitry Andric     S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
17540b57cec5SDimitry Andric          << LoopIncrement;
17550b57cec5SDimitry Andric   }
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric } // end namespace
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric void Sema::CheckBreakContinueBinding(Expr *E) {
17610b57cec5SDimitry Andric   if (!E || getLangOpts().CPlusPlus)
17620b57cec5SDimitry Andric     return;
17630b57cec5SDimitry Andric   BreakContinueFinder BCFinder(*this, E);
17640b57cec5SDimitry Andric   Scope *BreakParent = CurScope->getBreakParent();
17650b57cec5SDimitry Andric   if (BCFinder.BreakFound() && BreakParent) {
17660b57cec5SDimitry Andric     if (BreakParent->getFlags() & Scope::SwitchScope) {
17670b57cec5SDimitry Andric       Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
17680b57cec5SDimitry Andric     } else {
17690b57cec5SDimitry Andric       Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
17700b57cec5SDimitry Andric           << "break";
17710b57cec5SDimitry Andric     }
17720b57cec5SDimitry Andric   } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
17730b57cec5SDimitry Andric     Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
17740b57cec5SDimitry Andric         << "continue";
17750b57cec5SDimitry Andric   }
17760b57cec5SDimitry Andric }
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
17790b57cec5SDimitry Andric                               Stmt *First, ConditionResult Second,
17800b57cec5SDimitry Andric                               FullExprArg third, SourceLocation RParenLoc,
17810b57cec5SDimitry Andric                               Stmt *Body) {
17820b57cec5SDimitry Andric   if (Second.isInvalid())
17830b57cec5SDimitry Andric     return StmtError();
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus) {
17860b57cec5SDimitry Andric     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
17870b57cec5SDimitry Andric       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
17880b57cec5SDimitry Andric       // declare identifiers for objects having storage class 'auto' or
17890b57cec5SDimitry Andric       // 'register'.
17900b57cec5SDimitry Andric       for (auto *DI : DS->decls()) {
17910b57cec5SDimitry Andric         VarDecl *VD = dyn_cast<VarDecl>(DI);
17920b57cec5SDimitry Andric         if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
17930b57cec5SDimitry Andric           VD = nullptr;
17940b57cec5SDimitry Andric         if (!VD) {
17950b57cec5SDimitry Andric           Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
17960b57cec5SDimitry Andric           DI->setInvalidDecl();
17970b57cec5SDimitry Andric         }
17980b57cec5SDimitry Andric       }
17990b57cec5SDimitry Andric     }
18000b57cec5SDimitry Andric   }
18010b57cec5SDimitry Andric 
18020b57cec5SDimitry Andric   CheckBreakContinueBinding(Second.get().second);
18030b57cec5SDimitry Andric   CheckBreakContinueBinding(third.get());
18040b57cec5SDimitry Andric 
18050b57cec5SDimitry Andric   if (!Second.get().first)
18060b57cec5SDimitry Andric     CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
18070b57cec5SDimitry Andric                                      Body);
18080b57cec5SDimitry Andric   CheckForRedundantIteration(*this, third.get(), Body);
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric   if (Second.get().second &&
18110b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator,
18120b57cec5SDimitry Andric                        Second.get().second->getExprLoc()))
18130b57cec5SDimitry Andric     CommaVisitor(*this).Visit(Second.get().second);
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   Expr *Third  = third.release().getAs<Expr>();
18160b57cec5SDimitry Andric   if (isa<NullStmt>(Body))
18170b57cec5SDimitry Andric     getCurCompoundScope().setHasEmptyLoopBodies();
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   return new (Context)
18200b57cec5SDimitry Andric       ForStmt(Context, First, Second.get().second, Second.get().first, Third,
18210b57cec5SDimitry Andric               Body, ForLoc, LParenLoc, RParenLoc);
18220b57cec5SDimitry Andric }
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric /// In an Objective C collection iteration statement:
18250b57cec5SDimitry Andric ///   for (x in y)
18260b57cec5SDimitry Andric /// x can be an arbitrary l-value expression.  Bind it up as a
18270b57cec5SDimitry Andric /// full-expression.
18280b57cec5SDimitry Andric StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
18290b57cec5SDimitry Andric   // Reduce placeholder expressions here.  Note that this rejects the
18300b57cec5SDimitry Andric   // use of pseudo-object l-values in this position.
18310b57cec5SDimitry Andric   ExprResult result = CheckPlaceholderExpr(E);
18320b57cec5SDimitry Andric   if (result.isInvalid()) return StmtError();
18330b57cec5SDimitry Andric   E = result.get();
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
18360b57cec5SDimitry Andric   if (FullExpr.isInvalid())
18370b57cec5SDimitry Andric     return StmtError();
18380b57cec5SDimitry Andric   return StmtResult(static_cast<Stmt*>(FullExpr.get()));
18390b57cec5SDimitry Andric }
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric ExprResult
18420b57cec5SDimitry Andric Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
18430b57cec5SDimitry Andric   if (!collection)
18440b57cec5SDimitry Andric     return ExprError();
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric   ExprResult result = CorrectDelayedTyposInExpr(collection);
18470b57cec5SDimitry Andric   if (!result.isUsable())
18480b57cec5SDimitry Andric     return ExprError();
18490b57cec5SDimitry Andric   collection = result.get();
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   // Bail out early if we've got a type-dependent expression.
18520b57cec5SDimitry Andric   if (collection->isTypeDependent()) return collection;
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   // Perform normal l-value conversion.
18550b57cec5SDimitry Andric   result = DefaultFunctionArrayLvalueConversion(collection);
18560b57cec5SDimitry Andric   if (result.isInvalid())
18570b57cec5SDimitry Andric     return ExprError();
18580b57cec5SDimitry Andric   collection = result.get();
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric   // The operand needs to have object-pointer type.
18610b57cec5SDimitry Andric   // TODO: should we do a contextual conversion?
18620b57cec5SDimitry Andric   const ObjCObjectPointerType *pointerType =
18630b57cec5SDimitry Andric     collection->getType()->getAs<ObjCObjectPointerType>();
18640b57cec5SDimitry Andric   if (!pointerType)
18650b57cec5SDimitry Andric     return Diag(forLoc, diag::err_collection_expr_type)
18660b57cec5SDimitry Andric              << collection->getType() << collection->getSourceRange();
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   // Check that the operand provides
18690b57cec5SDimitry Andric   //   - countByEnumeratingWithState:objects:count:
18700b57cec5SDimitry Andric   const ObjCObjectType *objectType = pointerType->getObjectType();
18710b57cec5SDimitry Andric   ObjCInterfaceDecl *iface = objectType->getInterface();
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric   // If we have a forward-declared type, we can't do this check.
18740b57cec5SDimitry Andric   // Under ARC, it is an error not to have a forward-declared class.
18750b57cec5SDimitry Andric   if (iface &&
18760b57cec5SDimitry Andric       (getLangOpts().ObjCAutoRefCount
18770b57cec5SDimitry Andric            ? RequireCompleteType(forLoc, QualType(objectType, 0),
18780b57cec5SDimitry Andric                                  diag::err_arc_collection_forward, collection)
18790b57cec5SDimitry Andric            : !isCompleteType(forLoc, QualType(objectType, 0)))) {
18800b57cec5SDimitry Andric     // Otherwise, if we have any useful type information, check that
18810b57cec5SDimitry Andric     // the type declares the appropriate method.
18820b57cec5SDimitry Andric   } else if (iface || !objectType->qual_empty()) {
18830b57cec5SDimitry Andric     IdentifierInfo *selectorIdents[] = {
18840b57cec5SDimitry Andric       &Context.Idents.get("countByEnumeratingWithState"),
18850b57cec5SDimitry Andric       &Context.Idents.get("objects"),
18860b57cec5SDimitry Andric       &Context.Idents.get("count")
18870b57cec5SDimitry Andric     };
18880b57cec5SDimitry Andric     Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
18890b57cec5SDimitry Andric 
18900b57cec5SDimitry Andric     ObjCMethodDecl *method = nullptr;
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric     // If there's an interface, look in both the public and private APIs.
18930b57cec5SDimitry Andric     if (iface) {
18940b57cec5SDimitry Andric       method = iface->lookupInstanceMethod(selector);
18950b57cec5SDimitry Andric       if (!method) method = iface->lookupPrivateMethod(selector);
18960b57cec5SDimitry Andric     }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric     // Also check protocol qualifiers.
18990b57cec5SDimitry Andric     if (!method)
19000b57cec5SDimitry Andric       method = LookupMethodInQualifiedType(selector, pointerType,
19010b57cec5SDimitry Andric                                            /*instance*/ true);
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric     // If we didn't find it anywhere, give up.
19040b57cec5SDimitry Andric     if (!method) {
19050b57cec5SDimitry Andric       Diag(forLoc, diag::warn_collection_expr_type)
19060b57cec5SDimitry Andric         << collection->getType() << selector << collection->getSourceRange();
19070b57cec5SDimitry Andric     }
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric     // TODO: check for an incompatible signature?
19100b57cec5SDimitry Andric   }
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   // Wrap up any cleanups in the expression.
19130b57cec5SDimitry Andric   return collection;
19140b57cec5SDimitry Andric }
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric StmtResult
19170b57cec5SDimitry Andric Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
19180b57cec5SDimitry Andric                                  Stmt *First, Expr *collection,
19190b57cec5SDimitry Andric                                  SourceLocation RParenLoc) {
19200b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
19210b57cec5SDimitry Andric 
19220b57cec5SDimitry Andric   ExprResult CollectionExprResult =
19230b57cec5SDimitry Andric     CheckObjCForCollectionOperand(ForLoc, collection);
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric   if (First) {
19260b57cec5SDimitry Andric     QualType FirstType;
19270b57cec5SDimitry Andric     if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
19280b57cec5SDimitry Andric       if (!DS->isSingleDecl())
19290b57cec5SDimitry Andric         return StmtError(Diag((*DS->decl_begin())->getLocation(),
19300b57cec5SDimitry Andric                          diag::err_toomany_element_decls));
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric       VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
19330b57cec5SDimitry Andric       if (!D || D->isInvalidDecl())
19340b57cec5SDimitry Andric         return StmtError();
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric       FirstType = D->getType();
19370b57cec5SDimitry Andric       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
19380b57cec5SDimitry Andric       // declare identifiers for objects having storage class 'auto' or
19390b57cec5SDimitry Andric       // 'register'.
19400b57cec5SDimitry Andric       if (!D->hasLocalStorage())
19410b57cec5SDimitry Andric         return StmtError(Diag(D->getLocation(),
19420b57cec5SDimitry Andric                               diag::err_non_local_variable_decl_in_for));
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric       // If the type contained 'auto', deduce the 'auto' to 'id'.
19450b57cec5SDimitry Andric       if (FirstType->getContainedAutoType()) {
19460b57cec5SDimitry Andric         OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
19470b57cec5SDimitry Andric                                  VK_RValue);
19480b57cec5SDimitry Andric         Expr *DeducedInit = &OpaqueId;
19490b57cec5SDimitry Andric         if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
19500b57cec5SDimitry Andric                 DAR_Failed)
19510b57cec5SDimitry Andric           DiagnoseAutoDeductionFailure(D, DeducedInit);
19520b57cec5SDimitry Andric         if (FirstType.isNull()) {
19530b57cec5SDimitry Andric           D->setInvalidDecl();
19540b57cec5SDimitry Andric           return StmtError();
19550b57cec5SDimitry Andric         }
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric         D->setType(FirstType);
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric         if (!inTemplateInstantiation()) {
19600b57cec5SDimitry Andric           SourceLocation Loc =
19610b57cec5SDimitry Andric               D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
19620b57cec5SDimitry Andric           Diag(Loc, diag::warn_auto_var_is_id)
19630b57cec5SDimitry Andric             << D->getDeclName();
19640b57cec5SDimitry Andric         }
19650b57cec5SDimitry Andric       }
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric     } else {
19680b57cec5SDimitry Andric       Expr *FirstE = cast<Expr>(First);
19690b57cec5SDimitry Andric       if (!FirstE->isTypeDependent() && !FirstE->isLValue())
19700b57cec5SDimitry Andric         return StmtError(
19710b57cec5SDimitry Andric             Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
19720b57cec5SDimitry Andric             << First->getSourceRange());
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric       FirstType = static_cast<Expr*>(First)->getType();
19750b57cec5SDimitry Andric       if (FirstType.isConstQualified())
19760b57cec5SDimitry Andric         Diag(ForLoc, diag::err_selector_element_const_type)
19770b57cec5SDimitry Andric           << FirstType << First->getSourceRange();
19780b57cec5SDimitry Andric     }
19790b57cec5SDimitry Andric     if (!FirstType->isDependentType() &&
19800b57cec5SDimitry Andric         !FirstType->isObjCObjectPointerType() &&
19810b57cec5SDimitry Andric         !FirstType->isBlockPointerType())
19820b57cec5SDimitry Andric         return StmtError(Diag(ForLoc, diag::err_selector_element_type)
19830b57cec5SDimitry Andric                            << FirstType << First->getSourceRange());
19840b57cec5SDimitry Andric   }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   if (CollectionExprResult.isInvalid())
19870b57cec5SDimitry Andric     return StmtError();
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric   CollectionExprResult =
19900b57cec5SDimitry Andric       ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
19910b57cec5SDimitry Andric   if (CollectionExprResult.isInvalid())
19920b57cec5SDimitry Andric     return StmtError();
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric   return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
19950b57cec5SDimitry Andric                                              nullptr, ForLoc, RParenLoc);
19960b57cec5SDimitry Andric }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric /// Finish building a variable declaration for a for-range statement.
19990b57cec5SDimitry Andric /// \return true if an error occurs.
20000b57cec5SDimitry Andric static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
20010b57cec5SDimitry Andric                                   SourceLocation Loc, int DiagID) {
20020b57cec5SDimitry Andric   if (Decl->getType()->isUndeducedType()) {
20030b57cec5SDimitry Andric     ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
20040b57cec5SDimitry Andric     if (!Res.isUsable()) {
20050b57cec5SDimitry Andric       Decl->setInvalidDecl();
20060b57cec5SDimitry Andric       return true;
20070b57cec5SDimitry Andric     }
20080b57cec5SDimitry Andric     Init = Res.get();
20090b57cec5SDimitry Andric   }
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   // Deduce the type for the iterator variable now rather than leaving it to
20120b57cec5SDimitry Andric   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
20130b57cec5SDimitry Andric   QualType InitType;
20140b57cec5SDimitry Andric   if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
20150b57cec5SDimitry Andric       SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
20160b57cec5SDimitry Andric           Sema::DAR_Failed)
20170b57cec5SDimitry Andric     SemaRef.Diag(Loc, DiagID) << Init->getType();
20180b57cec5SDimitry Andric   if (InitType.isNull()) {
20190b57cec5SDimitry Andric     Decl->setInvalidDecl();
20200b57cec5SDimitry Andric     return true;
20210b57cec5SDimitry Andric   }
20220b57cec5SDimitry Andric   Decl->setType(InitType);
20230b57cec5SDimitry Andric 
20240b57cec5SDimitry Andric   // In ARC, infer lifetime.
20250b57cec5SDimitry Andric   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
20260b57cec5SDimitry Andric   // we're doing the equivalent of fast iteration.
20270b57cec5SDimitry Andric   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
20280b57cec5SDimitry Andric       SemaRef.inferObjCARCLifetime(Decl))
20290b57cec5SDimitry Andric     Decl->setInvalidDecl();
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
20320b57cec5SDimitry Andric   SemaRef.FinalizeDeclaration(Decl);
20330b57cec5SDimitry Andric   SemaRef.CurContext->addHiddenDecl(Decl);
20340b57cec5SDimitry Andric   return false;
20350b57cec5SDimitry Andric }
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric namespace {
20380b57cec5SDimitry Andric // An enum to represent whether something is dealing with a call to begin()
20390b57cec5SDimitry Andric // or a call to end() in a range-based for loop.
20400b57cec5SDimitry Andric enum BeginEndFunction {
20410b57cec5SDimitry Andric   BEF_begin,
20420b57cec5SDimitry Andric   BEF_end
20430b57cec5SDimitry Andric };
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric /// Produce a note indicating which begin/end function was implicitly called
20460b57cec5SDimitry Andric /// by a C++11 for-range statement. This is often not obvious from the code,
20470b57cec5SDimitry Andric /// nor from the diagnostics produced when analysing the implicit expressions
20480b57cec5SDimitry Andric /// required in a for-range statement.
20490b57cec5SDimitry Andric void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
20500b57cec5SDimitry Andric                                   BeginEndFunction BEF) {
20510b57cec5SDimitry Andric   CallExpr *CE = dyn_cast<CallExpr>(E);
20520b57cec5SDimitry Andric   if (!CE)
20530b57cec5SDimitry Andric     return;
20540b57cec5SDimitry Andric   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
20550b57cec5SDimitry Andric   if (!D)
20560b57cec5SDimitry Andric     return;
20570b57cec5SDimitry Andric   SourceLocation Loc = D->getLocation();
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric   std::string Description;
20600b57cec5SDimitry Andric   bool IsTemplate = false;
20610b57cec5SDimitry Andric   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
20620b57cec5SDimitry Andric     Description = SemaRef.getTemplateArgumentBindingsText(
20630b57cec5SDimitry Andric       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
20640b57cec5SDimitry Andric     IsTemplate = true;
20650b57cec5SDimitry Andric   }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
20680b57cec5SDimitry Andric     << BEF << IsTemplate << Description << E->getType();
20690b57cec5SDimitry Andric }
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric /// Build a variable declaration for a for-range statement.
20720b57cec5SDimitry Andric VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
20730b57cec5SDimitry Andric                               QualType Type, StringRef Name) {
20740b57cec5SDimitry Andric   DeclContext *DC = SemaRef.CurContext;
20750b57cec5SDimitry Andric   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
20760b57cec5SDimitry Andric   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
20770b57cec5SDimitry Andric   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
20780b57cec5SDimitry Andric                                   TInfo, SC_None);
20790b57cec5SDimitry Andric   Decl->setImplicit();
20800b57cec5SDimitry Andric   return Decl;
20810b57cec5SDimitry Andric }
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric static bool ObjCEnumerationCollection(Expr *Collection) {
20860b57cec5SDimitry Andric   return !Collection->isTypeDependent()
20870b57cec5SDimitry Andric           && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
20880b57cec5SDimitry Andric }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
20910b57cec5SDimitry Andric ///
20920b57cec5SDimitry Andric /// C++11 [stmt.ranged]:
20930b57cec5SDimitry Andric ///   A range-based for statement is equivalent to
20940b57cec5SDimitry Andric ///
20950b57cec5SDimitry Andric ///   {
20960b57cec5SDimitry Andric ///     auto && __range = range-init;
20970b57cec5SDimitry Andric ///     for ( auto __begin = begin-expr,
20980b57cec5SDimitry Andric ///           __end = end-expr;
20990b57cec5SDimitry Andric ///           __begin != __end;
21000b57cec5SDimitry Andric ///           ++__begin ) {
21010b57cec5SDimitry Andric ///       for-range-declaration = *__begin;
21020b57cec5SDimitry Andric ///       statement
21030b57cec5SDimitry Andric ///     }
21040b57cec5SDimitry Andric ///   }
21050b57cec5SDimitry Andric ///
21060b57cec5SDimitry Andric /// The body of the loop is not available yet, since it cannot be analysed until
21070b57cec5SDimitry Andric /// we have determined the type of the for-range-declaration.
21080b57cec5SDimitry Andric StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
21090b57cec5SDimitry Andric                                       SourceLocation CoawaitLoc, Stmt *InitStmt,
21100b57cec5SDimitry Andric                                       Stmt *First, SourceLocation ColonLoc,
21110b57cec5SDimitry Andric                                       Expr *Range, SourceLocation RParenLoc,
21120b57cec5SDimitry Andric                                       BuildForRangeKind Kind) {
21130b57cec5SDimitry Andric   if (!First)
21140b57cec5SDimitry Andric     return StmtError();
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric   if (Range && ObjCEnumerationCollection(Range)) {
21170b57cec5SDimitry Andric     // FIXME: Support init-statements in Objective-C++20 ranged for statement.
21180b57cec5SDimitry Andric     if (InitStmt)
21190b57cec5SDimitry Andric       return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
21200b57cec5SDimitry Andric                  << InitStmt->getSourceRange();
21210b57cec5SDimitry Andric     return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
21220b57cec5SDimitry Andric   }
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   DeclStmt *DS = dyn_cast<DeclStmt>(First);
21250b57cec5SDimitry Andric   assert(DS && "first part of for range not a decl stmt");
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   if (!DS->isSingleDecl()) {
21280b57cec5SDimitry Andric     Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
21290b57cec5SDimitry Andric     return StmtError();
21300b57cec5SDimitry Andric   }
21310b57cec5SDimitry Andric 
2132*5ffd83dbSDimitry Andric   // This function is responsible for attaching an initializer to LoopVar. We
2133*5ffd83dbSDimitry Andric   // must call ActOnInitializerError if we fail to do so.
21340b57cec5SDimitry Andric   Decl *LoopVar = DS->getSingleDecl();
21350b57cec5SDimitry Andric   if (LoopVar->isInvalidDecl() || !Range ||
21360b57cec5SDimitry Andric       DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2137*5ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
21380b57cec5SDimitry Andric     return StmtError();
21390b57cec5SDimitry Andric   }
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric   // Build the coroutine state immediately and not later during template
21420b57cec5SDimitry Andric   // instantiation
21430b57cec5SDimitry Andric   if (!CoawaitLoc.isInvalid()) {
2144*5ffd83dbSDimitry Andric     if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
2145*5ffd83dbSDimitry Andric       ActOnInitializerError(LoopVar);
21460b57cec5SDimitry Andric       return StmtError();
21470b57cec5SDimitry Andric     }
2148*5ffd83dbSDimitry Andric   }
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   // Build  auto && __range = range-init
21510b57cec5SDimitry Andric   // Divide by 2, since the variables are in the inner scope (loop body).
21520b57cec5SDimitry Andric   const auto DepthStr = std::to_string(S->getDepth() / 2);
21530b57cec5SDimitry Andric   SourceLocation RangeLoc = Range->getBeginLoc();
21540b57cec5SDimitry Andric   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
21550b57cec5SDimitry Andric                                            Context.getAutoRRefDeductType(),
21560b57cec5SDimitry Andric                                            std::string("__range") + DepthStr);
21570b57cec5SDimitry Andric   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
21580b57cec5SDimitry Andric                             diag::err_for_range_deduction_failure)) {
2159*5ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
21600b57cec5SDimitry Andric     return StmtError();
21610b57cec5SDimitry Andric   }
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   // Claim the type doesn't contain auto: we've already done the checking.
21640b57cec5SDimitry Andric   DeclGroupPtrTy RangeGroup =
21650b57cec5SDimitry Andric       BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
21660b57cec5SDimitry Andric   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
21670b57cec5SDimitry Andric   if (RangeDecl.isInvalid()) {
2168*5ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
21690b57cec5SDimitry Andric     return StmtError();
21700b57cec5SDimitry Andric   }
21710b57cec5SDimitry Andric 
2172*5ffd83dbSDimitry Andric   StmtResult R = BuildCXXForRangeStmt(
21730b57cec5SDimitry Andric       ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
21740b57cec5SDimitry Andric       /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
21750b57cec5SDimitry Andric       /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2176*5ffd83dbSDimitry Andric   if (R.isInvalid()) {
2177*5ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
2178*5ffd83dbSDimitry Andric     return StmtError();
2179*5ffd83dbSDimitry Andric   }
2180*5ffd83dbSDimitry Andric 
2181*5ffd83dbSDimitry Andric   return R;
21820b57cec5SDimitry Andric }
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric /// Create the initialization, compare, and increment steps for
21850b57cec5SDimitry Andric /// the range-based for loop expression.
21860b57cec5SDimitry Andric /// This function does not handle array-based for loops,
21870b57cec5SDimitry Andric /// which are created in Sema::BuildCXXForRangeStmt.
21880b57cec5SDimitry Andric ///
21890b57cec5SDimitry Andric /// \returns a ForRangeStatus indicating success or what kind of error occurred.
21900b57cec5SDimitry Andric /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
21910b57cec5SDimitry Andric /// CandidateSet and BEF are set and some non-success value is returned on
21920b57cec5SDimitry Andric /// failure.
21930b57cec5SDimitry Andric static Sema::ForRangeStatus
21940b57cec5SDimitry Andric BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
21950b57cec5SDimitry Andric                       QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
21960b57cec5SDimitry Andric                       SourceLocation ColonLoc, SourceLocation CoawaitLoc,
21970b57cec5SDimitry Andric                       OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
21980b57cec5SDimitry Andric                       ExprResult *EndExpr, BeginEndFunction *BEF) {
21990b57cec5SDimitry Andric   DeclarationNameInfo BeginNameInfo(
22000b57cec5SDimitry Andric       &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
22010b57cec5SDimitry Andric   DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
22020b57cec5SDimitry Andric                                   ColonLoc);
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
22050b57cec5SDimitry Andric                                  Sema::LookupMemberName);
22060b57cec5SDimitry Andric   LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   auto BuildBegin = [&] {
22090b57cec5SDimitry Andric     *BEF = BEF_begin;
22100b57cec5SDimitry Andric     Sema::ForRangeStatus RangeStatus =
22110b57cec5SDimitry Andric         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
22120b57cec5SDimitry Andric                                           BeginMemberLookup, CandidateSet,
22130b57cec5SDimitry Andric                                           BeginRange, BeginExpr);
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric     if (RangeStatus != Sema::FRS_Success) {
22160b57cec5SDimitry Andric       if (RangeStatus == Sema::FRS_DiagnosticIssued)
22170b57cec5SDimitry Andric         SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
22180b57cec5SDimitry Andric             << ColonLoc << BEF_begin << BeginRange->getType();
22190b57cec5SDimitry Andric       return RangeStatus;
22200b57cec5SDimitry Andric     }
22210b57cec5SDimitry Andric     if (!CoawaitLoc.isInvalid()) {
22220b57cec5SDimitry Andric       // FIXME: getCurScope() should not be used during template instantiation.
22230b57cec5SDimitry Andric       // We should pick up the set of unqualified lookup results for operator
22240b57cec5SDimitry Andric       // co_await during the initial parse.
22250b57cec5SDimitry Andric       *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
22260b57cec5SDimitry Andric                                             BeginExpr->get());
22270b57cec5SDimitry Andric       if (BeginExpr->isInvalid())
22280b57cec5SDimitry Andric         return Sema::FRS_DiagnosticIssued;
22290b57cec5SDimitry Andric     }
22300b57cec5SDimitry Andric     if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
22310b57cec5SDimitry Andric                               diag::err_for_range_iter_deduction_failure)) {
22320b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
22330b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
22340b57cec5SDimitry Andric     }
22350b57cec5SDimitry Andric     return Sema::FRS_Success;
22360b57cec5SDimitry Andric   };
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric   auto BuildEnd = [&] {
22390b57cec5SDimitry Andric     *BEF = BEF_end;
22400b57cec5SDimitry Andric     Sema::ForRangeStatus RangeStatus =
22410b57cec5SDimitry Andric         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
22420b57cec5SDimitry Andric                                           EndMemberLookup, CandidateSet,
22430b57cec5SDimitry Andric                                           EndRange, EndExpr);
22440b57cec5SDimitry Andric     if (RangeStatus != Sema::FRS_Success) {
22450b57cec5SDimitry Andric       if (RangeStatus == Sema::FRS_DiagnosticIssued)
22460b57cec5SDimitry Andric         SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
22470b57cec5SDimitry Andric             << ColonLoc << BEF_end << EndRange->getType();
22480b57cec5SDimitry Andric       return RangeStatus;
22490b57cec5SDimitry Andric     }
22500b57cec5SDimitry Andric     if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
22510b57cec5SDimitry Andric                               diag::err_for_range_iter_deduction_failure)) {
22520b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
22530b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
22540b57cec5SDimitry Andric     }
22550b57cec5SDimitry Andric     return Sema::FRS_Success;
22560b57cec5SDimitry Andric   };
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric   if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
22590b57cec5SDimitry Andric     // - if _RangeT is a class type, the unqualified-ids begin and end are
22600b57cec5SDimitry Andric     //   looked up in the scope of class _RangeT as if by class member access
22610b57cec5SDimitry Andric     //   lookup (3.4.5), and if either (or both) finds at least one
22620b57cec5SDimitry Andric     //   declaration, begin-expr and end-expr are __range.begin() and
22630b57cec5SDimitry Andric     //   __range.end(), respectively;
22640b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(BeginMemberLookup, D);
22650b57cec5SDimitry Andric     if (BeginMemberLookup.isAmbiguous())
22660b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(EndMemberLookup, D);
22690b57cec5SDimitry Andric     if (EndMemberLookup.isAmbiguous())
22700b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric     if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
22730b57cec5SDimitry Andric       // Look up the non-member form of the member we didn't find, first.
22740b57cec5SDimitry Andric       // This way we prefer a "no viable 'end'" diagnostic over a "i found
22750b57cec5SDimitry Andric       // a 'begin' but ignored it because there was no member 'end'"
22760b57cec5SDimitry Andric       // diagnostic.
22770b57cec5SDimitry Andric       auto BuildNonmember = [&](
22780b57cec5SDimitry Andric           BeginEndFunction BEFFound, LookupResult &Found,
22790b57cec5SDimitry Andric           llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
22800b57cec5SDimitry Andric           llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
22810b57cec5SDimitry Andric         LookupResult OldFound = std::move(Found);
22820b57cec5SDimitry Andric         Found.clear();
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric         if (Sema::ForRangeStatus Result = BuildNotFound())
22850b57cec5SDimitry Andric           return Result;
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric         switch (BuildFound()) {
22880b57cec5SDimitry Andric         case Sema::FRS_Success:
22890b57cec5SDimitry Andric           return Sema::FRS_Success;
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric         case Sema::FRS_NoViableFunction:
22920b57cec5SDimitry Andric           CandidateSet->NoteCandidates(
22930b57cec5SDimitry Andric               PartialDiagnosticAt(BeginRange->getBeginLoc(),
22940b57cec5SDimitry Andric                                   SemaRef.PDiag(diag::err_for_range_invalid)
22950b57cec5SDimitry Andric                                       << BeginRange->getType() << BEFFound),
22960b57cec5SDimitry Andric               SemaRef, OCD_AllCandidates, BeginRange);
22970b57cec5SDimitry Andric           LLVM_FALLTHROUGH;
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric         case Sema::FRS_DiagnosticIssued:
23000b57cec5SDimitry Andric           for (NamedDecl *D : OldFound) {
23010b57cec5SDimitry Andric             SemaRef.Diag(D->getLocation(),
23020b57cec5SDimitry Andric                          diag::note_for_range_member_begin_end_ignored)
23030b57cec5SDimitry Andric                 << BeginRange->getType() << BEFFound;
23040b57cec5SDimitry Andric           }
23050b57cec5SDimitry Andric           return Sema::FRS_DiagnosticIssued;
23060b57cec5SDimitry Andric         }
23070b57cec5SDimitry Andric         llvm_unreachable("unexpected ForRangeStatus");
23080b57cec5SDimitry Andric       };
23090b57cec5SDimitry Andric       if (BeginMemberLookup.empty())
23100b57cec5SDimitry Andric         return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
23110b57cec5SDimitry Andric       return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
23120b57cec5SDimitry Andric     }
23130b57cec5SDimitry Andric   } else {
23140b57cec5SDimitry Andric     // - otherwise, begin-expr and end-expr are begin(__range) and
23150b57cec5SDimitry Andric     //   end(__range), respectively, where begin and end are looked up with
23160b57cec5SDimitry Andric     //   argument-dependent lookup (3.4.2). For the purposes of this name
23170b57cec5SDimitry Andric     //   lookup, namespace std is an associated namespace.
23180b57cec5SDimitry Andric   }
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   if (Sema::ForRangeStatus Result = BuildBegin())
23210b57cec5SDimitry Andric     return Result;
23220b57cec5SDimitry Andric   return BuildEnd();
23230b57cec5SDimitry Andric }
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric /// Speculatively attempt to dereference an invalid range expression.
23260b57cec5SDimitry Andric /// If the attempt fails, this function will return a valid, null StmtResult
23270b57cec5SDimitry Andric /// and emit no diagnostics.
23280b57cec5SDimitry Andric static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
23290b57cec5SDimitry Andric                                                  SourceLocation ForLoc,
23300b57cec5SDimitry Andric                                                  SourceLocation CoawaitLoc,
23310b57cec5SDimitry Andric                                                  Stmt *InitStmt,
23320b57cec5SDimitry Andric                                                  Stmt *LoopVarDecl,
23330b57cec5SDimitry Andric                                                  SourceLocation ColonLoc,
23340b57cec5SDimitry Andric                                                  Expr *Range,
23350b57cec5SDimitry Andric                                                  SourceLocation RangeLoc,
23360b57cec5SDimitry Andric                                                  SourceLocation RParenLoc) {
23370b57cec5SDimitry Andric   // Determine whether we can rebuild the for-range statement with a
23380b57cec5SDimitry Andric   // dereferenced range expression.
23390b57cec5SDimitry Andric   ExprResult AdjustedRange;
23400b57cec5SDimitry Andric   {
23410b57cec5SDimitry Andric     Sema::SFINAETrap Trap(SemaRef);
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric     AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
23440b57cec5SDimitry Andric     if (AdjustedRange.isInvalid())
23450b57cec5SDimitry Andric       return StmtResult();
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric     StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
23480b57cec5SDimitry Andric         S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
23490b57cec5SDimitry Andric         AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
23500b57cec5SDimitry Andric     if (SR.isInvalid())
23510b57cec5SDimitry Andric       return StmtResult();
23520b57cec5SDimitry Andric   }
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric   // The attempt to dereference worked well enough that it could produce a valid
23550b57cec5SDimitry Andric   // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
23560b57cec5SDimitry Andric   // case there are any other (non-fatal) problems with it.
23570b57cec5SDimitry Andric   SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
23580b57cec5SDimitry Andric     << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
23590b57cec5SDimitry Andric   return SemaRef.ActOnCXXForRangeStmt(
23600b57cec5SDimitry Andric       S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
23610b57cec5SDimitry Andric       AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
23620b57cec5SDimitry Andric }
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
23650b57cec5SDimitry Andric StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
23660b57cec5SDimitry Andric                                       SourceLocation CoawaitLoc, Stmt *InitStmt,
23670b57cec5SDimitry Andric                                       SourceLocation ColonLoc, Stmt *RangeDecl,
23680b57cec5SDimitry Andric                                       Stmt *Begin, Stmt *End, Expr *Cond,
23690b57cec5SDimitry Andric                                       Expr *Inc, Stmt *LoopVarDecl,
23700b57cec5SDimitry Andric                                       SourceLocation RParenLoc,
23710b57cec5SDimitry Andric                                       BuildForRangeKind Kind) {
23720b57cec5SDimitry Andric   // FIXME: This should not be used during template instantiation. We should
23730b57cec5SDimitry Andric   // pick up the set of unqualified lookup results for the != and + operators
23740b57cec5SDimitry Andric   // in the initial parse.
23750b57cec5SDimitry Andric   //
23760b57cec5SDimitry Andric   // Testcase (accepts-invalid):
23770b57cec5SDimitry Andric   //   template<typename T> void f() { for (auto x : T()) {} }
23780b57cec5SDimitry Andric   //   namespace N { struct X { X begin(); X end(); int operator*(); }; }
23790b57cec5SDimitry Andric   //   bool operator!=(N::X, N::X); void operator++(N::X);
23800b57cec5SDimitry Andric   //   void g() { f<N::X>(); }
23810b57cec5SDimitry Andric   Scope *S = getCurScope();
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
23840b57cec5SDimitry Andric   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
23850b57cec5SDimitry Andric   QualType RangeVarType = RangeVar->getType();
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
23880b57cec5SDimitry Andric   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   StmtResult BeginDeclStmt = Begin;
23910b57cec5SDimitry Andric   StmtResult EndDeclStmt = End;
23920b57cec5SDimitry Andric   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric   if (RangeVarType->isDependentType()) {
23950b57cec5SDimitry Andric     // The range is implicitly used as a placeholder when it is dependent.
23960b57cec5SDimitry Andric     RangeVar->markUsed(Context);
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric     // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
23990b57cec5SDimitry Andric     // them in properly when we instantiate the loop.
24000b57cec5SDimitry Andric     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
24010b57cec5SDimitry Andric       if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
24020b57cec5SDimitry Andric         for (auto *Binding : DD->bindings())
24030b57cec5SDimitry Andric           Binding->setType(Context.DependentTy);
24040b57cec5SDimitry Andric       LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
24050b57cec5SDimitry Andric     }
24060b57cec5SDimitry Andric   } else if (!BeginDeclStmt.get()) {
24070b57cec5SDimitry Andric     SourceLocation RangeLoc = RangeVar->getLocation();
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
24120b57cec5SDimitry Andric                                                 VK_LValue, ColonLoc);
24130b57cec5SDimitry Andric     if (BeginRangeRef.isInvalid())
24140b57cec5SDimitry Andric       return StmtError();
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
24170b57cec5SDimitry Andric                                               VK_LValue, ColonLoc);
24180b57cec5SDimitry Andric     if (EndRangeRef.isInvalid())
24190b57cec5SDimitry Andric       return StmtError();
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric     QualType AutoType = Context.getAutoDeductType();
24220b57cec5SDimitry Andric     Expr *Range = RangeVar->getInit();
24230b57cec5SDimitry Andric     if (!Range)
24240b57cec5SDimitry Andric       return StmtError();
24250b57cec5SDimitry Andric     QualType RangeType = Range->getType();
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric     if (RequireCompleteType(RangeLoc, RangeType,
24280b57cec5SDimitry Andric                             diag::err_for_range_incomplete_type))
24290b57cec5SDimitry Andric       return StmtError();
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric     // Build auto __begin = begin-expr, __end = end-expr.
24320b57cec5SDimitry Andric     // Divide by 2, since the variables are in the inner scope (loop body).
24330b57cec5SDimitry Andric     const auto DepthStr = std::to_string(S->getDepth() / 2);
24340b57cec5SDimitry Andric     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
24350b57cec5SDimitry Andric                                              std::string("__begin") + DepthStr);
24360b57cec5SDimitry Andric     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
24370b57cec5SDimitry Andric                                            std::string("__end") + DepthStr);
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric     // Build begin-expr and end-expr and attach to __begin and __end variables.
24400b57cec5SDimitry Andric     ExprResult BeginExpr, EndExpr;
24410b57cec5SDimitry Andric     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
24420b57cec5SDimitry Andric       // - if _RangeT is an array type, begin-expr and end-expr are __range and
24430b57cec5SDimitry Andric       //   __range + __bound, respectively, where __bound is the array bound. If
24440b57cec5SDimitry Andric       //   _RangeT is an array of unknown size or an array of incomplete type,
24450b57cec5SDimitry Andric       //   the program is ill-formed;
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric       // begin-expr is __range.
24480b57cec5SDimitry Andric       BeginExpr = BeginRangeRef;
24490b57cec5SDimitry Andric       if (!CoawaitLoc.isInvalid()) {
24500b57cec5SDimitry Andric         BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
24510b57cec5SDimitry Andric         if (BeginExpr.isInvalid())
24520b57cec5SDimitry Andric           return StmtError();
24530b57cec5SDimitry Andric       }
24540b57cec5SDimitry Andric       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
24550b57cec5SDimitry Andric                                 diag::err_for_range_iter_deduction_failure)) {
24560b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
24570b57cec5SDimitry Andric         return StmtError();
24580b57cec5SDimitry Andric       }
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric       // Find the array bound.
24610b57cec5SDimitry Andric       ExprResult BoundExpr;
24620b57cec5SDimitry Andric       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
24630b57cec5SDimitry Andric         BoundExpr = IntegerLiteral::Create(
24640b57cec5SDimitry Andric             Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
24650b57cec5SDimitry Andric       else if (const VariableArrayType *VAT =
24660b57cec5SDimitry Andric                dyn_cast<VariableArrayType>(UnqAT)) {
24670b57cec5SDimitry Andric         // For a variably modified type we can't just use the expression within
24680b57cec5SDimitry Andric         // the array bounds, since we don't want that to be re-evaluated here.
24690b57cec5SDimitry Andric         // Rather, we need to determine what it was when the array was first
24700b57cec5SDimitry Andric         // created - so we resort to using sizeof(vla)/sizeof(element).
24710b57cec5SDimitry Andric         // For e.g.
24720b57cec5SDimitry Andric         //  void f(int b) {
24730b57cec5SDimitry Andric         //    int vla[b];
24740b57cec5SDimitry Andric         //    b = -1;   <-- This should not affect the num of iterations below
24750b57cec5SDimitry Andric         //    for (int &c : vla) { .. }
24760b57cec5SDimitry Andric         //  }
24770b57cec5SDimitry Andric 
24780b57cec5SDimitry Andric         // FIXME: This results in codegen generating IR that recalculates the
24790b57cec5SDimitry Andric         // run-time number of elements (as opposed to just using the IR Value
24800b57cec5SDimitry Andric         // that corresponds to the run-time value of each bound that was
24810b57cec5SDimitry Andric         // generated when the array was created.) If this proves too embarrassing
24820b57cec5SDimitry Andric         // even for unoptimized IR, consider passing a magic-value/cookie to
24830b57cec5SDimitry Andric         // codegen that then knows to simply use that initial llvm::Value (that
24840b57cec5SDimitry Andric         // corresponds to the bound at time of array creation) within
24850b57cec5SDimitry Andric         // getelementptr.  But be prepared to pay the price of increasing a
24860b57cec5SDimitry Andric         // customized form of coupling between the two components - which  could
24870b57cec5SDimitry Andric         // be hard to maintain as the codebase evolves.
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric         ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
24900b57cec5SDimitry Andric             EndVar->getLocation(), UETT_SizeOf,
24910b57cec5SDimitry Andric             /*IsType=*/true,
24920b57cec5SDimitry Andric             CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
24930b57cec5SDimitry Andric                                                  VAT->desugar(), RangeLoc))
24940b57cec5SDimitry Andric                 .getAsOpaquePtr(),
24950b57cec5SDimitry Andric             EndVar->getSourceRange());
24960b57cec5SDimitry Andric         if (SizeOfVLAExprR.isInvalid())
24970b57cec5SDimitry Andric           return StmtError();
24980b57cec5SDimitry Andric 
24990b57cec5SDimitry Andric         ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
25000b57cec5SDimitry Andric             EndVar->getLocation(), UETT_SizeOf,
25010b57cec5SDimitry Andric             /*IsType=*/true,
25020b57cec5SDimitry Andric             CreateParsedType(VAT->desugar(),
25030b57cec5SDimitry Andric                              Context.getTrivialTypeSourceInfo(
25040b57cec5SDimitry Andric                                  VAT->getElementType(), RangeLoc))
25050b57cec5SDimitry Andric                 .getAsOpaquePtr(),
25060b57cec5SDimitry Andric             EndVar->getSourceRange());
25070b57cec5SDimitry Andric         if (SizeOfEachElementExprR.isInvalid())
25080b57cec5SDimitry Andric           return StmtError();
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric         BoundExpr =
25110b57cec5SDimitry Andric             ActOnBinOp(S, EndVar->getLocation(), tok::slash,
25120b57cec5SDimitry Andric                        SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
25130b57cec5SDimitry Andric         if (BoundExpr.isInvalid())
25140b57cec5SDimitry Andric           return StmtError();
25150b57cec5SDimitry Andric 
25160b57cec5SDimitry Andric       } else {
25170b57cec5SDimitry Andric         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
25180b57cec5SDimitry Andric         // UnqAT is not incomplete and Range is not type-dependent.
25190b57cec5SDimitry Andric         llvm_unreachable("Unexpected array type in for-range");
25200b57cec5SDimitry Andric       }
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric       // end-expr is __range + __bound.
25230b57cec5SDimitry Andric       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
25240b57cec5SDimitry Andric                            BoundExpr.get());
25250b57cec5SDimitry Andric       if (EndExpr.isInvalid())
25260b57cec5SDimitry Andric         return StmtError();
25270b57cec5SDimitry Andric       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
25280b57cec5SDimitry Andric                                 diag::err_for_range_iter_deduction_failure)) {
25290b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
25300b57cec5SDimitry Andric         return StmtError();
25310b57cec5SDimitry Andric       }
25320b57cec5SDimitry Andric     } else {
25330b57cec5SDimitry Andric       OverloadCandidateSet CandidateSet(RangeLoc,
25340b57cec5SDimitry Andric                                         OverloadCandidateSet::CSK_Normal);
25350b57cec5SDimitry Andric       BeginEndFunction BEFFailure;
25360b57cec5SDimitry Andric       ForRangeStatus RangeStatus = BuildNonArrayForRange(
25370b57cec5SDimitry Andric           *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
25380b57cec5SDimitry Andric           EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
25390b57cec5SDimitry Andric           &BEFFailure);
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric       if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
25420b57cec5SDimitry Andric           BEFFailure == BEF_begin) {
25430b57cec5SDimitry Andric         // If the range is being built from an array parameter, emit a
25440b57cec5SDimitry Andric         // a diagnostic that it is being treated as a pointer.
25450b57cec5SDimitry Andric         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
25460b57cec5SDimitry Andric           if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
25470b57cec5SDimitry Andric             QualType ArrayTy = PVD->getOriginalType();
25480b57cec5SDimitry Andric             QualType PointerTy = PVD->getType();
25490b57cec5SDimitry Andric             if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
25500b57cec5SDimitry Andric               Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
25510b57cec5SDimitry Andric                   << RangeLoc << PVD << ArrayTy << PointerTy;
25520b57cec5SDimitry Andric               Diag(PVD->getLocation(), diag::note_declared_at);
25530b57cec5SDimitry Andric               return StmtError();
25540b57cec5SDimitry Andric             }
25550b57cec5SDimitry Andric           }
25560b57cec5SDimitry Andric         }
25570b57cec5SDimitry Andric 
25580b57cec5SDimitry Andric         // If building the range failed, try dereferencing the range expression
25590b57cec5SDimitry Andric         // unless a diagnostic was issued or the end function is problematic.
25600b57cec5SDimitry Andric         StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
25610b57cec5SDimitry Andric                                                        CoawaitLoc, InitStmt,
25620b57cec5SDimitry Andric                                                        LoopVarDecl, ColonLoc,
25630b57cec5SDimitry Andric                                                        Range, RangeLoc,
25640b57cec5SDimitry Andric                                                        RParenLoc);
25650b57cec5SDimitry Andric         if (SR.isInvalid() || SR.isUsable())
25660b57cec5SDimitry Andric           return SR;
25670b57cec5SDimitry Andric       }
25680b57cec5SDimitry Andric 
25690b57cec5SDimitry Andric       // Otherwise, emit diagnostics if we haven't already.
25700b57cec5SDimitry Andric       if (RangeStatus == FRS_NoViableFunction) {
25710b57cec5SDimitry Andric         Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
25720b57cec5SDimitry Andric         CandidateSet.NoteCandidates(
25730b57cec5SDimitry Andric             PartialDiagnosticAt(Range->getBeginLoc(),
25740b57cec5SDimitry Andric                                 PDiag(diag::err_for_range_invalid)
25750b57cec5SDimitry Andric                                     << RangeLoc << Range->getType()
25760b57cec5SDimitry Andric                                     << BEFFailure),
25770b57cec5SDimitry Andric             *this, OCD_AllCandidates, Range);
25780b57cec5SDimitry Andric       }
25790b57cec5SDimitry Andric       // Return an error if no fix was discovered.
25800b57cec5SDimitry Andric       if (RangeStatus != FRS_Success)
25810b57cec5SDimitry Andric         return StmtError();
25820b57cec5SDimitry Andric     }
25830b57cec5SDimitry Andric 
25840b57cec5SDimitry Andric     assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
25850b57cec5SDimitry Andric            "invalid range expression in for loop");
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric     // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
25880b57cec5SDimitry Andric     // C++1z removes this restriction.
25890b57cec5SDimitry Andric     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
25900b57cec5SDimitry Andric     if (!Context.hasSameType(BeginType, EndType)) {
25910b57cec5SDimitry Andric       Diag(RangeLoc, getLangOpts().CPlusPlus17
25920b57cec5SDimitry Andric                          ? diag::warn_for_range_begin_end_types_differ
25930b57cec5SDimitry Andric                          : diag::ext_for_range_begin_end_types_differ)
25940b57cec5SDimitry Andric           << BeginType << EndType;
25950b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
25960b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
25970b57cec5SDimitry Andric     }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric     BeginDeclStmt =
26000b57cec5SDimitry Andric         ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
26010b57cec5SDimitry Andric     EndDeclStmt =
26020b57cec5SDimitry Andric         ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
26030b57cec5SDimitry Andric 
26040b57cec5SDimitry Andric     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
26050b57cec5SDimitry Andric     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
26060b57cec5SDimitry Andric                                            VK_LValue, ColonLoc);
26070b57cec5SDimitry Andric     if (BeginRef.isInvalid())
26080b57cec5SDimitry Andric       return StmtError();
26090b57cec5SDimitry Andric 
26100b57cec5SDimitry Andric     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
26110b57cec5SDimitry Andric                                          VK_LValue, ColonLoc);
26120b57cec5SDimitry Andric     if (EndRef.isInvalid())
26130b57cec5SDimitry Andric       return StmtError();
26140b57cec5SDimitry Andric 
26150b57cec5SDimitry Andric     // Build and check __begin != __end expression.
26160b57cec5SDimitry Andric     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
26170b57cec5SDimitry Andric                            BeginRef.get(), EndRef.get());
26180b57cec5SDimitry Andric     if (!NotEqExpr.isInvalid())
26190b57cec5SDimitry Andric       NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
26200b57cec5SDimitry Andric     if (!NotEqExpr.isInvalid())
26210b57cec5SDimitry Andric       NotEqExpr =
26220b57cec5SDimitry Andric           ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
26230b57cec5SDimitry Andric     if (NotEqExpr.isInvalid()) {
26240b57cec5SDimitry Andric       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
26250b57cec5SDimitry Andric         << RangeLoc << 0 << BeginRangeRef.get()->getType();
26260b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
26270b57cec5SDimitry Andric       if (!Context.hasSameType(BeginType, EndType))
26280b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
26290b57cec5SDimitry Andric       return StmtError();
26300b57cec5SDimitry Andric     }
26310b57cec5SDimitry Andric 
26320b57cec5SDimitry Andric     // Build and check ++__begin expression.
26330b57cec5SDimitry Andric     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
26340b57cec5SDimitry Andric                                 VK_LValue, ColonLoc);
26350b57cec5SDimitry Andric     if (BeginRef.isInvalid())
26360b57cec5SDimitry Andric       return StmtError();
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
26390b57cec5SDimitry Andric     if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
26400b57cec5SDimitry Andric       // FIXME: getCurScope() should not be used during template instantiation.
26410b57cec5SDimitry Andric       // We should pick up the set of unqualified lookup results for operator
26420b57cec5SDimitry Andric       // co_await during the initial parse.
26430b57cec5SDimitry Andric       IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
26440b57cec5SDimitry Andric     if (!IncrExpr.isInvalid())
26450b57cec5SDimitry Andric       IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
26460b57cec5SDimitry Andric     if (IncrExpr.isInvalid()) {
26470b57cec5SDimitry Andric       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
26480b57cec5SDimitry Andric         << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
26490b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
26500b57cec5SDimitry Andric       return StmtError();
26510b57cec5SDimitry Andric     }
26520b57cec5SDimitry Andric 
26530b57cec5SDimitry Andric     // Build and check *__begin  expression.
26540b57cec5SDimitry Andric     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
26550b57cec5SDimitry Andric                                 VK_LValue, ColonLoc);
26560b57cec5SDimitry Andric     if (BeginRef.isInvalid())
26570b57cec5SDimitry Andric       return StmtError();
26580b57cec5SDimitry Andric 
26590b57cec5SDimitry Andric     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
26600b57cec5SDimitry Andric     if (DerefExpr.isInvalid()) {
26610b57cec5SDimitry Andric       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
26620b57cec5SDimitry Andric         << RangeLoc << 1 << BeginRangeRef.get()->getType();
26630b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
26640b57cec5SDimitry Andric       return StmtError();
26650b57cec5SDimitry Andric     }
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric     // Attach  *__begin  as initializer for VD. Don't touch it if we're just
26680b57cec5SDimitry Andric     // trying to determine whether this would be a valid range.
26690b57cec5SDimitry Andric     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
26700b57cec5SDimitry Andric       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2671*5ffd83dbSDimitry Andric       if (LoopVar->isInvalidDecl() ||
2672*5ffd83dbSDimitry Andric           (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
26730b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
26740b57cec5SDimitry Andric     }
26750b57cec5SDimitry Andric   }
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric   // Don't bother to actually allocate the result if we're just trying to
26780b57cec5SDimitry Andric   // determine whether it would be valid.
26790b57cec5SDimitry Andric   if (Kind == BFRK_Check)
26800b57cec5SDimitry Andric     return StmtResult();
26810b57cec5SDimitry Andric 
2682a7dea167SDimitry Andric   // In OpenMP loop region loop control variable must be private. Perform
2683a7dea167SDimitry Andric   // analysis of first part (if any).
2684a7dea167SDimitry Andric   if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
2685a7dea167SDimitry Andric     ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
2686a7dea167SDimitry Andric 
26870b57cec5SDimitry Andric   return new (Context) CXXForRangeStmt(
26880b57cec5SDimitry Andric       InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
26890b57cec5SDimitry Andric       cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
26900b57cec5SDimitry Andric       IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
26910b57cec5SDimitry Andric       ColonLoc, RParenLoc);
26920b57cec5SDimitry Andric }
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
26950b57cec5SDimitry Andric /// statement.
26960b57cec5SDimitry Andric StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
26970b57cec5SDimitry Andric   if (!S || !B)
26980b57cec5SDimitry Andric     return StmtError();
26990b57cec5SDimitry Andric   ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
27000b57cec5SDimitry Andric 
27010b57cec5SDimitry Andric   ForStmt->setBody(B);
27020b57cec5SDimitry Andric   return S;
27030b57cec5SDimitry Andric }
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric // Warn when the loop variable is a const reference that creates a copy.
27060b57cec5SDimitry Andric // Suggest using the non-reference type for copies.  If a copy can be prevented
27070b57cec5SDimitry Andric // suggest the const reference type that would do so.
27080b57cec5SDimitry Andric // For instance, given "for (const &Foo : Range)", suggest
27090b57cec5SDimitry Andric // "for (const Foo : Range)" to denote a copy is made for the loop.  If
27100b57cec5SDimitry Andric // possible, also suggest "for (const &Bar : Range)" if this type prevents
27110b57cec5SDimitry Andric // the copy altogether.
27120b57cec5SDimitry Andric static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
27130b57cec5SDimitry Andric                                                     const VarDecl *VD,
27140b57cec5SDimitry Andric                                                     QualType RangeInitType) {
27150b57cec5SDimitry Andric   const Expr *InitExpr = VD->getInit();
27160b57cec5SDimitry Andric   if (!InitExpr)
27170b57cec5SDimitry Andric     return;
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   QualType VariableType = VD->getType();
27200b57cec5SDimitry Andric 
27210b57cec5SDimitry Andric   if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
27220b57cec5SDimitry Andric     if (!Cleanups->cleanupsHaveSideEffects())
27230b57cec5SDimitry Andric       InitExpr = Cleanups->getSubExpr();
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric   const MaterializeTemporaryExpr *MTE =
27260b57cec5SDimitry Andric       dyn_cast<MaterializeTemporaryExpr>(InitExpr);
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   // No copy made.
27290b57cec5SDimitry Andric   if (!MTE)
27300b57cec5SDimitry Andric     return;
27310b57cec5SDimitry Andric 
2732480093f4SDimitry Andric   const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric   // Searching for either UnaryOperator for dereference of a pointer or
27350b57cec5SDimitry Andric   // CXXOperatorCallExpr for handling iterators.
27360b57cec5SDimitry Andric   while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
27370b57cec5SDimitry Andric     if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
27380b57cec5SDimitry Andric       E = CCE->getArg(0);
27390b57cec5SDimitry Andric     } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
27400b57cec5SDimitry Andric       const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
27410b57cec5SDimitry Andric       E = ME->getBase();
27420b57cec5SDimitry Andric     } else {
27430b57cec5SDimitry Andric       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2744480093f4SDimitry Andric       E = MTE->getSubExpr();
27450b57cec5SDimitry Andric     }
27460b57cec5SDimitry Andric     E = E->IgnoreImpCasts();
27470b57cec5SDimitry Andric   }
27480b57cec5SDimitry Andric 
2749*5ffd83dbSDimitry Andric   QualType ReferenceReturnType;
27500b57cec5SDimitry Andric   if (isa<UnaryOperator>(E)) {
2751*5ffd83dbSDimitry Andric     ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
27520b57cec5SDimitry Andric   } else {
27530b57cec5SDimitry Andric     const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
27540b57cec5SDimitry Andric     const FunctionDecl *FD = Call->getDirectCallee();
27550b57cec5SDimitry Andric     QualType ReturnType = FD->getReturnType();
2756*5ffd83dbSDimitry Andric     if (ReturnType->isReferenceType())
2757*5ffd83dbSDimitry Andric       ReferenceReturnType = ReturnType;
27580b57cec5SDimitry Andric   }
27590b57cec5SDimitry Andric 
2760*5ffd83dbSDimitry Andric   if (!ReferenceReturnType.isNull()) {
27610b57cec5SDimitry Andric     // Loop variable creates a temporary.  Suggest either to go with
27620b57cec5SDimitry Andric     // non-reference loop variable to indicate a copy is made, or
2763*5ffd83dbSDimitry Andric     // the correct type to bind a const reference.
2764*5ffd83dbSDimitry Andric     SemaRef.Diag(VD->getLocation(),
2765*5ffd83dbSDimitry Andric                  diag::warn_for_range_const_ref_binds_temp_built_from_ref)
2766*5ffd83dbSDimitry Andric         << VD << VariableType << ReferenceReturnType;
27670b57cec5SDimitry Andric     QualType NonReferenceType = VariableType.getNonReferenceType();
27680b57cec5SDimitry Andric     NonReferenceType.removeLocalConst();
27690b57cec5SDimitry Andric     QualType NewReferenceType =
27700b57cec5SDimitry Andric         SemaRef.Context.getLValueReferenceType(E->getType().withConst());
27710b57cec5SDimitry Andric     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2772480093f4SDimitry Andric         << NonReferenceType << NewReferenceType << VD->getSourceRange()
2773480093f4SDimitry Andric         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
2774480093f4SDimitry Andric   } else if (!VariableType->isRValueReferenceType()) {
27750b57cec5SDimitry Andric     // The range always returns a copy, so a temporary is always created.
27760b57cec5SDimitry Andric     // Suggest removing the reference from the loop variable.
2777480093f4SDimitry Andric     // If the type is a rvalue reference do not warn since that changes the
2778480093f4SDimitry Andric     // semantic of the code.
2779*5ffd83dbSDimitry Andric     SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
27800b57cec5SDimitry Andric         << VD << RangeInitType;
27810b57cec5SDimitry Andric     QualType NonReferenceType = VariableType.getNonReferenceType();
27820b57cec5SDimitry Andric     NonReferenceType.removeLocalConst();
27830b57cec5SDimitry Andric     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2784480093f4SDimitry Andric         << NonReferenceType << VD->getSourceRange()
2785480093f4SDimitry Andric         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
27860b57cec5SDimitry Andric   }
27870b57cec5SDimitry Andric }
27880b57cec5SDimitry Andric 
2789480093f4SDimitry Andric /// Determines whether the @p VariableType's declaration is a record with the
2790480093f4SDimitry Andric /// clang::trivial_abi attribute.
2791480093f4SDimitry Andric static bool hasTrivialABIAttr(QualType VariableType) {
2792480093f4SDimitry Andric   if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
2793480093f4SDimitry Andric     return RD->hasAttr<TrivialABIAttr>();
2794480093f4SDimitry Andric 
2795480093f4SDimitry Andric   return false;
2796480093f4SDimitry Andric }
2797480093f4SDimitry Andric 
27980b57cec5SDimitry Andric // Warns when the loop variable can be changed to a reference type to
27990b57cec5SDimitry Andric // prevent a copy.  For instance, if given "for (const Foo x : Range)" suggest
28000b57cec5SDimitry Andric // "for (const Foo &x : Range)" if this form does not make a copy.
28010b57cec5SDimitry Andric static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
28020b57cec5SDimitry Andric                                                 const VarDecl *VD) {
28030b57cec5SDimitry Andric   const Expr *InitExpr = VD->getInit();
28040b57cec5SDimitry Andric   if (!InitExpr)
28050b57cec5SDimitry Andric     return;
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric   QualType VariableType = VD->getType();
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
28100b57cec5SDimitry Andric     if (!CE->getConstructor()->isCopyConstructor())
28110b57cec5SDimitry Andric       return;
28120b57cec5SDimitry Andric   } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
28130b57cec5SDimitry Andric     if (CE->getCastKind() != CK_LValueToRValue)
28140b57cec5SDimitry Andric       return;
28150b57cec5SDimitry Andric   } else {
28160b57cec5SDimitry Andric     return;
28170b57cec5SDimitry Andric   }
28180b57cec5SDimitry Andric 
2819480093f4SDimitry Andric   // Small trivially copyable types are cheap to copy. Do not emit the
2820480093f4SDimitry Andric   // diagnostic for these instances. 64 bytes is a common size of a cache line.
2821480093f4SDimitry Andric   // (The function `getTypeSize` returns the size in bits.)
2822480093f4SDimitry Andric   ASTContext &Ctx = SemaRef.Context;
2823480093f4SDimitry Andric   if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
2824480093f4SDimitry Andric       (VariableType.isTriviallyCopyableType(Ctx) ||
2825480093f4SDimitry Andric        hasTrivialABIAttr(VariableType)))
28260b57cec5SDimitry Andric     return;
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   // Suggest changing from a const variable to a const reference variable
28290b57cec5SDimitry Andric   // if doing so will prevent a copy.
28300b57cec5SDimitry Andric   SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2831*5ffd83dbSDimitry Andric       << VD << VariableType;
28320b57cec5SDimitry Andric   SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
28330b57cec5SDimitry Andric       << SemaRef.Context.getLValueReferenceType(VariableType)
2834480093f4SDimitry Andric       << VD->getSourceRange()
2835480093f4SDimitry Andric       << FixItHint::CreateInsertion(VD->getLocation(), "&");
28360b57cec5SDimitry Andric }
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
28390b57cec5SDimitry Andric /// 1) for (const foo &x : foos) where foos only returns a copy.  Suggest
28400b57cec5SDimitry Andric ///    using "const foo x" to show that a copy is made
28410b57cec5SDimitry Andric /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
28420b57cec5SDimitry Andric ///    Suggest either "const bar x" to keep the copying or "const foo& x" to
28430b57cec5SDimitry Andric ///    prevent the copy.
28440b57cec5SDimitry Andric /// 3) for (const foo x : foos) where x is constructed from a reference foo.
28450b57cec5SDimitry Andric ///    Suggest "const foo &x" to prevent the copy.
28460b57cec5SDimitry Andric static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
28470b57cec5SDimitry Andric                                            const CXXForRangeStmt *ForStmt) {
284855e4f9d5SDimitry Andric   if (SemaRef.inTemplateInstantiation())
284955e4f9d5SDimitry Andric     return;
285055e4f9d5SDimitry Andric 
2851*5ffd83dbSDimitry Andric   if (SemaRef.Diags.isIgnored(
2852*5ffd83dbSDimitry Andric           diag::warn_for_range_const_ref_binds_temp_built_from_ref,
28530b57cec5SDimitry Andric           ForStmt->getBeginLoc()) &&
2854*5ffd83dbSDimitry Andric       SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
28550b57cec5SDimitry Andric                               ForStmt->getBeginLoc()) &&
28560b57cec5SDimitry Andric       SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
28570b57cec5SDimitry Andric                               ForStmt->getBeginLoc())) {
28580b57cec5SDimitry Andric     return;
28590b57cec5SDimitry Andric   }
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   const VarDecl *VD = ForStmt->getLoopVariable();
28620b57cec5SDimitry Andric   if (!VD)
28630b57cec5SDimitry Andric     return;
28640b57cec5SDimitry Andric 
28650b57cec5SDimitry Andric   QualType VariableType = VD->getType();
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric   if (VariableType->isIncompleteType())
28680b57cec5SDimitry Andric     return;
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric   const Expr *InitExpr = VD->getInit();
28710b57cec5SDimitry Andric   if (!InitExpr)
28720b57cec5SDimitry Andric     return;
28730b57cec5SDimitry Andric 
287455e4f9d5SDimitry Andric   if (InitExpr->getExprLoc().isMacroID())
287555e4f9d5SDimitry Andric     return;
287655e4f9d5SDimitry Andric 
28770b57cec5SDimitry Andric   if (VariableType->isReferenceType()) {
28780b57cec5SDimitry Andric     DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
28790b57cec5SDimitry Andric                                             ForStmt->getRangeInit()->getType());
28800b57cec5SDimitry Andric   } else if (VariableType.isConstQualified()) {
28810b57cec5SDimitry Andric     DiagnoseForRangeConstVariableCopies(SemaRef, VD);
28820b57cec5SDimitry Andric   }
28830b57cec5SDimitry Andric }
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
28860b57cec5SDimitry Andric /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
28870b57cec5SDimitry Andric /// body cannot be performed until after the type of the range variable is
28880b57cec5SDimitry Andric /// determined.
28890b57cec5SDimitry Andric StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
28900b57cec5SDimitry Andric   if (!S || !B)
28910b57cec5SDimitry Andric     return StmtError();
28920b57cec5SDimitry Andric 
28930b57cec5SDimitry Andric   if (isa<ObjCForCollectionStmt>(S))
28940b57cec5SDimitry Andric     return FinishObjCForCollectionStmt(S, B);
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
28970b57cec5SDimitry Andric   ForStmt->setBody(B);
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
29000b57cec5SDimitry Andric                         diag::warn_empty_range_based_for_body);
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric   DiagnoseForRangeVariableCopies(*this, ForStmt);
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric   return S;
29050b57cec5SDimitry Andric }
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
29080b57cec5SDimitry Andric                                SourceLocation LabelLoc,
29090b57cec5SDimitry Andric                                LabelDecl *TheDecl) {
29100b57cec5SDimitry Andric   setFunctionHasBranchIntoScope();
29110b57cec5SDimitry Andric   TheDecl->markUsed(Context);
29120b57cec5SDimitry Andric   return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
29130b57cec5SDimitry Andric }
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric StmtResult
29160b57cec5SDimitry Andric Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
29170b57cec5SDimitry Andric                             Expr *E) {
29180b57cec5SDimitry Andric   // Convert operand to void*
29190b57cec5SDimitry Andric   if (!E->isTypeDependent()) {
29200b57cec5SDimitry Andric     QualType ETy = E->getType();
29210b57cec5SDimitry Andric     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
29220b57cec5SDimitry Andric     ExprResult ExprRes = E;
29230b57cec5SDimitry Andric     AssignConvertType ConvTy =
29240b57cec5SDimitry Andric       CheckSingleAssignmentConstraints(DestTy, ExprRes);
29250b57cec5SDimitry Andric     if (ExprRes.isInvalid())
29260b57cec5SDimitry Andric       return StmtError();
29270b57cec5SDimitry Andric     E = ExprRes.get();
29280b57cec5SDimitry Andric     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
29290b57cec5SDimitry Andric       return StmtError();
29300b57cec5SDimitry Andric   }
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric   ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
29330b57cec5SDimitry Andric   if (ExprRes.isInvalid())
29340b57cec5SDimitry Andric     return StmtError();
29350b57cec5SDimitry Andric   E = ExprRes.get();
29360b57cec5SDimitry Andric 
29370b57cec5SDimitry Andric   setFunctionHasIndirectGoto();
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric   return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
29400b57cec5SDimitry Andric }
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
29430b57cec5SDimitry Andric                                      const Scope &DestScope) {
29440b57cec5SDimitry Andric   if (!S.CurrentSEHFinally.empty() &&
29450b57cec5SDimitry Andric       DestScope.Contains(*S.CurrentSEHFinally.back())) {
29460b57cec5SDimitry Andric     S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
29470b57cec5SDimitry Andric   }
29480b57cec5SDimitry Andric }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric StmtResult
29510b57cec5SDimitry Andric Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
29520b57cec5SDimitry Andric   Scope *S = CurScope->getContinueParent();
29530b57cec5SDimitry Andric   if (!S) {
29540b57cec5SDimitry Andric     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
29550b57cec5SDimitry Andric     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
29560b57cec5SDimitry Andric   }
29570b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric   return new (Context) ContinueStmt(ContinueLoc);
29600b57cec5SDimitry Andric }
29610b57cec5SDimitry Andric 
29620b57cec5SDimitry Andric StmtResult
29630b57cec5SDimitry Andric Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
29640b57cec5SDimitry Andric   Scope *S = CurScope->getBreakParent();
29650b57cec5SDimitry Andric   if (!S) {
29660b57cec5SDimitry Andric     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
29670b57cec5SDimitry Andric     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
29680b57cec5SDimitry Andric   }
29690b57cec5SDimitry Andric   if (S->isOpenMPLoopScope())
29700b57cec5SDimitry Andric     return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
29710b57cec5SDimitry Andric                      << "break");
29720b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   return new (Context) BreakStmt(BreakLoc);
29750b57cec5SDimitry Andric }
29760b57cec5SDimitry Andric 
29770b57cec5SDimitry Andric /// Determine whether the given expression is a candidate for
29780b57cec5SDimitry Andric /// copy elision in either a return statement or a throw expression.
29790b57cec5SDimitry Andric ///
29800b57cec5SDimitry Andric /// \param ReturnType If we're determining the copy elision candidate for
29810b57cec5SDimitry Andric /// a return statement, this is the return type of the function. If we're
29820b57cec5SDimitry Andric /// determining the copy elision candidate for a throw expression, this will
29830b57cec5SDimitry Andric /// be a NULL type.
29840b57cec5SDimitry Andric ///
29850b57cec5SDimitry Andric /// \param E The expression being returned from the function or block, or
29860b57cec5SDimitry Andric /// being thrown.
29870b57cec5SDimitry Andric ///
29880b57cec5SDimitry Andric /// \param CESK Whether we allow function parameters or
29890b57cec5SDimitry Andric /// id-expressions that could be moved out of the function to be considered NRVO
29900b57cec5SDimitry Andric /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
29910b57cec5SDimitry Andric /// determine whether we should try to move as part of a return or throw (which
29920b57cec5SDimitry Andric /// does allow function parameters).
29930b57cec5SDimitry Andric ///
29940b57cec5SDimitry Andric /// \returns The NRVO candidate variable, if the return statement may use the
29950b57cec5SDimitry Andric /// NRVO, or NULL if there is no such candidate.
29960b57cec5SDimitry Andric VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
29970b57cec5SDimitry Andric                                        CopyElisionSemanticsKind CESK) {
29980b57cec5SDimitry Andric   // - in a return statement in a function [where] ...
29990b57cec5SDimitry Andric   // ... the expression is the name of a non-volatile automatic object ...
30000b57cec5SDimitry Andric   DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
30010b57cec5SDimitry Andric   if (!DR || DR->refersToEnclosingVariableOrCapture())
30020b57cec5SDimitry Andric     return nullptr;
30030b57cec5SDimitry Andric   VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
30040b57cec5SDimitry Andric   if (!VD)
30050b57cec5SDimitry Andric     return nullptr;
30060b57cec5SDimitry Andric 
30070b57cec5SDimitry Andric   if (isCopyElisionCandidate(ReturnType, VD, CESK))
30080b57cec5SDimitry Andric     return VD;
30090b57cec5SDimitry Andric   return nullptr;
30100b57cec5SDimitry Andric }
30110b57cec5SDimitry Andric 
30120b57cec5SDimitry Andric bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
30130b57cec5SDimitry Andric                                   CopyElisionSemanticsKind CESK) {
30140b57cec5SDimitry Andric   QualType VDType = VD->getType();
30150b57cec5SDimitry Andric   // - in a return statement in a function with ...
30160b57cec5SDimitry Andric   // ... a class return type ...
30170b57cec5SDimitry Andric   if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
30180b57cec5SDimitry Andric     if (!ReturnType->isRecordType())
30190b57cec5SDimitry Andric       return false;
30200b57cec5SDimitry Andric     // ... the same cv-unqualified type as the function return type ...
30210b57cec5SDimitry Andric     // When considering moving this expression out, allow dissimilar types.
30220b57cec5SDimitry Andric     if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
30230b57cec5SDimitry Andric         !Context.hasSameUnqualifiedType(ReturnType, VDType))
30240b57cec5SDimitry Andric       return false;
30250b57cec5SDimitry Andric   }
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric   // ...object (other than a function or catch-clause parameter)...
30280b57cec5SDimitry Andric   if (VD->getKind() != Decl::Var &&
30290b57cec5SDimitry Andric       !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
30300b57cec5SDimitry Andric     return false;
30310b57cec5SDimitry Andric   if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
30320b57cec5SDimitry Andric     return false;
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric   // ...automatic...
30350b57cec5SDimitry Andric   if (!VD->hasLocalStorage()) return false;
30360b57cec5SDimitry Andric 
30370b57cec5SDimitry Andric   // Return false if VD is a __block variable. We don't want to implicitly move
30380b57cec5SDimitry Andric   // out of a __block variable during a return because we cannot assume the
30390b57cec5SDimitry Andric   // variable will no longer be used.
30400b57cec5SDimitry Andric   if (VD->hasAttr<BlocksAttr>()) return false;
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric   if (CESK & CES_AllowDifferentTypes)
30430b57cec5SDimitry Andric     return true;
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   // ...non-volatile...
30460b57cec5SDimitry Andric   if (VD->getType().isVolatileQualified()) return false;
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric   // Variables with higher required alignment than their type's ABI
30490b57cec5SDimitry Andric   // alignment cannot use NRVO.
30500b57cec5SDimitry Andric   if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
30510b57cec5SDimitry Andric       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
30520b57cec5SDimitry Andric     return false;
30530b57cec5SDimitry Andric 
30540b57cec5SDimitry Andric   return true;
30550b57cec5SDimitry Andric }
30560b57cec5SDimitry Andric 
30570b57cec5SDimitry Andric /// Try to perform the initialization of a potentially-movable value,
30580b57cec5SDimitry Andric /// which is the operand to a return or throw statement.
30590b57cec5SDimitry Andric ///
30600b57cec5SDimitry Andric /// This routine implements C++14 [class.copy]p32, which attempts to treat
30610b57cec5SDimitry Andric /// returned lvalues as rvalues in certain cases (to prefer move construction),
30620b57cec5SDimitry Andric /// then falls back to treating them as lvalues if that failed.
30630b57cec5SDimitry Andric ///
30640b57cec5SDimitry Andric /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
30650b57cec5SDimitry Andric /// resolutions that find non-constructors, such as derived-to-base conversions
30660b57cec5SDimitry Andric /// or `operator T()&&` member functions. If false, do consider such
30670b57cec5SDimitry Andric /// conversion sequences.
30680b57cec5SDimitry Andric ///
30690b57cec5SDimitry Andric /// \param Res We will fill this in if move-initialization was possible.
30700b57cec5SDimitry Andric /// If move-initialization is not possible, such that we must fall back to
30710b57cec5SDimitry Andric /// treating the operand as an lvalue, we will leave Res in its original
30720b57cec5SDimitry Andric /// invalid state.
30730b57cec5SDimitry Andric static void TryMoveInitialization(Sema& S,
30740b57cec5SDimitry Andric                                   const InitializedEntity &Entity,
30750b57cec5SDimitry Andric                                   const VarDecl *NRVOCandidate,
30760b57cec5SDimitry Andric                                   QualType ResultType,
30770b57cec5SDimitry Andric                                   Expr *&Value,
30780b57cec5SDimitry Andric                                   bool ConvertingConstructorsOnly,
30790b57cec5SDimitry Andric                                   ExprResult &Res) {
30800b57cec5SDimitry Andric   ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
30810b57cec5SDimitry Andric                             CK_NoOp, Value, VK_XValue);
30820b57cec5SDimitry Andric 
30830b57cec5SDimitry Andric   Expr *InitExpr = &AsRvalue;
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric   InitializationKind Kind = InitializationKind::CreateCopy(
30860b57cec5SDimitry Andric       Value->getBeginLoc(), Value->getBeginLoc());
30870b57cec5SDimitry Andric 
30880b57cec5SDimitry Andric   InitializationSequence Seq(S, Entity, Kind, InitExpr);
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric   if (!Seq)
30910b57cec5SDimitry Andric     return;
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric   for (const InitializationSequence::Step &Step : Seq.steps()) {
30940b57cec5SDimitry Andric     if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
30950b57cec5SDimitry Andric         Step.Kind != InitializationSequence::SK_UserConversion)
30960b57cec5SDimitry Andric       continue;
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric     FunctionDecl *FD = Step.Function.Function;
30990b57cec5SDimitry Andric     if (ConvertingConstructorsOnly) {
31000b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(FD)) {
31010b57cec5SDimitry Andric         // C++14 [class.copy]p32:
31020b57cec5SDimitry Andric         // [...] If the first overload resolution fails or was not performed,
31030b57cec5SDimitry Andric         // or if the type of the first parameter of the selected constructor
31040b57cec5SDimitry Andric         // is not an rvalue reference to the object's type (possibly
31050b57cec5SDimitry Andric         // cv-qualified), overload resolution is performed again, considering
31060b57cec5SDimitry Andric         // the object as an lvalue.
31070b57cec5SDimitry Andric         const RValueReferenceType *RRefType =
31080b57cec5SDimitry Andric             FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
31090b57cec5SDimitry Andric         if (!RRefType)
31100b57cec5SDimitry Andric           break;
31110b57cec5SDimitry Andric         if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
31120b57cec5SDimitry Andric                                               NRVOCandidate->getType()))
31130b57cec5SDimitry Andric           break;
31140b57cec5SDimitry Andric       } else {
31150b57cec5SDimitry Andric         continue;
31160b57cec5SDimitry Andric       }
31170b57cec5SDimitry Andric     } else {
31180b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(FD)) {
31190b57cec5SDimitry Andric         // Check that overload resolution selected a constructor taking an
31200b57cec5SDimitry Andric         // rvalue reference. If it selected an lvalue reference, then we
31210b57cec5SDimitry Andric         // didn't need to cast this thing to an rvalue in the first place.
31220b57cec5SDimitry Andric         if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
31230b57cec5SDimitry Andric           break;
31240b57cec5SDimitry Andric       } else if (isa<CXXMethodDecl>(FD)) {
31250b57cec5SDimitry Andric         // Check that overload resolution selected a conversion operator
31260b57cec5SDimitry Andric         // taking an rvalue reference.
31270b57cec5SDimitry Andric         if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
31280b57cec5SDimitry Andric           break;
31290b57cec5SDimitry Andric       } else {
31300b57cec5SDimitry Andric         continue;
31310b57cec5SDimitry Andric       }
31320b57cec5SDimitry Andric     }
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric     // Promote "AsRvalue" to the heap, since we now need this
31350b57cec5SDimitry Andric     // expression node to persist.
31360b57cec5SDimitry Andric     Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
31370b57cec5SDimitry Andric                                      Value, nullptr, VK_XValue);
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric     // Complete type-checking the initialization of the return type
31400b57cec5SDimitry Andric     // using the constructor we found.
31410b57cec5SDimitry Andric     Res = Seq.Perform(S, Entity, Kind, Value);
31420b57cec5SDimitry Andric   }
31430b57cec5SDimitry Andric }
31440b57cec5SDimitry Andric 
31450b57cec5SDimitry Andric /// Perform the initialization of a potentially-movable value, which
31460b57cec5SDimitry Andric /// is the result of return value.
31470b57cec5SDimitry Andric ///
31480b57cec5SDimitry Andric /// This routine implements C++14 [class.copy]p32, which attempts to treat
31490b57cec5SDimitry Andric /// returned lvalues as rvalues in certain cases (to prefer move construction),
31500b57cec5SDimitry Andric /// then falls back to treating them as lvalues if that failed.
31510b57cec5SDimitry Andric ExprResult
31520b57cec5SDimitry Andric Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
31530b57cec5SDimitry Andric                                       const VarDecl *NRVOCandidate,
31540b57cec5SDimitry Andric                                       QualType ResultType,
31550b57cec5SDimitry Andric                                       Expr *Value,
31560b57cec5SDimitry Andric                                       bool AllowNRVO) {
31570b57cec5SDimitry Andric   // C++14 [class.copy]p32:
31580b57cec5SDimitry Andric   // When the criteria for elision of a copy/move operation are met, but not for
31590b57cec5SDimitry Andric   // an exception-declaration, and the object to be copied is designated by an
31600b57cec5SDimitry Andric   // lvalue, or when the expression in a return statement is a (possibly
31610b57cec5SDimitry Andric   // parenthesized) id-expression that names an object with automatic storage
31620b57cec5SDimitry Andric   // duration declared in the body or parameter-declaration-clause of the
31630b57cec5SDimitry Andric   // innermost enclosing function or lambda-expression, overload resolution to
31640b57cec5SDimitry Andric   // select the constructor for the copy is first performed as if the object
31650b57cec5SDimitry Andric   // were designated by an rvalue.
31660b57cec5SDimitry Andric   ExprResult Res = ExprError();
31670b57cec5SDimitry Andric 
31680b57cec5SDimitry Andric   if (AllowNRVO) {
31690b57cec5SDimitry Andric     bool AffectedByCWG1579 = false;
31700b57cec5SDimitry Andric 
31710b57cec5SDimitry Andric     if (!NRVOCandidate) {
31720b57cec5SDimitry Andric       NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
31730b57cec5SDimitry Andric       if (NRVOCandidate &&
31740b57cec5SDimitry Andric           !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
31750b57cec5SDimitry Andric                                       Value->getExprLoc())) {
31760b57cec5SDimitry Andric         const VarDecl *NRVOCandidateInCXX11 =
31770b57cec5SDimitry Andric             getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
31780b57cec5SDimitry Andric         AffectedByCWG1579 = (!NRVOCandidateInCXX11);
31790b57cec5SDimitry Andric       }
31800b57cec5SDimitry Andric     }
31810b57cec5SDimitry Andric 
31820b57cec5SDimitry Andric     if (NRVOCandidate) {
31830b57cec5SDimitry Andric       TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
31840b57cec5SDimitry Andric                             true, Res);
31850b57cec5SDimitry Andric     }
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric     if (!Res.isInvalid() && AffectedByCWG1579) {
31880b57cec5SDimitry Andric       QualType QT = NRVOCandidate->getType();
31890b57cec5SDimitry Andric       if (QT.getNonReferenceType()
31900b57cec5SDimitry Andric                      .getUnqualifiedType()
31910b57cec5SDimitry Andric                      .isTriviallyCopyableType(Context)) {
31920b57cec5SDimitry Andric         // Adding 'std::move' around a trivially copyable variable is probably
31930b57cec5SDimitry Andric         // pointless. Don't suggest it.
31940b57cec5SDimitry Andric       } else {
31950b57cec5SDimitry Andric         // Common cases for this are returning unique_ptr<Derived> from a
31960b57cec5SDimitry Andric         // function of return type unique_ptr<Base>, or returning T from a
31970b57cec5SDimitry Andric         // function of return type Expected<T>. This is totally fine in a
31980b57cec5SDimitry Andric         // post-CWG1579 world, but was not fine before.
31990b57cec5SDimitry Andric         assert(!ResultType.isNull());
32000b57cec5SDimitry Andric         SmallString<32> Str;
32010b57cec5SDimitry Andric         Str += "std::move(";
32020b57cec5SDimitry Andric         Str += NRVOCandidate->getDeclName().getAsString();
32030b57cec5SDimitry Andric         Str += ")";
32040b57cec5SDimitry Andric         Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
32050b57cec5SDimitry Andric             << Value->getSourceRange()
32060b57cec5SDimitry Andric             << NRVOCandidate->getDeclName() << ResultType << QT;
32070b57cec5SDimitry Andric         Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
32080b57cec5SDimitry Andric             << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
32090b57cec5SDimitry Andric       }
32100b57cec5SDimitry Andric     } else if (Res.isInvalid() &&
32110b57cec5SDimitry Andric                !getDiagnostics().isIgnored(diag::warn_return_std_move,
32120b57cec5SDimitry Andric                                            Value->getExprLoc())) {
32130b57cec5SDimitry Andric       const VarDecl *FakeNRVOCandidate =
32140b57cec5SDimitry Andric           getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
32150b57cec5SDimitry Andric       if (FakeNRVOCandidate) {
32160b57cec5SDimitry Andric         QualType QT = FakeNRVOCandidate->getType();
32170b57cec5SDimitry Andric         if (QT->isLValueReferenceType()) {
32180b57cec5SDimitry Andric           // Adding 'std::move' around an lvalue reference variable's name is
32190b57cec5SDimitry Andric           // dangerous. Don't suggest it.
32200b57cec5SDimitry Andric         } else if (QT.getNonReferenceType()
32210b57cec5SDimitry Andric                        .getUnqualifiedType()
32220b57cec5SDimitry Andric                        .isTriviallyCopyableType(Context)) {
32230b57cec5SDimitry Andric           // Adding 'std::move' around a trivially copyable variable is probably
32240b57cec5SDimitry Andric           // pointless. Don't suggest it.
32250b57cec5SDimitry Andric         } else {
32260b57cec5SDimitry Andric           ExprResult FakeRes = ExprError();
32270b57cec5SDimitry Andric           Expr *FakeValue = Value;
32280b57cec5SDimitry Andric           TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
32290b57cec5SDimitry Andric                                 FakeValue, false, FakeRes);
32300b57cec5SDimitry Andric           if (!FakeRes.isInvalid()) {
32310b57cec5SDimitry Andric             bool IsThrow =
32320b57cec5SDimitry Andric                 (Entity.getKind() == InitializedEntity::EK_Exception);
32330b57cec5SDimitry Andric             SmallString<32> Str;
32340b57cec5SDimitry Andric             Str += "std::move(";
32350b57cec5SDimitry Andric             Str += FakeNRVOCandidate->getDeclName().getAsString();
32360b57cec5SDimitry Andric             Str += ")";
32370b57cec5SDimitry Andric             Diag(Value->getExprLoc(), diag::warn_return_std_move)
32380b57cec5SDimitry Andric                 << Value->getSourceRange()
32390b57cec5SDimitry Andric                 << FakeNRVOCandidate->getDeclName() << IsThrow;
32400b57cec5SDimitry Andric             Diag(Value->getExprLoc(), diag::note_add_std_move)
32410b57cec5SDimitry Andric                 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
32420b57cec5SDimitry Andric           }
32430b57cec5SDimitry Andric         }
32440b57cec5SDimitry Andric       }
32450b57cec5SDimitry Andric     }
32460b57cec5SDimitry Andric   }
32470b57cec5SDimitry Andric 
32480b57cec5SDimitry Andric   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
32490b57cec5SDimitry Andric   // above, or overload resolution failed. Either way, we need to try
32500b57cec5SDimitry Andric   // (again) now with the return value expression as written.
32510b57cec5SDimitry Andric   if (Res.isInvalid())
32520b57cec5SDimitry Andric     Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   return Res;
32550b57cec5SDimitry Andric }
32560b57cec5SDimitry Andric 
32570b57cec5SDimitry Andric /// Determine whether the declared return type of the specified function
32580b57cec5SDimitry Andric /// contains 'auto'.
32590b57cec5SDimitry Andric static bool hasDeducedReturnType(FunctionDecl *FD) {
32600b57cec5SDimitry Andric   const FunctionProtoType *FPT =
32610b57cec5SDimitry Andric       FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
32620b57cec5SDimitry Andric   return FPT->getReturnType()->isUndeducedType();
32630b57cec5SDimitry Andric }
32640b57cec5SDimitry Andric 
32650b57cec5SDimitry Andric /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
32660b57cec5SDimitry Andric /// for capturing scopes.
32670b57cec5SDimitry Andric ///
32680b57cec5SDimitry Andric StmtResult
32690b57cec5SDimitry Andric Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
32700b57cec5SDimitry Andric   // If this is the first return we've seen, infer the return type.
32710b57cec5SDimitry Andric   // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
32720b57cec5SDimitry Andric   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
32730b57cec5SDimitry Andric   QualType FnRetType = CurCap->ReturnType;
32740b57cec5SDimitry Andric   LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
32750b57cec5SDimitry Andric   bool HasDeducedReturnType =
32760b57cec5SDimitry Andric       CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
32770b57cec5SDimitry Andric 
32780b57cec5SDimitry Andric   if (ExprEvalContexts.back().Context ==
32790b57cec5SDimitry Andric           ExpressionEvaluationContext::DiscardedStatement &&
32800b57cec5SDimitry Andric       (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
32810b57cec5SDimitry Andric     if (RetValExp) {
32820b57cec5SDimitry Andric       ExprResult ER =
32830b57cec5SDimitry Andric           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
32840b57cec5SDimitry Andric       if (ER.isInvalid())
32850b57cec5SDimitry Andric         return StmtError();
32860b57cec5SDimitry Andric       RetValExp = ER.get();
32870b57cec5SDimitry Andric     }
32880b57cec5SDimitry Andric     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
32890b57cec5SDimitry Andric                               /* NRVOCandidate=*/nullptr);
32900b57cec5SDimitry Andric   }
32910b57cec5SDimitry Andric 
32920b57cec5SDimitry Andric   if (HasDeducedReturnType) {
32930b57cec5SDimitry Andric     // In C++1y, the return type may involve 'auto'.
32940b57cec5SDimitry Andric     // FIXME: Blocks might have a return type of 'auto' explicitly specified.
32950b57cec5SDimitry Andric     FunctionDecl *FD = CurLambda->CallOperator;
32960b57cec5SDimitry Andric     if (CurCap->ReturnType.isNull())
32970b57cec5SDimitry Andric       CurCap->ReturnType = FD->getReturnType();
32980b57cec5SDimitry Andric 
32990b57cec5SDimitry Andric     AutoType *AT = CurCap->ReturnType->getContainedAutoType();
33000b57cec5SDimitry Andric     assert(AT && "lost auto type from lambda return type");
33010b57cec5SDimitry Andric     if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
33020b57cec5SDimitry Andric       FD->setInvalidDecl();
3303*5ffd83dbSDimitry Andric       // FIXME: preserve the ill-formed return expression.
33040b57cec5SDimitry Andric       return StmtError();
33050b57cec5SDimitry Andric     }
33060b57cec5SDimitry Andric     CurCap->ReturnType = FnRetType = FD->getReturnType();
33070b57cec5SDimitry Andric   } else if (CurCap->HasImplicitReturnType) {
33080b57cec5SDimitry Andric     // For blocks/lambdas with implicit return types, we check each return
33090b57cec5SDimitry Andric     // statement individually, and deduce the common return type when the block
33100b57cec5SDimitry Andric     // or lambda is completed.
33110b57cec5SDimitry Andric     // FIXME: Fold this into the 'auto' codepath above.
33120b57cec5SDimitry Andric     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
33130b57cec5SDimitry Andric       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
33140b57cec5SDimitry Andric       if (Result.isInvalid())
33150b57cec5SDimitry Andric         return StmtError();
33160b57cec5SDimitry Andric       RetValExp = Result.get();
33170b57cec5SDimitry Andric 
33180b57cec5SDimitry Andric       // DR1048: even prior to C++14, we should use the 'auto' deduction rules
33190b57cec5SDimitry Andric       // when deducing a return type for a lambda-expression (or by extension
33200b57cec5SDimitry Andric       // for a block). These rules differ from the stated C++11 rules only in
33210b57cec5SDimitry Andric       // that they remove top-level cv-qualifiers.
33220b57cec5SDimitry Andric       if (!CurContext->isDependentContext())
33230b57cec5SDimitry Andric         FnRetType = RetValExp->getType().getUnqualifiedType();
33240b57cec5SDimitry Andric       else
33250b57cec5SDimitry Andric         FnRetType = CurCap->ReturnType = Context.DependentTy;
33260b57cec5SDimitry Andric     } else {
33270b57cec5SDimitry Andric       if (RetValExp) {
33280b57cec5SDimitry Andric         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
33290b57cec5SDimitry Andric         // initializer list, because it is not an expression (even
33300b57cec5SDimitry Andric         // though we represent it as one). We still deduce 'void'.
33310b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_lambda_return_init_list)
33320b57cec5SDimitry Andric           << RetValExp->getSourceRange();
33330b57cec5SDimitry Andric       }
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric       FnRetType = Context.VoidTy;
33360b57cec5SDimitry Andric     }
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric     // Although we'll properly infer the type of the block once it's completed,
33390b57cec5SDimitry Andric     // make sure we provide a return type now for better error recovery.
33400b57cec5SDimitry Andric     if (CurCap->ReturnType.isNull())
33410b57cec5SDimitry Andric       CurCap->ReturnType = FnRetType;
33420b57cec5SDimitry Andric   }
33430b57cec5SDimitry Andric   assert(!FnRetType.isNull());
33440b57cec5SDimitry Andric 
3345a7dea167SDimitry Andric   if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3346a7dea167SDimitry Andric     if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
33470b57cec5SDimitry Andric       Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
33480b57cec5SDimitry Andric       return StmtError();
33490b57cec5SDimitry Andric     }
3350a7dea167SDimitry Andric   } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
33510b57cec5SDimitry Andric     Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
33520b57cec5SDimitry Andric     return StmtError();
33530b57cec5SDimitry Andric   } else {
33540b57cec5SDimitry Andric     assert(CurLambda && "unknown kind of captured scope");
3355a7dea167SDimitry Andric     if (CurLambda->CallOperator->getType()
3356a7dea167SDimitry Andric             ->castAs<FunctionType>()
33570b57cec5SDimitry Andric             ->getNoReturnAttr()) {
33580b57cec5SDimitry Andric       Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
33590b57cec5SDimitry Andric       return StmtError();
33600b57cec5SDimitry Andric     }
33610b57cec5SDimitry Andric   }
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric   // Otherwise, verify that this result type matches the previous one.  We are
33640b57cec5SDimitry Andric   // pickier with blocks than for normal functions because we don't have GCC
33650b57cec5SDimitry Andric   // compatibility to worry about here.
33660b57cec5SDimitry Andric   const VarDecl *NRVOCandidate = nullptr;
33670b57cec5SDimitry Andric   if (FnRetType->isDependentType()) {
33680b57cec5SDimitry Andric     // Delay processing for now.  TODO: there are lots of dependent
33690b57cec5SDimitry Andric     // types we can conclusively prove aren't void.
33700b57cec5SDimitry Andric   } else if (FnRetType->isVoidType()) {
33710b57cec5SDimitry Andric     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
33720b57cec5SDimitry Andric         !(getLangOpts().CPlusPlus &&
33730b57cec5SDimitry Andric           (RetValExp->isTypeDependent() ||
33740b57cec5SDimitry Andric            RetValExp->getType()->isVoidType()))) {
33750b57cec5SDimitry Andric       if (!getLangOpts().CPlusPlus &&
33760b57cec5SDimitry Andric           RetValExp->getType()->isVoidType())
33770b57cec5SDimitry Andric         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
33780b57cec5SDimitry Andric       else {
33790b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_return_block_has_expr);
33800b57cec5SDimitry Andric         RetValExp = nullptr;
33810b57cec5SDimitry Andric       }
33820b57cec5SDimitry Andric     }
33830b57cec5SDimitry Andric   } else if (!RetValExp) {
33840b57cec5SDimitry Andric     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
33850b57cec5SDimitry Andric   } else if (!RetValExp->isTypeDependent()) {
33860b57cec5SDimitry Andric     // we have a non-void block with an expression, continue checking
33870b57cec5SDimitry Andric 
33880b57cec5SDimitry Andric     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
33890b57cec5SDimitry Andric     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
33900b57cec5SDimitry Andric     // function return.
33910b57cec5SDimitry Andric 
33920b57cec5SDimitry Andric     // In C++ the return statement is handled via a copy initialization.
33930b57cec5SDimitry Andric     // the C version of which boils down to CheckSingleAssignmentConstraints.
33940b57cec5SDimitry Andric     NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
33950b57cec5SDimitry Andric     InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
33960b57cec5SDimitry Andric                                                                    FnRetType,
33970b57cec5SDimitry Andric                                                       NRVOCandidate != nullptr);
33980b57cec5SDimitry Andric     ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
33990b57cec5SDimitry Andric                                                      FnRetType, RetValExp);
34000b57cec5SDimitry Andric     if (Res.isInvalid()) {
34010b57cec5SDimitry Andric       // FIXME: Cleanup temporaries here, anyway?
34020b57cec5SDimitry Andric       return StmtError();
34030b57cec5SDimitry Andric     }
34040b57cec5SDimitry Andric     RetValExp = Res.get();
34050b57cec5SDimitry Andric     CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
34060b57cec5SDimitry Andric   } else {
34070b57cec5SDimitry Andric     NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
34080b57cec5SDimitry Andric   }
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric   if (RetValExp) {
34110b57cec5SDimitry Andric     ExprResult ER =
34120b57cec5SDimitry Andric         ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
34130b57cec5SDimitry Andric     if (ER.isInvalid())
34140b57cec5SDimitry Andric       return StmtError();
34150b57cec5SDimitry Andric     RetValExp = ER.get();
34160b57cec5SDimitry Andric   }
34170b57cec5SDimitry Andric   auto *Result =
34180b57cec5SDimitry Andric       ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric   // If we need to check for the named return value optimization,
34210b57cec5SDimitry Andric   // or if we need to infer the return type,
34220b57cec5SDimitry Andric   // save the return statement in our scope for later processing.
34230b57cec5SDimitry Andric   if (CurCap->HasImplicitReturnType || NRVOCandidate)
34240b57cec5SDimitry Andric     FunctionScopes.back()->Returns.push_back(Result);
34250b57cec5SDimitry Andric 
34260b57cec5SDimitry Andric   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
34270b57cec5SDimitry Andric     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
34280b57cec5SDimitry Andric 
34290b57cec5SDimitry Andric   return Result;
34300b57cec5SDimitry Andric }
34310b57cec5SDimitry Andric 
34320b57cec5SDimitry Andric namespace {
34330b57cec5SDimitry Andric /// Marks all typedefs in all local classes in a type referenced.
34340b57cec5SDimitry Andric ///
34350b57cec5SDimitry Andric /// In a function like
34360b57cec5SDimitry Andric /// auto f() {
34370b57cec5SDimitry Andric ///   struct S { typedef int a; };
34380b57cec5SDimitry Andric ///   return S();
34390b57cec5SDimitry Andric /// }
34400b57cec5SDimitry Andric ///
34410b57cec5SDimitry Andric /// the local type escapes and could be referenced in some TUs but not in
34420b57cec5SDimitry Andric /// others. Pretend that all local typedefs are always referenced, to not warn
34430b57cec5SDimitry Andric /// on this. This isn't necessary if f has internal linkage, or the typedef
34440b57cec5SDimitry Andric /// is private.
34450b57cec5SDimitry Andric class LocalTypedefNameReferencer
34460b57cec5SDimitry Andric     : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
34470b57cec5SDimitry Andric public:
34480b57cec5SDimitry Andric   LocalTypedefNameReferencer(Sema &S) : S(S) {}
34490b57cec5SDimitry Andric   bool VisitRecordType(const RecordType *RT);
34500b57cec5SDimitry Andric private:
34510b57cec5SDimitry Andric   Sema &S;
34520b57cec5SDimitry Andric };
34530b57cec5SDimitry Andric bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
34540b57cec5SDimitry Andric   auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
34550b57cec5SDimitry Andric   if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
34560b57cec5SDimitry Andric       R->isDependentType())
34570b57cec5SDimitry Andric     return true;
34580b57cec5SDimitry Andric   for (auto *TmpD : R->decls())
34590b57cec5SDimitry Andric     if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
34600b57cec5SDimitry Andric       if (T->getAccess() != AS_private || R->hasFriends())
34610b57cec5SDimitry Andric         S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
34620b57cec5SDimitry Andric   return true;
34630b57cec5SDimitry Andric }
34640b57cec5SDimitry Andric }
34650b57cec5SDimitry Andric 
34660b57cec5SDimitry Andric TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
34670b57cec5SDimitry Andric   return FD->getTypeSourceInfo()
34680b57cec5SDimitry Andric       ->getTypeLoc()
34690b57cec5SDimitry Andric       .getAsAdjusted<FunctionProtoTypeLoc>()
34700b57cec5SDimitry Andric       .getReturnLoc();
34710b57cec5SDimitry Andric }
34720b57cec5SDimitry Andric 
34730b57cec5SDimitry Andric /// Deduce the return type for a function from a returned expression, per
34740b57cec5SDimitry Andric /// C++1y [dcl.spec.auto]p6.
34750b57cec5SDimitry Andric bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
34760b57cec5SDimitry Andric                                             SourceLocation ReturnLoc,
34770b57cec5SDimitry Andric                                             Expr *&RetExpr,
34780b57cec5SDimitry Andric                                             AutoType *AT) {
34790b57cec5SDimitry Andric   // If this is the conversion function for a lambda, we choose to deduce it
34800b57cec5SDimitry Andric   // type from the corresponding call operator, not from the synthesized return
34810b57cec5SDimitry Andric   // statement within it. See Sema::DeduceReturnType.
34820b57cec5SDimitry Andric   if (isLambdaConversionOperator(FD))
34830b57cec5SDimitry Andric     return false;
34840b57cec5SDimitry Andric 
34850b57cec5SDimitry Andric   TypeLoc OrigResultType = getReturnTypeLoc(FD);
34860b57cec5SDimitry Andric   QualType Deduced;
34870b57cec5SDimitry Andric 
34880b57cec5SDimitry Andric   if (RetExpr && isa<InitListExpr>(RetExpr)) {
34890b57cec5SDimitry Andric     //  If the deduction is for a return statement and the initializer is
34900b57cec5SDimitry Andric     //  a braced-init-list, the program is ill-formed.
34910b57cec5SDimitry Andric     Diag(RetExpr->getExprLoc(),
34920b57cec5SDimitry Andric          getCurLambda() ? diag::err_lambda_return_init_list
34930b57cec5SDimitry Andric                         : diag::err_auto_fn_return_init_list)
34940b57cec5SDimitry Andric         << RetExpr->getSourceRange();
34950b57cec5SDimitry Andric     return true;
34960b57cec5SDimitry Andric   }
34970b57cec5SDimitry Andric 
34980b57cec5SDimitry Andric   if (FD->isDependentContext()) {
34990b57cec5SDimitry Andric     // C++1y [dcl.spec.auto]p12:
35000b57cec5SDimitry Andric     //   Return type deduction [...] occurs when the definition is
35010b57cec5SDimitry Andric     //   instantiated even if the function body contains a return
35020b57cec5SDimitry Andric     //   statement with a non-type-dependent operand.
35030b57cec5SDimitry Andric     assert(AT->isDeduced() && "should have deduced to dependent type");
35040b57cec5SDimitry Andric     return false;
35050b57cec5SDimitry Andric   }
35060b57cec5SDimitry Andric 
35070b57cec5SDimitry Andric   if (RetExpr) {
35080b57cec5SDimitry Andric     //  Otherwise, [...] deduce a value for U using the rules of template
35090b57cec5SDimitry Andric     //  argument deduction.
35100b57cec5SDimitry Andric     DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
35110b57cec5SDimitry Andric 
35120b57cec5SDimitry Andric     if (DAR == DAR_Failed && !FD->isInvalidDecl())
35130b57cec5SDimitry Andric       Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
35140b57cec5SDimitry Andric         << OrigResultType.getType() << RetExpr->getType();
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric     if (DAR != DAR_Succeeded)
35170b57cec5SDimitry Andric       return true;
35180b57cec5SDimitry Andric 
35190b57cec5SDimitry Andric     // If a local type is part of the returned type, mark its fields as
35200b57cec5SDimitry Andric     // referenced.
35210b57cec5SDimitry Andric     LocalTypedefNameReferencer Referencer(*this);
35220b57cec5SDimitry Andric     Referencer.TraverseType(RetExpr->getType());
35230b57cec5SDimitry Andric   } else {
35240b57cec5SDimitry Andric     //  In the case of a return with no operand, the initializer is considered
35250b57cec5SDimitry Andric     //  to be void().
35260b57cec5SDimitry Andric     //
35270b57cec5SDimitry Andric     // Deduction here can only succeed if the return type is exactly 'cv auto'
35280b57cec5SDimitry Andric     // or 'decltype(auto)', so just check for that case directly.
35290b57cec5SDimitry Andric     if (!OrigResultType.getType()->getAs<AutoType>()) {
35300b57cec5SDimitry Andric       Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
35310b57cec5SDimitry Andric         << OrigResultType.getType();
35320b57cec5SDimitry Andric       return true;
35330b57cec5SDimitry Andric     }
35340b57cec5SDimitry Andric     // We always deduce U = void in this case.
35350b57cec5SDimitry Andric     Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
35360b57cec5SDimitry Andric     if (Deduced.isNull())
35370b57cec5SDimitry Andric       return true;
35380b57cec5SDimitry Andric   }
35390b57cec5SDimitry Andric 
3540a7dea167SDimitry Andric   // CUDA: Kernel function must have 'void' return type.
3541a7dea167SDimitry Andric   if (getLangOpts().CUDA)
3542a7dea167SDimitry Andric     if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) {
3543a7dea167SDimitry Andric       Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3544a7dea167SDimitry Andric           << FD->getType() << FD->getSourceRange();
3545a7dea167SDimitry Andric       return true;
3546a7dea167SDimitry Andric     }
3547a7dea167SDimitry Andric 
35480b57cec5SDimitry Andric   //  If a function with a declared return type that contains a placeholder type
35490b57cec5SDimitry Andric   //  has multiple return statements, the return type is deduced for each return
35500b57cec5SDimitry Andric   //  statement. [...] if the type deduced is not the same in each deduction,
35510b57cec5SDimitry Andric   //  the program is ill-formed.
35520b57cec5SDimitry Andric   QualType DeducedT = AT->getDeducedType();
35530b57cec5SDimitry Andric   if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
35540b57cec5SDimitry Andric     AutoType *NewAT = Deduced->getContainedAutoType();
35550b57cec5SDimitry Andric     // It is possible that NewAT->getDeducedType() is null. When that happens,
35560b57cec5SDimitry Andric     // we should not crash, instead we ignore this deduction.
35570b57cec5SDimitry Andric     if (NewAT->getDeducedType().isNull())
35580b57cec5SDimitry Andric       return false;
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric     CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
35610b57cec5SDimitry Andric                                    DeducedT);
35620b57cec5SDimitry Andric     CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
35630b57cec5SDimitry Andric                                    NewAT->getDeducedType());
35640b57cec5SDimitry Andric     if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
35650b57cec5SDimitry Andric       const LambdaScopeInfo *LambdaSI = getCurLambda();
35660b57cec5SDimitry Andric       if (LambdaSI && LambdaSI->HasImplicitReturnType) {
35670b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
35680b57cec5SDimitry Andric           << NewAT->getDeducedType() << DeducedT
35690b57cec5SDimitry Andric           << true /*IsLambda*/;
35700b57cec5SDimitry Andric       } else {
35710b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
35720b57cec5SDimitry Andric           << (AT->isDecltypeAuto() ? 1 : 0)
35730b57cec5SDimitry Andric           << NewAT->getDeducedType() << DeducedT;
35740b57cec5SDimitry Andric       }
35750b57cec5SDimitry Andric       return true;
35760b57cec5SDimitry Andric     }
35770b57cec5SDimitry Andric   } else if (!FD->isInvalidDecl()) {
35780b57cec5SDimitry Andric     // Update all declarations of the function to have the deduced return type.
35790b57cec5SDimitry Andric     Context.adjustDeducedFunctionResultType(FD, Deduced);
35800b57cec5SDimitry Andric   }
35810b57cec5SDimitry Andric 
35820b57cec5SDimitry Andric   return false;
35830b57cec5SDimitry Andric }
35840b57cec5SDimitry Andric 
35850b57cec5SDimitry Andric StmtResult
35860b57cec5SDimitry Andric Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
35870b57cec5SDimitry Andric                       Scope *CurScope) {
35880b57cec5SDimitry Andric   // Correct typos, in case the containing function returns 'auto' and
35890b57cec5SDimitry Andric   // RetValExp should determine the deduced type.
35900b57cec5SDimitry Andric   ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
35910b57cec5SDimitry Andric   if (RetVal.isInvalid())
35920b57cec5SDimitry Andric     return StmtError();
35930b57cec5SDimitry Andric   StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
35940b57cec5SDimitry Andric   if (R.isInvalid() || ExprEvalContexts.back().Context ==
35950b57cec5SDimitry Andric                            ExpressionEvaluationContext::DiscardedStatement)
35960b57cec5SDimitry Andric     return R;
35970b57cec5SDimitry Andric 
35980b57cec5SDimitry Andric   if (VarDecl *VD =
35990b57cec5SDimitry Andric       const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
36000b57cec5SDimitry Andric     CurScope->addNRVOCandidate(VD);
36010b57cec5SDimitry Andric   } else {
36020b57cec5SDimitry Andric     CurScope->setNoNRVO();
36030b57cec5SDimitry Andric   }
36040b57cec5SDimitry Andric 
36050b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
36060b57cec5SDimitry Andric 
36070b57cec5SDimitry Andric   return R;
36080b57cec5SDimitry Andric }
36090b57cec5SDimitry Andric 
36100b57cec5SDimitry Andric StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
36110b57cec5SDimitry Andric   // Check for unexpanded parameter packs.
36120b57cec5SDimitry Andric   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
36130b57cec5SDimitry Andric     return StmtError();
36140b57cec5SDimitry Andric 
36150b57cec5SDimitry Andric   if (isa<CapturingScopeInfo>(getCurFunction()))
36160b57cec5SDimitry Andric     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
36170b57cec5SDimitry Andric 
36180b57cec5SDimitry Andric   QualType FnRetType;
36190b57cec5SDimitry Andric   QualType RelatedRetType;
36200b57cec5SDimitry Andric   const AttrVec *Attrs = nullptr;
36210b57cec5SDimitry Andric   bool isObjCMethod = false;
36220b57cec5SDimitry Andric 
36230b57cec5SDimitry Andric   if (const FunctionDecl *FD = getCurFunctionDecl()) {
36240b57cec5SDimitry Andric     FnRetType = FD->getReturnType();
36250b57cec5SDimitry Andric     if (FD->hasAttrs())
36260b57cec5SDimitry Andric       Attrs = &FD->getAttrs();
36270b57cec5SDimitry Andric     if (FD->isNoReturn())
36280b57cec5SDimitry Andric       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
36290b57cec5SDimitry Andric         << FD->getDeclName();
36300b57cec5SDimitry Andric     if (FD->isMain() && RetValExp)
36310b57cec5SDimitry Andric       if (isa<CXXBoolLiteralExpr>(RetValExp))
36320b57cec5SDimitry Andric         Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
36330b57cec5SDimitry Andric           << RetValExp->getSourceRange();
3634*5ffd83dbSDimitry Andric     if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3635*5ffd83dbSDimitry Andric       if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
3636*5ffd83dbSDimitry Andric         if (RT->getDecl()->isOrContainsUnion())
3637*5ffd83dbSDimitry Andric           Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3638*5ffd83dbSDimitry Andric       }
3639*5ffd83dbSDimitry Andric     }
36400b57cec5SDimitry Andric   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
36410b57cec5SDimitry Andric     FnRetType = MD->getReturnType();
36420b57cec5SDimitry Andric     isObjCMethod = true;
36430b57cec5SDimitry Andric     if (MD->hasAttrs())
36440b57cec5SDimitry Andric       Attrs = &MD->getAttrs();
36450b57cec5SDimitry Andric     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
36460b57cec5SDimitry Andric       // In the implementation of a method with a related return type, the
36470b57cec5SDimitry Andric       // type used to type-check the validity of return statements within the
36480b57cec5SDimitry Andric       // method body is a pointer to the type of the class being implemented.
36490b57cec5SDimitry Andric       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
36500b57cec5SDimitry Andric       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
36510b57cec5SDimitry Andric     }
36520b57cec5SDimitry Andric   } else // If we don't have a function/method context, bail.
36530b57cec5SDimitry Andric     return StmtError();
36540b57cec5SDimitry Andric 
36550b57cec5SDimitry Andric   // C++1z: discarded return statements are not considered when deducing a
36560b57cec5SDimitry Andric   // return type.
36570b57cec5SDimitry Andric   if (ExprEvalContexts.back().Context ==
36580b57cec5SDimitry Andric           ExpressionEvaluationContext::DiscardedStatement &&
36590b57cec5SDimitry Andric       FnRetType->getContainedAutoType()) {
36600b57cec5SDimitry Andric     if (RetValExp) {
36610b57cec5SDimitry Andric       ExprResult ER =
36620b57cec5SDimitry Andric           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
36630b57cec5SDimitry Andric       if (ER.isInvalid())
36640b57cec5SDimitry Andric         return StmtError();
36650b57cec5SDimitry Andric       RetValExp = ER.get();
36660b57cec5SDimitry Andric     }
36670b57cec5SDimitry Andric     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
36680b57cec5SDimitry Andric                               /* NRVOCandidate=*/nullptr);
36690b57cec5SDimitry Andric   }
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric   // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
36720b57cec5SDimitry Andric   // deduction.
36730b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus14) {
36740b57cec5SDimitry Andric     if (AutoType *AT = FnRetType->getContainedAutoType()) {
36750b57cec5SDimitry Andric       FunctionDecl *FD = cast<FunctionDecl>(CurContext);
36760b57cec5SDimitry Andric       if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
36770b57cec5SDimitry Andric         FD->setInvalidDecl();
36780b57cec5SDimitry Andric         return StmtError();
36790b57cec5SDimitry Andric       } else {
36800b57cec5SDimitry Andric         FnRetType = FD->getReturnType();
36810b57cec5SDimitry Andric       }
36820b57cec5SDimitry Andric     }
36830b57cec5SDimitry Andric   }
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric   bool HasDependentReturnType = FnRetType->isDependentType();
36860b57cec5SDimitry Andric 
36870b57cec5SDimitry Andric   ReturnStmt *Result = nullptr;
36880b57cec5SDimitry Andric   if (FnRetType->isVoidType()) {
36890b57cec5SDimitry Andric     if (RetValExp) {
36900b57cec5SDimitry Andric       if (isa<InitListExpr>(RetValExp)) {
36910b57cec5SDimitry Andric         // We simply never allow init lists as the return value of void
36920b57cec5SDimitry Andric         // functions. This is compatible because this was never allowed before,
36930b57cec5SDimitry Andric         // so there's no legacy code to deal with.
36940b57cec5SDimitry Andric         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
36950b57cec5SDimitry Andric         int FunctionKind = 0;
36960b57cec5SDimitry Andric         if (isa<ObjCMethodDecl>(CurDecl))
36970b57cec5SDimitry Andric           FunctionKind = 1;
36980b57cec5SDimitry Andric         else if (isa<CXXConstructorDecl>(CurDecl))
36990b57cec5SDimitry Andric           FunctionKind = 2;
37000b57cec5SDimitry Andric         else if (isa<CXXDestructorDecl>(CurDecl))
37010b57cec5SDimitry Andric           FunctionKind = 3;
37020b57cec5SDimitry Andric 
37030b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_return_init_list)
37040b57cec5SDimitry Andric           << CurDecl->getDeclName() << FunctionKind
37050b57cec5SDimitry Andric           << RetValExp->getSourceRange();
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric         // Drop the expression.
37080b57cec5SDimitry Andric         RetValExp = nullptr;
37090b57cec5SDimitry Andric       } else if (!RetValExp->isTypeDependent()) {
37100b57cec5SDimitry Andric         // C99 6.8.6.4p1 (ext_ since GCC warns)
37110b57cec5SDimitry Andric         unsigned D = diag::ext_return_has_expr;
37120b57cec5SDimitry Andric         if (RetValExp->getType()->isVoidType()) {
37130b57cec5SDimitry Andric           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
37140b57cec5SDimitry Andric           if (isa<CXXConstructorDecl>(CurDecl) ||
37150b57cec5SDimitry Andric               isa<CXXDestructorDecl>(CurDecl))
37160b57cec5SDimitry Andric             D = diag::err_ctor_dtor_returns_void;
37170b57cec5SDimitry Andric           else
37180b57cec5SDimitry Andric             D = diag::ext_return_has_void_expr;
37190b57cec5SDimitry Andric         }
37200b57cec5SDimitry Andric         else {
37210b57cec5SDimitry Andric           ExprResult Result = RetValExp;
37220b57cec5SDimitry Andric           Result = IgnoredValueConversions(Result.get());
37230b57cec5SDimitry Andric           if (Result.isInvalid())
37240b57cec5SDimitry Andric             return StmtError();
37250b57cec5SDimitry Andric           RetValExp = Result.get();
37260b57cec5SDimitry Andric           RetValExp = ImpCastExprToType(RetValExp,
37270b57cec5SDimitry Andric                                         Context.VoidTy, CK_ToVoid).get();
37280b57cec5SDimitry Andric         }
37290b57cec5SDimitry Andric         // return of void in constructor/destructor is illegal in C++.
37300b57cec5SDimitry Andric         if (D == diag::err_ctor_dtor_returns_void) {
37310b57cec5SDimitry Andric           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
37320b57cec5SDimitry Andric           Diag(ReturnLoc, D)
37330b57cec5SDimitry Andric             << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
37340b57cec5SDimitry Andric             << RetValExp->getSourceRange();
37350b57cec5SDimitry Andric         }
37360b57cec5SDimitry Andric         // return (some void expression); is legal in C++.
37370b57cec5SDimitry Andric         else if (D != diag::ext_return_has_void_expr ||
37380b57cec5SDimitry Andric                  !getLangOpts().CPlusPlus) {
37390b57cec5SDimitry Andric           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric           int FunctionKind = 0;
37420b57cec5SDimitry Andric           if (isa<ObjCMethodDecl>(CurDecl))
37430b57cec5SDimitry Andric             FunctionKind = 1;
37440b57cec5SDimitry Andric           else if (isa<CXXConstructorDecl>(CurDecl))
37450b57cec5SDimitry Andric             FunctionKind = 2;
37460b57cec5SDimitry Andric           else if (isa<CXXDestructorDecl>(CurDecl))
37470b57cec5SDimitry Andric             FunctionKind = 3;
37480b57cec5SDimitry Andric 
37490b57cec5SDimitry Andric           Diag(ReturnLoc, D)
37500b57cec5SDimitry Andric             << CurDecl->getDeclName() << FunctionKind
37510b57cec5SDimitry Andric             << RetValExp->getSourceRange();
37520b57cec5SDimitry Andric         }
37530b57cec5SDimitry Andric       }
37540b57cec5SDimitry Andric 
37550b57cec5SDimitry Andric       if (RetValExp) {
37560b57cec5SDimitry Andric         ExprResult ER =
37570b57cec5SDimitry Andric             ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
37580b57cec5SDimitry Andric         if (ER.isInvalid())
37590b57cec5SDimitry Andric           return StmtError();
37600b57cec5SDimitry Andric         RetValExp = ER.get();
37610b57cec5SDimitry Andric       }
37620b57cec5SDimitry Andric     }
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
37650b57cec5SDimitry Andric                                 /* NRVOCandidate=*/nullptr);
37660b57cec5SDimitry Andric   } else if (!RetValExp && !HasDependentReturnType) {
37670b57cec5SDimitry Andric     FunctionDecl *FD = getCurFunctionDecl();
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric     unsigned DiagID;
37700b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
37710b57cec5SDimitry Andric       // C++11 [stmt.return]p2
37720b57cec5SDimitry Andric       DiagID = diag::err_constexpr_return_missing_expr;
37730b57cec5SDimitry Andric       FD->setInvalidDecl();
37740b57cec5SDimitry Andric     } else if (getLangOpts().C99) {
37750b57cec5SDimitry Andric       // C99 6.8.6.4p1 (ext_ since GCC warns)
37760b57cec5SDimitry Andric       DiagID = diag::ext_return_missing_expr;
37770b57cec5SDimitry Andric     } else {
37780b57cec5SDimitry Andric       // C90 6.6.6.4p4
37790b57cec5SDimitry Andric       DiagID = diag::warn_return_missing_expr;
37800b57cec5SDimitry Andric     }
37810b57cec5SDimitry Andric 
37820b57cec5SDimitry Andric     if (FD)
37830b57cec5SDimitry Andric       Diag(ReturnLoc, DiagID)
37840b57cec5SDimitry Andric           << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
37850b57cec5SDimitry Andric     else
37860b57cec5SDimitry Andric       Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
37870b57cec5SDimitry Andric 
37880b57cec5SDimitry Andric     Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
37890b57cec5SDimitry Andric                                 /* NRVOCandidate=*/nullptr);
37900b57cec5SDimitry Andric   } else {
37910b57cec5SDimitry Andric     assert(RetValExp || HasDependentReturnType);
37920b57cec5SDimitry Andric     const VarDecl *NRVOCandidate = nullptr;
37930b57cec5SDimitry Andric 
37940b57cec5SDimitry Andric     QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
37950b57cec5SDimitry Andric 
37960b57cec5SDimitry Andric     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
37970b57cec5SDimitry Andric     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
37980b57cec5SDimitry Andric     // function return.
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric     // In C++ the return statement is handled via a copy initialization,
38010b57cec5SDimitry Andric     // the C version of which boils down to CheckSingleAssignmentConstraints.
38020b57cec5SDimitry Andric     if (RetValExp)
38030b57cec5SDimitry Andric       NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
38040b57cec5SDimitry Andric     if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
38050b57cec5SDimitry Andric       // we have a non-void function with an expression, continue checking
38060b57cec5SDimitry Andric       InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
38070b57cec5SDimitry Andric                                                                      RetType,
38080b57cec5SDimitry Andric                                                       NRVOCandidate != nullptr);
38090b57cec5SDimitry Andric       ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
38100b57cec5SDimitry Andric                                                        RetType, RetValExp);
38110b57cec5SDimitry Andric       if (Res.isInvalid()) {
38120b57cec5SDimitry Andric         // FIXME: Clean up temporaries here anyway?
38130b57cec5SDimitry Andric         return StmtError();
38140b57cec5SDimitry Andric       }
38150b57cec5SDimitry Andric       RetValExp = Res.getAs<Expr>();
38160b57cec5SDimitry Andric 
38170b57cec5SDimitry Andric       // If we have a related result type, we need to implicitly
38180b57cec5SDimitry Andric       // convert back to the formal result type.  We can't pretend to
38190b57cec5SDimitry Andric       // initialize the result again --- we might end double-retaining
38200b57cec5SDimitry Andric       // --- so instead we initialize a notional temporary.
38210b57cec5SDimitry Andric       if (!RelatedRetType.isNull()) {
38220b57cec5SDimitry Andric         Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
38230b57cec5SDimitry Andric                                                             FnRetType);
38240b57cec5SDimitry Andric         Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
38250b57cec5SDimitry Andric         if (Res.isInvalid()) {
38260b57cec5SDimitry Andric           // FIXME: Clean up temporaries here anyway?
38270b57cec5SDimitry Andric           return StmtError();
38280b57cec5SDimitry Andric         }
38290b57cec5SDimitry Andric         RetValExp = Res.getAs<Expr>();
38300b57cec5SDimitry Andric       }
38310b57cec5SDimitry Andric 
38320b57cec5SDimitry Andric       CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
38330b57cec5SDimitry Andric                          getCurFunctionDecl());
38340b57cec5SDimitry Andric     }
38350b57cec5SDimitry Andric 
38360b57cec5SDimitry Andric     if (RetValExp) {
38370b57cec5SDimitry Andric       ExprResult ER =
38380b57cec5SDimitry Andric           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
38390b57cec5SDimitry Andric       if (ER.isInvalid())
38400b57cec5SDimitry Andric         return StmtError();
38410b57cec5SDimitry Andric       RetValExp = ER.get();
38420b57cec5SDimitry Andric     }
38430b57cec5SDimitry Andric     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
38440b57cec5SDimitry Andric   }
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric   // If we need to check for the named return value optimization, save the
38470b57cec5SDimitry Andric   // return statement in our scope for later processing.
38480b57cec5SDimitry Andric   if (Result->getNRVOCandidate())
38490b57cec5SDimitry Andric     FunctionScopes.back()->Returns.push_back(Result);
38500b57cec5SDimitry Andric 
38510b57cec5SDimitry Andric   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
38520b57cec5SDimitry Andric     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
38530b57cec5SDimitry Andric 
38540b57cec5SDimitry Andric   return Result;
38550b57cec5SDimitry Andric }
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric StmtResult
38580b57cec5SDimitry Andric Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
38590b57cec5SDimitry Andric                            SourceLocation RParen, Decl *Parm,
38600b57cec5SDimitry Andric                            Stmt *Body) {
38610b57cec5SDimitry Andric   VarDecl *Var = cast_or_null<VarDecl>(Parm);
38620b57cec5SDimitry Andric   if (Var && Var->isInvalidDecl())
38630b57cec5SDimitry Andric     return StmtError();
38640b57cec5SDimitry Andric 
38650b57cec5SDimitry Andric   return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
38660b57cec5SDimitry Andric }
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric StmtResult
38690b57cec5SDimitry Andric Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
38700b57cec5SDimitry Andric   return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
38710b57cec5SDimitry Andric }
38720b57cec5SDimitry Andric 
38730b57cec5SDimitry Andric StmtResult
38740b57cec5SDimitry Andric Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
38750b57cec5SDimitry Andric                          MultiStmtArg CatchStmts, Stmt *Finally) {
38760b57cec5SDimitry Andric   if (!getLangOpts().ObjCExceptions)
38770b57cec5SDimitry Andric     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
38780b57cec5SDimitry Andric 
38790b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
38800b57cec5SDimitry Andric   unsigned NumCatchStmts = CatchStmts.size();
38810b57cec5SDimitry Andric   return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
38820b57cec5SDimitry Andric                                NumCatchStmts, Finally);
38830b57cec5SDimitry Andric }
38840b57cec5SDimitry Andric 
38850b57cec5SDimitry Andric StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
38860b57cec5SDimitry Andric   if (Throw) {
38870b57cec5SDimitry Andric     ExprResult Result = DefaultLvalueConversion(Throw);
38880b57cec5SDimitry Andric     if (Result.isInvalid())
38890b57cec5SDimitry Andric       return StmtError();
38900b57cec5SDimitry Andric 
38910b57cec5SDimitry Andric     Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
38920b57cec5SDimitry Andric     if (Result.isInvalid())
38930b57cec5SDimitry Andric       return StmtError();
38940b57cec5SDimitry Andric     Throw = Result.get();
38950b57cec5SDimitry Andric 
38960b57cec5SDimitry Andric     QualType ThrowType = Throw->getType();
38970b57cec5SDimitry Andric     // Make sure the expression type is an ObjC pointer or "void *".
38980b57cec5SDimitry Andric     if (!ThrowType->isDependentType() &&
38990b57cec5SDimitry Andric         !ThrowType->isObjCObjectPointerType()) {
39000b57cec5SDimitry Andric       const PointerType *PT = ThrowType->getAs<PointerType>();
39010b57cec5SDimitry Andric       if (!PT || !PT->getPointeeType()->isVoidType())
39020b57cec5SDimitry Andric         return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
39030b57cec5SDimitry Andric                          << Throw->getType() << Throw->getSourceRange());
39040b57cec5SDimitry Andric     }
39050b57cec5SDimitry Andric   }
39060b57cec5SDimitry Andric 
39070b57cec5SDimitry Andric   return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
39080b57cec5SDimitry Andric }
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric StmtResult
39110b57cec5SDimitry Andric Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
39120b57cec5SDimitry Andric                            Scope *CurScope) {
39130b57cec5SDimitry Andric   if (!getLangOpts().ObjCExceptions)
39140b57cec5SDimitry Andric     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
39150b57cec5SDimitry Andric 
39160b57cec5SDimitry Andric   if (!Throw) {
39170b57cec5SDimitry Andric     // @throw without an expression designates a rethrow (which must occur
39180b57cec5SDimitry Andric     // in the context of an @catch clause).
39190b57cec5SDimitry Andric     Scope *AtCatchParent = CurScope;
39200b57cec5SDimitry Andric     while (AtCatchParent && !AtCatchParent->isAtCatchScope())
39210b57cec5SDimitry Andric       AtCatchParent = AtCatchParent->getParent();
39220b57cec5SDimitry Andric     if (!AtCatchParent)
39230b57cec5SDimitry Andric       return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
39240b57cec5SDimitry Andric   }
39250b57cec5SDimitry Andric   return BuildObjCAtThrowStmt(AtLoc, Throw);
39260b57cec5SDimitry Andric }
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric ExprResult
39290b57cec5SDimitry Andric Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
39300b57cec5SDimitry Andric   ExprResult result = DefaultLvalueConversion(operand);
39310b57cec5SDimitry Andric   if (result.isInvalid())
39320b57cec5SDimitry Andric     return ExprError();
39330b57cec5SDimitry Andric   operand = result.get();
39340b57cec5SDimitry Andric 
39350b57cec5SDimitry Andric   // Make sure the expression type is an ObjC pointer or "void *".
39360b57cec5SDimitry Andric   QualType type = operand->getType();
39370b57cec5SDimitry Andric   if (!type->isDependentType() &&
39380b57cec5SDimitry Andric       !type->isObjCObjectPointerType()) {
39390b57cec5SDimitry Andric     const PointerType *pointerType = type->getAs<PointerType>();
39400b57cec5SDimitry Andric     if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
39410b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
39420b57cec5SDimitry Andric         if (RequireCompleteType(atLoc, type,
39430b57cec5SDimitry Andric                                 diag::err_incomplete_receiver_type))
39440b57cec5SDimitry Andric           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
39450b57cec5SDimitry Andric                    << type << operand->getSourceRange();
39460b57cec5SDimitry Andric 
39470b57cec5SDimitry Andric         ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
39480b57cec5SDimitry Andric         if (result.isInvalid())
39490b57cec5SDimitry Andric           return ExprError();
39500b57cec5SDimitry Andric         if (!result.isUsable())
39510b57cec5SDimitry Andric           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
39520b57cec5SDimitry Andric                    << type << operand->getSourceRange();
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric         operand = result.get();
39550b57cec5SDimitry Andric       } else {
39560b57cec5SDimitry Andric           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
39570b57cec5SDimitry Andric                    << type << operand->getSourceRange();
39580b57cec5SDimitry Andric       }
39590b57cec5SDimitry Andric     }
39600b57cec5SDimitry Andric   }
39610b57cec5SDimitry Andric 
39620b57cec5SDimitry Andric   // The operand to @synchronized is a full-expression.
39630b57cec5SDimitry Andric   return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
39640b57cec5SDimitry Andric }
39650b57cec5SDimitry Andric 
39660b57cec5SDimitry Andric StmtResult
39670b57cec5SDimitry Andric Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
39680b57cec5SDimitry Andric                                   Stmt *SyncBody) {
39690b57cec5SDimitry Andric   // We can't jump into or indirect-jump out of a @synchronized block.
39700b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
39710b57cec5SDimitry Andric   return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
39720b57cec5SDimitry Andric }
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
39750b57cec5SDimitry Andric /// and creates a proper catch handler from them.
39760b57cec5SDimitry Andric StmtResult
39770b57cec5SDimitry Andric Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
39780b57cec5SDimitry Andric                          Stmt *HandlerBlock) {
39790b57cec5SDimitry Andric   // There's nothing to test that ActOnExceptionDecl didn't already test.
39800b57cec5SDimitry Andric   return new (Context)
39810b57cec5SDimitry Andric       CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
39820b57cec5SDimitry Andric }
39830b57cec5SDimitry Andric 
39840b57cec5SDimitry Andric StmtResult
39850b57cec5SDimitry Andric Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
39860b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
39870b57cec5SDimitry Andric   return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
39880b57cec5SDimitry Andric }
39890b57cec5SDimitry Andric 
39900b57cec5SDimitry Andric namespace {
39910b57cec5SDimitry Andric class CatchHandlerType {
39920b57cec5SDimitry Andric   QualType QT;
39930b57cec5SDimitry Andric   unsigned IsPointer : 1;
39940b57cec5SDimitry Andric 
39950b57cec5SDimitry Andric   // This is a special constructor to be used only with DenseMapInfo's
39960b57cec5SDimitry Andric   // getEmptyKey() and getTombstoneKey() functions.
39970b57cec5SDimitry Andric   friend struct llvm::DenseMapInfo<CatchHandlerType>;
39980b57cec5SDimitry Andric   enum Unique { ForDenseMap };
39990b57cec5SDimitry Andric   CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
40000b57cec5SDimitry Andric 
40010b57cec5SDimitry Andric public:
40020b57cec5SDimitry Andric   /// Used when creating a CatchHandlerType from a handler type; will determine
40030b57cec5SDimitry Andric   /// whether the type is a pointer or reference and will strip off the top
40040b57cec5SDimitry Andric   /// level pointer and cv-qualifiers.
40050b57cec5SDimitry Andric   CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
40060b57cec5SDimitry Andric     if (QT->isPointerType())
40070b57cec5SDimitry Andric       IsPointer = true;
40080b57cec5SDimitry Andric 
40090b57cec5SDimitry Andric     if (IsPointer || QT->isReferenceType())
40100b57cec5SDimitry Andric       QT = QT->getPointeeType();
40110b57cec5SDimitry Andric     QT = QT.getUnqualifiedType();
40120b57cec5SDimitry Andric   }
40130b57cec5SDimitry Andric 
40140b57cec5SDimitry Andric   /// Used when creating a CatchHandlerType from a base class type; pretends the
40150b57cec5SDimitry Andric   /// type passed in had the pointer qualifier, does not need to get an
40160b57cec5SDimitry Andric   /// unqualified type.
40170b57cec5SDimitry Andric   CatchHandlerType(QualType QT, bool IsPointer)
40180b57cec5SDimitry Andric       : QT(QT), IsPointer(IsPointer) {}
40190b57cec5SDimitry Andric 
40200b57cec5SDimitry Andric   QualType underlying() const { return QT; }
40210b57cec5SDimitry Andric   bool isPointer() const { return IsPointer; }
40220b57cec5SDimitry Andric 
40230b57cec5SDimitry Andric   friend bool operator==(const CatchHandlerType &LHS,
40240b57cec5SDimitry Andric                          const CatchHandlerType &RHS) {
40250b57cec5SDimitry Andric     // If the pointer qualification does not match, we can return early.
40260b57cec5SDimitry Andric     if (LHS.IsPointer != RHS.IsPointer)
40270b57cec5SDimitry Andric       return false;
40280b57cec5SDimitry Andric     // Otherwise, check the underlying type without cv-qualifiers.
40290b57cec5SDimitry Andric     return LHS.QT == RHS.QT;
40300b57cec5SDimitry Andric   }
40310b57cec5SDimitry Andric };
40320b57cec5SDimitry Andric } // namespace
40330b57cec5SDimitry Andric 
40340b57cec5SDimitry Andric namespace llvm {
40350b57cec5SDimitry Andric template <> struct DenseMapInfo<CatchHandlerType> {
40360b57cec5SDimitry Andric   static CatchHandlerType getEmptyKey() {
40370b57cec5SDimitry Andric     return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
40380b57cec5SDimitry Andric                        CatchHandlerType::ForDenseMap);
40390b57cec5SDimitry Andric   }
40400b57cec5SDimitry Andric 
40410b57cec5SDimitry Andric   static CatchHandlerType getTombstoneKey() {
40420b57cec5SDimitry Andric     return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
40430b57cec5SDimitry Andric                        CatchHandlerType::ForDenseMap);
40440b57cec5SDimitry Andric   }
40450b57cec5SDimitry Andric 
40460b57cec5SDimitry Andric   static unsigned getHashValue(const CatchHandlerType &Base) {
40470b57cec5SDimitry Andric     return DenseMapInfo<QualType>::getHashValue(Base.underlying());
40480b57cec5SDimitry Andric   }
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   static bool isEqual(const CatchHandlerType &LHS,
40510b57cec5SDimitry Andric                       const CatchHandlerType &RHS) {
40520b57cec5SDimitry Andric     return LHS == RHS;
40530b57cec5SDimitry Andric   }
40540b57cec5SDimitry Andric };
40550b57cec5SDimitry Andric }
40560b57cec5SDimitry Andric 
40570b57cec5SDimitry Andric namespace {
40580b57cec5SDimitry Andric class CatchTypePublicBases {
40590b57cec5SDimitry Andric   ASTContext &Ctx;
40600b57cec5SDimitry Andric   const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
40610b57cec5SDimitry Andric   const bool CheckAgainstPointer;
40620b57cec5SDimitry Andric 
40630b57cec5SDimitry Andric   CXXCatchStmt *FoundHandler;
40640b57cec5SDimitry Andric   CanQualType FoundHandlerType;
40650b57cec5SDimitry Andric 
40660b57cec5SDimitry Andric public:
40670b57cec5SDimitry Andric   CatchTypePublicBases(
40680b57cec5SDimitry Andric       ASTContext &Ctx,
40690b57cec5SDimitry Andric       const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
40700b57cec5SDimitry Andric       : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
40710b57cec5SDimitry Andric         FoundHandler(nullptr) {}
40720b57cec5SDimitry Andric 
40730b57cec5SDimitry Andric   CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
40740b57cec5SDimitry Andric   CanQualType getFoundHandlerType() const { return FoundHandlerType; }
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric   bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
40770b57cec5SDimitry Andric     if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
40780b57cec5SDimitry Andric       CatchHandlerType Check(S->getType(), CheckAgainstPointer);
40790b57cec5SDimitry Andric       const auto &M = TypesToCheck;
40800b57cec5SDimitry Andric       auto I = M.find(Check);
40810b57cec5SDimitry Andric       if (I != M.end()) {
40820b57cec5SDimitry Andric         FoundHandler = I->second;
40830b57cec5SDimitry Andric         FoundHandlerType = Ctx.getCanonicalType(S->getType());
40840b57cec5SDimitry Andric         return true;
40850b57cec5SDimitry Andric       }
40860b57cec5SDimitry Andric     }
40870b57cec5SDimitry Andric     return false;
40880b57cec5SDimitry Andric   }
40890b57cec5SDimitry Andric };
40900b57cec5SDimitry Andric }
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
40930b57cec5SDimitry Andric /// handlers and creates a try statement from them.
40940b57cec5SDimitry Andric StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
40950b57cec5SDimitry Andric                                   ArrayRef<Stmt *> Handlers) {
40960b57cec5SDimitry Andric   // Don't report an error if 'try' is used in system headers.
40970b57cec5SDimitry Andric   if (!getLangOpts().CXXExceptions &&
40980b57cec5SDimitry Andric       !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
40990b57cec5SDimitry Andric     // Delay error emission for the OpenMP device code.
41000b57cec5SDimitry Andric     targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
41010b57cec5SDimitry Andric   }
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   // Exceptions aren't allowed in CUDA device code.
41040b57cec5SDimitry Andric   if (getLangOpts().CUDA)
41050b57cec5SDimitry Andric     CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
41060b57cec5SDimitry Andric         << "try" << CurrentCUDATarget();
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
41090b57cec5SDimitry Andric     Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
41100b57cec5SDimitry Andric 
41110b57cec5SDimitry Andric   sema::FunctionScopeInfo *FSI = getCurFunction();
41120b57cec5SDimitry Andric 
41130b57cec5SDimitry Andric   // C++ try is incompatible with SEH __try.
41140b57cec5SDimitry Andric   if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
41150b57cec5SDimitry Andric     Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
41160b57cec5SDimitry Andric     Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
41170b57cec5SDimitry Andric   }
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   const unsigned NumHandlers = Handlers.size();
41200b57cec5SDimitry Andric   assert(!Handlers.empty() &&
41210b57cec5SDimitry Andric          "The parser shouldn't call this if there are no handlers.");
41220b57cec5SDimitry Andric 
41230b57cec5SDimitry Andric   llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
41240b57cec5SDimitry Andric   for (unsigned i = 0; i < NumHandlers; ++i) {
41250b57cec5SDimitry Andric     CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
41260b57cec5SDimitry Andric 
41270b57cec5SDimitry Andric     // Diagnose when the handler is a catch-all handler, but it isn't the last
41280b57cec5SDimitry Andric     // handler for the try block. [except.handle]p5. Also, skip exception
41290b57cec5SDimitry Andric     // declarations that are invalid, since we can't usefully report on them.
41300b57cec5SDimitry Andric     if (!H->getExceptionDecl()) {
41310b57cec5SDimitry Andric       if (i < NumHandlers - 1)
41320b57cec5SDimitry Andric         return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
41330b57cec5SDimitry Andric       continue;
41340b57cec5SDimitry Andric     } else if (H->getExceptionDecl()->isInvalidDecl())
41350b57cec5SDimitry Andric       continue;
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric     // Walk the type hierarchy to diagnose when this type has already been
41380b57cec5SDimitry Andric     // handled (duplication), or cannot be handled (derivation inversion). We
41390b57cec5SDimitry Andric     // ignore top-level cv-qualifiers, per [except.handle]p3
41400b57cec5SDimitry Andric     CatchHandlerType HandlerCHT =
41410b57cec5SDimitry Andric         (QualType)Context.getCanonicalType(H->getCaughtType());
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric     // We can ignore whether the type is a reference or a pointer; we need the
41440b57cec5SDimitry Andric     // underlying declaration type in order to get at the underlying record
41450b57cec5SDimitry Andric     // decl, if there is one.
41460b57cec5SDimitry Andric     QualType Underlying = HandlerCHT.underlying();
41470b57cec5SDimitry Andric     if (auto *RD = Underlying->getAsCXXRecordDecl()) {
41480b57cec5SDimitry Andric       if (!RD->hasDefinition())
41490b57cec5SDimitry Andric         continue;
41500b57cec5SDimitry Andric       // Check that none of the public, unambiguous base classes are in the
41510b57cec5SDimitry Andric       // map ([except.handle]p1). Give the base classes the same pointer
41520b57cec5SDimitry Andric       // qualification as the original type we are basing off of. This allows
41530b57cec5SDimitry Andric       // comparison against the handler type using the same top-level pointer
41540b57cec5SDimitry Andric       // as the original type.
41550b57cec5SDimitry Andric       CXXBasePaths Paths;
41560b57cec5SDimitry Andric       Paths.setOrigin(RD);
41570b57cec5SDimitry Andric       CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
41580b57cec5SDimitry Andric       if (RD->lookupInBases(CTPB, Paths)) {
41590b57cec5SDimitry Andric         const CXXCatchStmt *Problem = CTPB.getFoundHandler();
41600b57cec5SDimitry Andric         if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
41610b57cec5SDimitry Andric           Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
41620b57cec5SDimitry Andric                diag::warn_exception_caught_by_earlier_handler)
41630b57cec5SDimitry Andric               << H->getCaughtType();
41640b57cec5SDimitry Andric           Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
41650b57cec5SDimitry Andric                 diag::note_previous_exception_handler)
41660b57cec5SDimitry Andric               << Problem->getCaughtType();
41670b57cec5SDimitry Andric         }
41680b57cec5SDimitry Andric       }
41690b57cec5SDimitry Andric     }
41700b57cec5SDimitry Andric 
41710b57cec5SDimitry Andric     // Add the type the list of ones we have handled; diagnose if we've already
41720b57cec5SDimitry Andric     // handled it.
41730b57cec5SDimitry Andric     auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
41740b57cec5SDimitry Andric     if (!R.second) {
41750b57cec5SDimitry Andric       const CXXCatchStmt *Problem = R.first->second;
41760b57cec5SDimitry Andric       Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
41770b57cec5SDimitry Andric            diag::warn_exception_caught_by_earlier_handler)
41780b57cec5SDimitry Andric           << H->getCaughtType();
41790b57cec5SDimitry Andric       Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
41800b57cec5SDimitry Andric            diag::note_previous_exception_handler)
41810b57cec5SDimitry Andric           << Problem->getCaughtType();
41820b57cec5SDimitry Andric     }
41830b57cec5SDimitry Andric   }
41840b57cec5SDimitry Andric 
41850b57cec5SDimitry Andric   FSI->setHasCXXTry(TryLoc);
41860b57cec5SDimitry Andric 
41870b57cec5SDimitry Andric   return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
41880b57cec5SDimitry Andric }
41890b57cec5SDimitry Andric 
41900b57cec5SDimitry Andric StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
41910b57cec5SDimitry Andric                                   Stmt *TryBlock, Stmt *Handler) {
41920b57cec5SDimitry Andric   assert(TryBlock && Handler);
41930b57cec5SDimitry Andric 
41940b57cec5SDimitry Andric   sema::FunctionScopeInfo *FSI = getCurFunction();
41950b57cec5SDimitry Andric 
41960b57cec5SDimitry Andric   // SEH __try is incompatible with C++ try. Borland appears to support this,
41970b57cec5SDimitry Andric   // however.
41980b57cec5SDimitry Andric   if (!getLangOpts().Borland) {
41990b57cec5SDimitry Andric     if (FSI->FirstCXXTryLoc.isValid()) {
42000b57cec5SDimitry Andric       Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
42010b57cec5SDimitry Andric       Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
42020b57cec5SDimitry Andric     }
42030b57cec5SDimitry Andric   }
42040b57cec5SDimitry Andric 
42050b57cec5SDimitry Andric   FSI->setHasSEHTry(TryLoc);
42060b57cec5SDimitry Andric 
42070b57cec5SDimitry Andric   // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
42080b57cec5SDimitry Andric   // track if they use SEH.
42090b57cec5SDimitry Andric   DeclContext *DC = CurContext;
42100b57cec5SDimitry Andric   while (DC && !DC->isFunctionOrMethod())
42110b57cec5SDimitry Andric     DC = DC->getParent();
42120b57cec5SDimitry Andric   FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
42130b57cec5SDimitry Andric   if (FD)
42140b57cec5SDimitry Andric     FD->setUsesSEHTry(true);
42150b57cec5SDimitry Andric   else
42160b57cec5SDimitry Andric     Diag(TryLoc, diag::err_seh_try_outside_functions);
42170b57cec5SDimitry Andric 
42180b57cec5SDimitry Andric   // Reject __try on unsupported targets.
42190b57cec5SDimitry Andric   if (!Context.getTargetInfo().isSEHTrySupported())
42200b57cec5SDimitry Andric     Diag(TryLoc, diag::err_seh_try_unsupported);
42210b57cec5SDimitry Andric 
42220b57cec5SDimitry Andric   return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
42230b57cec5SDimitry Andric }
42240b57cec5SDimitry Andric 
4225480093f4SDimitry Andric StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
42260b57cec5SDimitry Andric                                      Stmt *Block) {
42270b57cec5SDimitry Andric   assert(FilterExpr && Block);
4228480093f4SDimitry Andric   QualType FTy = FilterExpr->getType();
4229480093f4SDimitry Andric   if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4230480093f4SDimitry Andric     return StmtError(
4231480093f4SDimitry Andric         Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4232480093f4SDimitry Andric         << FTy);
42330b57cec5SDimitry Andric   }
42340b57cec5SDimitry Andric   return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
42350b57cec5SDimitry Andric }
42360b57cec5SDimitry Andric 
42370b57cec5SDimitry Andric void Sema::ActOnStartSEHFinallyBlock() {
42380b57cec5SDimitry Andric   CurrentSEHFinally.push_back(CurScope);
42390b57cec5SDimitry Andric }
42400b57cec5SDimitry Andric 
42410b57cec5SDimitry Andric void Sema::ActOnAbortSEHFinallyBlock() {
42420b57cec5SDimitry Andric   CurrentSEHFinally.pop_back();
42430b57cec5SDimitry Andric }
42440b57cec5SDimitry Andric 
42450b57cec5SDimitry Andric StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
42460b57cec5SDimitry Andric   assert(Block);
42470b57cec5SDimitry Andric   CurrentSEHFinally.pop_back();
42480b57cec5SDimitry Andric   return SEHFinallyStmt::Create(Context, Loc, Block);
42490b57cec5SDimitry Andric }
42500b57cec5SDimitry Andric 
42510b57cec5SDimitry Andric StmtResult
42520b57cec5SDimitry Andric Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
42530b57cec5SDimitry Andric   Scope *SEHTryParent = CurScope;
42540b57cec5SDimitry Andric   while (SEHTryParent && !SEHTryParent->isSEHTryScope())
42550b57cec5SDimitry Andric     SEHTryParent = SEHTryParent->getParent();
42560b57cec5SDimitry Andric   if (!SEHTryParent)
42570b57cec5SDimitry Andric     return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
42580b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
42590b57cec5SDimitry Andric 
42600b57cec5SDimitry Andric   return new (Context) SEHLeaveStmt(Loc);
42610b57cec5SDimitry Andric }
42620b57cec5SDimitry Andric 
42630b57cec5SDimitry Andric StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
42640b57cec5SDimitry Andric                                             bool IsIfExists,
42650b57cec5SDimitry Andric                                             NestedNameSpecifierLoc QualifierLoc,
42660b57cec5SDimitry Andric                                             DeclarationNameInfo NameInfo,
42670b57cec5SDimitry Andric                                             Stmt *Nested)
42680b57cec5SDimitry Andric {
42690b57cec5SDimitry Andric   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
42700b57cec5SDimitry Andric                                              QualifierLoc, NameInfo,
42710b57cec5SDimitry Andric                                              cast<CompoundStmt>(Nested));
42720b57cec5SDimitry Andric }
42730b57cec5SDimitry Andric 
42740b57cec5SDimitry Andric 
42750b57cec5SDimitry Andric StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
42760b57cec5SDimitry Andric                                             bool IsIfExists,
42770b57cec5SDimitry Andric                                             CXXScopeSpec &SS,
42780b57cec5SDimitry Andric                                             UnqualifiedId &Name,
42790b57cec5SDimitry Andric                                             Stmt *Nested) {
42800b57cec5SDimitry Andric   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
42810b57cec5SDimitry Andric                                     SS.getWithLocInContext(Context),
42820b57cec5SDimitry Andric                                     GetNameFromUnqualifiedId(Name),
42830b57cec5SDimitry Andric                                     Nested);
42840b57cec5SDimitry Andric }
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric RecordDecl*
42870b57cec5SDimitry Andric Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
42880b57cec5SDimitry Andric                                    unsigned NumParams) {
42890b57cec5SDimitry Andric   DeclContext *DC = CurContext;
42900b57cec5SDimitry Andric   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
42910b57cec5SDimitry Andric     DC = DC->getParent();
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric   RecordDecl *RD = nullptr;
42940b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
42950b57cec5SDimitry Andric     RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
42960b57cec5SDimitry Andric                                /*Id=*/nullptr);
42970b57cec5SDimitry Andric   else
42980b57cec5SDimitry Andric     RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric   RD->setCapturedRecord();
43010b57cec5SDimitry Andric   DC->addDecl(RD);
43020b57cec5SDimitry Andric   RD->setImplicit();
43030b57cec5SDimitry Andric   RD->startDefinition();
43040b57cec5SDimitry Andric 
43050b57cec5SDimitry Andric   assert(NumParams > 0 && "CapturedStmt requires context parameter");
43060b57cec5SDimitry Andric   CD = CapturedDecl::Create(Context, CurContext, NumParams);
43070b57cec5SDimitry Andric   DC->addDecl(CD);
43080b57cec5SDimitry Andric   return RD;
43090b57cec5SDimitry Andric }
43100b57cec5SDimitry Andric 
43110b57cec5SDimitry Andric static bool
43120b57cec5SDimitry Andric buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
43130b57cec5SDimitry Andric                              SmallVectorImpl<CapturedStmt::Capture> &Captures,
43140b57cec5SDimitry Andric                              SmallVectorImpl<Expr *> &CaptureInits) {
43150b57cec5SDimitry Andric   for (const sema::Capture &Cap : RSI->Captures) {
43160b57cec5SDimitry Andric     if (Cap.isInvalid())
43170b57cec5SDimitry Andric       continue;
43180b57cec5SDimitry Andric 
43190b57cec5SDimitry Andric     // Form the initializer for the capture.
43200b57cec5SDimitry Andric     ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
43210b57cec5SDimitry Andric                                          RSI->CapRegionKind == CR_OpenMP);
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric     // FIXME: Bail out now if the capture is not used and the initializer has
43240b57cec5SDimitry Andric     // no side-effects.
43250b57cec5SDimitry Andric 
43260b57cec5SDimitry Andric     // Create a field for this capture.
43270b57cec5SDimitry Andric     FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
43280b57cec5SDimitry Andric 
43290b57cec5SDimitry Andric     // Add the capture to our list of captures.
43300b57cec5SDimitry Andric     if (Cap.isThisCapture()) {
43310b57cec5SDimitry Andric       Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
43320b57cec5SDimitry Andric                                                CapturedStmt::VCK_This));
43330b57cec5SDimitry Andric     } else if (Cap.isVLATypeCapture()) {
43340b57cec5SDimitry Andric       Captures.push_back(
43350b57cec5SDimitry Andric           CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
43360b57cec5SDimitry Andric     } else {
43370b57cec5SDimitry Andric       assert(Cap.isVariableCapture() && "unknown kind of capture");
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric       if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
43400b57cec5SDimitry Andric         S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
43410b57cec5SDimitry Andric 
43420b57cec5SDimitry Andric       Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
43430b57cec5SDimitry Andric                                                Cap.isReferenceCapture()
43440b57cec5SDimitry Andric                                                    ? CapturedStmt::VCK_ByRef
43450b57cec5SDimitry Andric                                                    : CapturedStmt::VCK_ByCopy,
43460b57cec5SDimitry Andric                                                Cap.getVariable()));
43470b57cec5SDimitry Andric     }
43480b57cec5SDimitry Andric     CaptureInits.push_back(Init.get());
43490b57cec5SDimitry Andric   }
43500b57cec5SDimitry Andric   return false;
43510b57cec5SDimitry Andric }
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
43540b57cec5SDimitry Andric                                     CapturedRegionKind Kind,
43550b57cec5SDimitry Andric                                     unsigned NumParams) {
43560b57cec5SDimitry Andric   CapturedDecl *CD = nullptr;
43570b57cec5SDimitry Andric   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
43580b57cec5SDimitry Andric 
43590b57cec5SDimitry Andric   // Build the context parameter
43600b57cec5SDimitry Andric   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
43610b57cec5SDimitry Andric   IdentifierInfo *ParamName = &Context.Idents.get("__context");
43620b57cec5SDimitry Andric   QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
43630b57cec5SDimitry Andric   auto *Param =
43640b57cec5SDimitry Andric       ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
43650b57cec5SDimitry Andric                                 ImplicitParamDecl::CapturedContext);
43660b57cec5SDimitry Andric   DC->addDecl(Param);
43670b57cec5SDimitry Andric 
43680b57cec5SDimitry Andric   CD->setContextParam(0, Param);
43690b57cec5SDimitry Andric 
43700b57cec5SDimitry Andric   // Enter the capturing scope for this captured region.
43710b57cec5SDimitry Andric   PushCapturedRegionScope(CurScope, CD, RD, Kind);
43720b57cec5SDimitry Andric 
43730b57cec5SDimitry Andric   if (CurScope)
43740b57cec5SDimitry Andric     PushDeclContext(CurScope, CD);
43750b57cec5SDimitry Andric   else
43760b57cec5SDimitry Andric     CurContext = CD;
43770b57cec5SDimitry Andric 
43780b57cec5SDimitry Andric   PushExpressionEvaluationContext(
43790b57cec5SDimitry Andric       ExpressionEvaluationContext::PotentiallyEvaluated);
43800b57cec5SDimitry Andric }
43810b57cec5SDimitry Andric 
43820b57cec5SDimitry Andric void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
43830b57cec5SDimitry Andric                                     CapturedRegionKind Kind,
4384a7dea167SDimitry Andric                                     ArrayRef<CapturedParamNameType> Params,
4385a7dea167SDimitry Andric                                     unsigned OpenMPCaptureLevel) {
43860b57cec5SDimitry Andric   CapturedDecl *CD = nullptr;
43870b57cec5SDimitry Andric   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
43880b57cec5SDimitry Andric 
43890b57cec5SDimitry Andric   // Build the context parameter
43900b57cec5SDimitry Andric   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
43910b57cec5SDimitry Andric   bool ContextIsFound = false;
43920b57cec5SDimitry Andric   unsigned ParamNum = 0;
43930b57cec5SDimitry Andric   for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
43940b57cec5SDimitry Andric                                                  E = Params.end();
43950b57cec5SDimitry Andric        I != E; ++I, ++ParamNum) {
43960b57cec5SDimitry Andric     if (I->second.isNull()) {
43970b57cec5SDimitry Andric       assert(!ContextIsFound &&
43980b57cec5SDimitry Andric              "null type has been found already for '__context' parameter");
43990b57cec5SDimitry Andric       IdentifierInfo *ParamName = &Context.Idents.get("__context");
44000b57cec5SDimitry Andric       QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
44010b57cec5SDimitry Andric                                .withConst()
44020b57cec5SDimitry Andric                                .withRestrict();
44030b57cec5SDimitry Andric       auto *Param =
44040b57cec5SDimitry Andric           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
44050b57cec5SDimitry Andric                                     ImplicitParamDecl::CapturedContext);
44060b57cec5SDimitry Andric       DC->addDecl(Param);
44070b57cec5SDimitry Andric       CD->setContextParam(ParamNum, Param);
44080b57cec5SDimitry Andric       ContextIsFound = true;
44090b57cec5SDimitry Andric     } else {
44100b57cec5SDimitry Andric       IdentifierInfo *ParamName = &Context.Idents.get(I->first);
44110b57cec5SDimitry Andric       auto *Param =
44120b57cec5SDimitry Andric           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
44130b57cec5SDimitry Andric                                     ImplicitParamDecl::CapturedContext);
44140b57cec5SDimitry Andric       DC->addDecl(Param);
44150b57cec5SDimitry Andric       CD->setParam(ParamNum, Param);
44160b57cec5SDimitry Andric     }
44170b57cec5SDimitry Andric   }
44180b57cec5SDimitry Andric   assert(ContextIsFound && "no null type for '__context' parameter");
44190b57cec5SDimitry Andric   if (!ContextIsFound) {
44200b57cec5SDimitry Andric     // Add __context implicitly if it is not specified.
44210b57cec5SDimitry Andric     IdentifierInfo *ParamName = &Context.Idents.get("__context");
44220b57cec5SDimitry Andric     QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
44230b57cec5SDimitry Andric     auto *Param =
44240b57cec5SDimitry Andric         ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
44250b57cec5SDimitry Andric                                   ImplicitParamDecl::CapturedContext);
44260b57cec5SDimitry Andric     DC->addDecl(Param);
44270b57cec5SDimitry Andric     CD->setContextParam(ParamNum, Param);
44280b57cec5SDimitry Andric   }
44290b57cec5SDimitry Andric   // Enter the capturing scope for this captured region.
4430a7dea167SDimitry Andric   PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
44310b57cec5SDimitry Andric 
44320b57cec5SDimitry Andric   if (CurScope)
44330b57cec5SDimitry Andric     PushDeclContext(CurScope, CD);
44340b57cec5SDimitry Andric   else
44350b57cec5SDimitry Andric     CurContext = CD;
44360b57cec5SDimitry Andric 
44370b57cec5SDimitry Andric   PushExpressionEvaluationContext(
44380b57cec5SDimitry Andric       ExpressionEvaluationContext::PotentiallyEvaluated);
44390b57cec5SDimitry Andric }
44400b57cec5SDimitry Andric 
44410b57cec5SDimitry Andric void Sema::ActOnCapturedRegionError() {
44420b57cec5SDimitry Andric   DiscardCleanupsInEvaluationContext();
44430b57cec5SDimitry Andric   PopExpressionEvaluationContext();
44440b57cec5SDimitry Andric   PopDeclContext();
44450b57cec5SDimitry Andric   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
44460b57cec5SDimitry Andric   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
44470b57cec5SDimitry Andric 
44480b57cec5SDimitry Andric   RecordDecl *Record = RSI->TheRecordDecl;
44490b57cec5SDimitry Andric   Record->setInvalidDecl();
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric   SmallVector<Decl*, 4> Fields(Record->fields());
44520b57cec5SDimitry Andric   ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
44530b57cec5SDimitry Andric               SourceLocation(), SourceLocation(), ParsedAttributesView());
44540b57cec5SDimitry Andric }
44550b57cec5SDimitry Andric 
44560b57cec5SDimitry Andric StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
44570b57cec5SDimitry Andric   // Leave the captured scope before we start creating captures in the
44580b57cec5SDimitry Andric   // enclosing scope.
44590b57cec5SDimitry Andric   DiscardCleanupsInEvaluationContext();
44600b57cec5SDimitry Andric   PopExpressionEvaluationContext();
44610b57cec5SDimitry Andric   PopDeclContext();
44620b57cec5SDimitry Andric   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
44630b57cec5SDimitry Andric   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
44640b57cec5SDimitry Andric 
44650b57cec5SDimitry Andric   SmallVector<CapturedStmt::Capture, 4> Captures;
44660b57cec5SDimitry Andric   SmallVector<Expr *, 4> CaptureInits;
44670b57cec5SDimitry Andric   if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
44680b57cec5SDimitry Andric     return StmtError();
44690b57cec5SDimitry Andric 
44700b57cec5SDimitry Andric   CapturedDecl *CD = RSI->TheCapturedDecl;
44710b57cec5SDimitry Andric   RecordDecl *RD = RSI->TheRecordDecl;
44720b57cec5SDimitry Andric 
44730b57cec5SDimitry Andric   CapturedStmt *Res = CapturedStmt::Create(
44740b57cec5SDimitry Andric       getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
44750b57cec5SDimitry Andric       Captures, CaptureInits, CD, RD);
44760b57cec5SDimitry Andric 
44770b57cec5SDimitry Andric   CD->setBody(Res->getCapturedStmt());
44780b57cec5SDimitry Andric   RD->completeDefinition();
44790b57cec5SDimitry Andric 
44800b57cec5SDimitry Andric   return Res;
44810b57cec5SDimitry Andric }
4482