xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaStmt.cpp (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for statements.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/IgnoreExpr.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Ownership.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 
43 using namespace clang;
44 using namespace sema;
45 
46 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
47   if (FE.isInvalid())
48     return StmtError();
49 
50   FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
51   if (FE.isInvalid())
52     return StmtError();
53 
54   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
55   // void expression for its side effects.  Conversion to void allows any
56   // operand, even incomplete types.
57 
58   // Same thing in for stmt first clause (when expr) and third clause.
59   return StmtResult(FE.getAs<Stmt>());
60 }
61 
62 
63 StmtResult Sema::ActOnExprStmtError() {
64   DiscardCleanupsInEvaluationContext();
65   return StmtError();
66 }
67 
68 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
69                                bool HasLeadingEmptyMacro) {
70   return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
71 }
72 
73 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
74                                SourceLocation EndLoc) {
75   DeclGroupRef DG = dg.get();
76 
77   // If we have an invalid decl, just return an error.
78   if (DG.isNull()) return StmtError();
79 
80   return new (Context) DeclStmt(DG, StartLoc, EndLoc);
81 }
82 
83 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
84   DeclGroupRef DG = dg.get();
85 
86   // If we don't have a declaration, or we have an invalid declaration,
87   // just return.
88   if (DG.isNull() || !DG.isSingleDecl())
89     return;
90 
91   Decl *decl = DG.getSingleDecl();
92   if (!decl || decl->isInvalidDecl())
93     return;
94 
95   // Only variable declarations are permitted.
96   VarDecl *var = dyn_cast<VarDecl>(decl);
97   if (!var) {
98     Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
99     decl->setInvalidDecl();
100     return;
101   }
102 
103   // foreach variables are never actually initialized in the way that
104   // the parser came up with.
105   var->setInit(nullptr);
106 
107   // In ARC, we don't need to retain the iteration variable of a fast
108   // enumeration loop.  Rather than actually trying to catch that
109   // during declaration processing, we remove the consequences here.
110   if (getLangOpts().ObjCAutoRefCount) {
111     QualType type = var->getType();
112 
113     // Only do this if we inferred the lifetime.  Inferred lifetime
114     // will show up as a local qualifier because explicit lifetime
115     // should have shown up as an AttributedType instead.
116     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
117       // Add 'const' and mark the variable as pseudo-strong.
118       var->setType(type.withConst());
119       var->setARCPseudoStrong(true);
120     }
121   }
122 }
123 
124 /// Diagnose unused comparisons, both builtin and overloaded operators.
125 /// For '==' and '!=', suggest fixits for '=' or '|='.
126 ///
127 /// Adding a cast to void (or other expression wrappers) will prevent the
128 /// warning from firing.
129 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
130   SourceLocation Loc;
131   bool CanAssign;
132   enum { Equality, Inequality, Relational, ThreeWay } Kind;
133 
134   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
135     if (!Op->isComparisonOp())
136       return false;
137 
138     if (Op->getOpcode() == BO_EQ)
139       Kind = Equality;
140     else if (Op->getOpcode() == BO_NE)
141       Kind = Inequality;
142     else if (Op->getOpcode() == BO_Cmp)
143       Kind = ThreeWay;
144     else {
145       assert(Op->isRelationalOp());
146       Kind = Relational;
147     }
148     Loc = Op->getOperatorLoc();
149     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
150   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
151     switch (Op->getOperator()) {
152     case OO_EqualEqual:
153       Kind = Equality;
154       break;
155     case OO_ExclaimEqual:
156       Kind = Inequality;
157       break;
158     case OO_Less:
159     case OO_Greater:
160     case OO_GreaterEqual:
161     case OO_LessEqual:
162       Kind = Relational;
163       break;
164     case OO_Spaceship:
165       Kind = ThreeWay;
166       break;
167     default:
168       return false;
169     }
170 
171     Loc = Op->getOperatorLoc();
172     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
173   } else {
174     // Not a typo-prone comparison.
175     return false;
176   }
177 
178   // Suppress warnings when the operator, suspicious as it may be, comes from
179   // a macro expansion.
180   if (S.SourceMgr.isMacroBodyExpansion(Loc))
181     return false;
182 
183   S.Diag(Loc, diag::warn_unused_comparison)
184     << (unsigned)Kind << E->getSourceRange();
185 
186   // If the LHS is a plausible entity to assign to, provide a fixit hint to
187   // correct common typos.
188   if (CanAssign) {
189     if (Kind == Inequality)
190       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191         << FixItHint::CreateReplacement(Loc, "|=");
192     else if (Kind == Equality)
193       S.Diag(Loc, diag::note_equality_comparison_to_assign)
194         << FixItHint::CreateReplacement(Loc, "=");
195   }
196 
197   return true;
198 }
199 
200 static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
201                               SourceLocation Loc, SourceRange R1,
202                               SourceRange R2, bool IsCtor) {
203   if (!A)
204     return false;
205   StringRef Msg = A->getMessage();
206 
207   if (Msg.empty()) {
208     if (IsCtor)
209       return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
210     return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
211   }
212 
213   if (IsCtor)
214     return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
215                                                           << R2;
216   return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
217 }
218 
219 void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
220   if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
221     return DiagnoseUnusedExprResult(Label->getSubStmt(), DiagID);
222 
223   const Expr *E = dyn_cast_or_null<Expr>(S);
224   if (!E)
225     return;
226 
227   // If we are in an unevaluated expression context, then there can be no unused
228   // results because the results aren't expected to be used in the first place.
229   if (isUnevaluatedContext())
230     return;
231 
232   SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
233   // In most cases, we don't want to warn if the expression is written in a
234   // macro body, or if the macro comes from a system header. If the offending
235   // expression is a call to a function with the warn_unused_result attribute,
236   // we warn no matter the location. Because of the order in which the various
237   // checks need to happen, we factor out the macro-related test here.
238   bool ShouldSuppress =
239       SourceMgr.isMacroBodyExpansion(ExprLoc) ||
240       SourceMgr.isInSystemMacro(ExprLoc);
241 
242   const Expr *WarnExpr;
243   SourceLocation Loc;
244   SourceRange R1, R2;
245   if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
246     return;
247 
248   // If this is a GNU statement expression expanded from a macro, it is probably
249   // unused because it is a function-like macro that can be used as either an
250   // expression or statement.  Don't warn, because it is almost certainly a
251   // false positive.
252   if (isa<StmtExpr>(E) && Loc.isMacroID())
253     return;
254 
255   // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
256   // That macro is frequently used to suppress "unused parameter" warnings,
257   // but its implementation makes clang's -Wunused-value fire.  Prevent this.
258   if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
259     SourceLocation SpellLoc = Loc;
260     if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
261       return;
262   }
263 
264   // Okay, we have an unused result.  Depending on what the base expression is,
265   // we might want to make a more specific diagnostic.  Check for one of these
266   // cases now.
267   if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
268     E = Temps->getSubExpr();
269   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
270     E = TempExpr->getSubExpr();
271 
272   if (DiagnoseUnusedComparison(*this, E))
273     return;
274 
275   E = WarnExpr;
276   if (const auto *Cast = dyn_cast<CastExpr>(E))
277     if (Cast->getCastKind() == CK_NoOp ||
278         Cast->getCastKind() == CK_ConstructorConversion)
279       E = Cast->getSubExpr()->IgnoreImpCasts();
280 
281   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
282     if (E->getType()->isVoidType())
283       return;
284 
285     if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
286                                      CE->getUnusedResultAttr(Context)),
287                           Loc, R1, R2, /*isCtor=*/false))
288       return;
289 
290     // If the callee has attribute pure, const, or warn_unused_result, warn with
291     // a more specific message to make it clear what is happening. If the call
292     // is written in a macro body, only warn if it has the warn_unused_result
293     // attribute.
294     if (const Decl *FD = CE->getCalleeDecl()) {
295       if (ShouldSuppress)
296         return;
297       if (FD->hasAttr<PureAttr>()) {
298         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
299         return;
300       }
301       if (FD->hasAttr<ConstAttr>()) {
302         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
303         return;
304       }
305     }
306   } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
307     if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
308       const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
309       A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
310       if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
311         return;
312     }
313   } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
314     if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
315 
316       if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
317                             R2, /*isCtor=*/false))
318         return;
319     }
320   } else if (ShouldSuppress)
321     return;
322 
323   E = WarnExpr;
324   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
325     if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
326       Diag(Loc, diag::err_arc_unused_init_message) << R1;
327       return;
328     }
329     const ObjCMethodDecl *MD = ME->getMethodDecl();
330     if (MD) {
331       if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
332                             R2, /*isCtor=*/false))
333         return;
334     }
335   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
336     const Expr *Source = POE->getSyntacticForm();
337     // Handle the actually selected call of an OpenMP specialized call.
338     if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
339         POE->getNumSemanticExprs() == 1 &&
340         isa<CallExpr>(POE->getSemanticExpr(0)))
341       return DiagnoseUnusedExprResult(POE->getSemanticExpr(0), DiagID);
342     if (isa<ObjCSubscriptRefExpr>(Source))
343       DiagID = diag::warn_unused_container_subscript_expr;
344     else if (isa<ObjCPropertyRefExpr>(Source))
345       DiagID = diag::warn_unused_property_expr;
346   } else if (const CXXFunctionalCastExpr *FC
347                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
348     const Expr *E = FC->getSubExpr();
349     if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
350       E = TE->getSubExpr();
351     if (isa<CXXTemporaryObjectExpr>(E))
352       return;
353     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
354       if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
355         if (!RD->getAttr<WarnUnusedAttr>())
356           return;
357   }
358   // Diagnose "(void*) blah" as a typo for "(void) blah".
359   else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
360     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
361     QualType T = TI->getType();
362 
363     // We really do want to use the non-canonical type here.
364     if (T == Context.VoidPtrTy) {
365       PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
366 
367       Diag(Loc, diag::warn_unused_voidptr)
368         << FixItHint::CreateRemoval(TL.getStarLoc());
369       return;
370     }
371   }
372 
373   // Tell the user to assign it into a variable to force a volatile load if this
374   // isn't an array.
375   if (E->isGLValue() && E->getType().isVolatileQualified() &&
376       !E->getType()->isArrayType()) {
377     Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
378     return;
379   }
380 
381   // Do not diagnose use of a comma operator in a SFINAE context because the
382   // type of the left operand could be used for SFINAE, so technically it is
383   // *used*.
384   if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
385     DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt,
386                     PDiag(DiagID) << R1 << R2);
387 }
388 
389 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
390   PushCompoundScope(IsStmtExpr);
391 }
392 
393 void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
394   if (getCurFPFeatures().isFPConstrained()) {
395     FunctionScopeInfo *FSI = getCurFunction();
396     assert(FSI);
397     FSI->setUsesFPIntrin();
398   }
399 }
400 
401 void Sema::ActOnFinishOfCompoundStmt() {
402   PopCompoundScope();
403 }
404 
405 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
406   return getCurFunction()->CompoundScopes.back();
407 }
408 
409 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
410                                    ArrayRef<Stmt *> Elts, bool isStmtExpr) {
411   const unsigned NumElts = Elts.size();
412 
413   // If we're in C mode, check that we don't have any decls after stmts.  If
414   // so, emit an extension diagnostic in C89 and potentially a warning in later
415   // versions.
416   const unsigned MixedDeclsCodeID = getLangOpts().C99
417                                         ? diag::warn_mixed_decls_code
418                                         : diag::ext_mixed_decls_code;
419   if (!getLangOpts().CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) {
420     // Note that __extension__ can be around a decl.
421     unsigned i = 0;
422     // Skip over all declarations.
423     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
424       /*empty*/;
425 
426     // We found the end of the list or a statement.  Scan for another declstmt.
427     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
428       /*empty*/;
429 
430     if (i != NumElts) {
431       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
432       Diag(D->getLocation(), MixedDeclsCodeID);
433     }
434   }
435 
436   // Check for suspicious empty body (null statement) in `for' and `while'
437   // statements.  Don't do anything for template instantiations, this just adds
438   // noise.
439   if (NumElts != 0 && !CurrentInstantiationScope &&
440       getCurCompoundScope().HasEmptyLoopBodies) {
441     for (unsigned i = 0; i != NumElts - 1; ++i)
442       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
443   }
444 
445   // Calculate difference between FP options in this compound statement and in
446   // the enclosing one. If this is a function body, take the difference against
447   // default options. In this case the difference will indicate options that are
448   // changed upon entry to the statement.
449   FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
450                       ? FPOptions(getLangOpts())
451                       : getCurCompoundScope().InitialFPFeatures;
452   FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(FPO);
453 
454   return CompoundStmt::Create(Context, Elts, FPDiff, L, R);
455 }
456 
457 ExprResult
458 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
459   if (!Val.get())
460     return Val;
461 
462   if (DiagnoseUnexpandedParameterPack(Val.get()))
463     return ExprError();
464 
465   // If we're not inside a switch, let the 'case' statement handling diagnose
466   // this. Just clean up after the expression as best we can.
467   if (getCurFunction()->SwitchStack.empty())
468     return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
469                                getLangOpts().CPlusPlus11);
470 
471   Expr *CondExpr =
472       getCurFunction()->SwitchStack.back().getPointer()->getCond();
473   if (!CondExpr)
474     return ExprError();
475   QualType CondType = CondExpr->getType();
476 
477   auto CheckAndFinish = [&](Expr *E) {
478     if (CondType->isDependentType() || E->isTypeDependent())
479       return ExprResult(E);
480 
481     if (getLangOpts().CPlusPlus11) {
482       // C++11 [stmt.switch]p2: the constant-expression shall be a converted
483       // constant expression of the promoted type of the switch condition.
484       llvm::APSInt TempVal;
485       return CheckConvertedConstantExpression(E, CondType, TempVal,
486                                               CCEK_CaseValue);
487     }
488 
489     ExprResult ER = E;
490     if (!E->isValueDependent())
491       ER = VerifyIntegerConstantExpression(E, AllowFold);
492     if (!ER.isInvalid())
493       ER = DefaultLvalueConversion(ER.get());
494     if (!ER.isInvalid())
495       ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
496     if (!ER.isInvalid())
497       ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
498     return ER;
499   };
500 
501   ExprResult Converted = CorrectDelayedTyposInExpr(
502       Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
503       CheckAndFinish);
504   if (Converted.get() == Val.get())
505     Converted = CheckAndFinish(Val.get());
506   return Converted;
507 }
508 
509 StmtResult
510 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
511                     SourceLocation DotDotDotLoc, ExprResult RHSVal,
512                     SourceLocation ColonLoc) {
513   assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
514   assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
515                                    : RHSVal.isInvalid() || RHSVal.get()) &&
516          "missing RHS value");
517 
518   if (getCurFunction()->SwitchStack.empty()) {
519     Diag(CaseLoc, diag::err_case_not_in_switch);
520     return StmtError();
521   }
522 
523   if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
524     getCurFunction()->SwitchStack.back().setInt(true);
525     return StmtError();
526   }
527 
528   auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
529                               CaseLoc, DotDotDotLoc, ColonLoc);
530   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
531   return CS;
532 }
533 
534 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
535 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
536   cast<CaseStmt>(S)->setSubStmt(SubStmt);
537 }
538 
539 StmtResult
540 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
541                        Stmt *SubStmt, Scope *CurScope) {
542   if (getCurFunction()->SwitchStack.empty()) {
543     Diag(DefaultLoc, diag::err_default_not_in_switch);
544     return SubStmt;
545   }
546 
547   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
548   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
549   return DS;
550 }
551 
552 StmtResult
553 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
554                      SourceLocation ColonLoc, Stmt *SubStmt) {
555   // If the label was multiply defined, reject it now.
556   if (TheDecl->getStmt()) {
557     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
558     Diag(TheDecl->getLocation(), diag::note_previous_definition);
559     return SubStmt;
560   }
561 
562   ReservedIdentifierStatus Status = TheDecl->isReserved(getLangOpts());
563   if (isReservedInAllContexts(Status) &&
564       !Context.getSourceManager().isInSystemHeader(IdentLoc))
565     Diag(IdentLoc, diag::warn_reserved_extern_symbol)
566         << TheDecl << static_cast<int>(Status);
567 
568   // Otherwise, things are good.  Fill in the declaration and return it.
569   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
570   TheDecl->setStmt(LS);
571   if (!TheDecl->isGnuLocal()) {
572     TheDecl->setLocStart(IdentLoc);
573     if (!TheDecl->isMSAsmLabel()) {
574       // Don't update the location of MS ASM labels.  These will result in
575       // a diagnostic, and changing the location here will mess that up.
576       TheDecl->setLocation(IdentLoc);
577     }
578   }
579   return LS;
580 }
581 
582 StmtResult Sema::BuildAttributedStmt(SourceLocation AttrsLoc,
583                                      ArrayRef<const Attr *> Attrs,
584                                      Stmt *SubStmt) {
585   // FIXME: this code should move when a planned refactoring around statement
586   // attributes lands.
587   for (const auto *A : Attrs) {
588     if (A->getKind() == attr::MustTail) {
589       if (!checkAndRewriteMustTailAttr(SubStmt, *A)) {
590         return SubStmt;
591       }
592       setFunctionHasMustTail();
593     }
594   }
595 
596   return AttributedStmt::Create(Context, AttrsLoc, Attrs, SubStmt);
597 }
598 
599 StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs,
600                                      Stmt *SubStmt) {
601   SmallVector<const Attr *, 1> SemanticAttrs;
602   ProcessStmtAttributes(SubStmt, Attrs, SemanticAttrs);
603   if (!SemanticAttrs.empty())
604     return BuildAttributedStmt(Attrs.Range.getBegin(), SemanticAttrs, SubStmt);
605   // If none of the attributes applied, that's fine, we can recover by
606   // returning the substatement directly instead of making an AttributedStmt
607   // with no attributes on it.
608   return SubStmt;
609 }
610 
611 bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) {
612   ReturnStmt *R = cast<ReturnStmt>(St);
613   Expr *E = R->getRetValue();
614 
615   if (CurContext->isDependentContext() || (E && E->isInstantiationDependent()))
616     // We have to suspend our check until template instantiation time.
617     return true;
618 
619   if (!checkMustTailAttr(St, MTA))
620     return false;
621 
622   // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
623   // Currently it does not skip implicit constructors in an initialization
624   // context.
625   auto IgnoreImplicitAsWritten = [](Expr *E) -> Expr * {
626     return IgnoreExprNodes(E, IgnoreImplicitAsWrittenSingleStep,
627                            IgnoreElidableImplicitConstructorSingleStep);
628   };
629 
630   // Now that we have verified that 'musttail' is valid here, rewrite the
631   // return value to remove all implicit nodes, but retain parentheses.
632   R->setRetValue(IgnoreImplicitAsWritten(E));
633   return true;
634 }
635 
636 bool Sema::checkMustTailAttr(const Stmt *St, const Attr &MTA) {
637   assert(!CurContext->isDependentContext() &&
638          "musttail cannot be checked from a dependent context");
639 
640   // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
641   auto IgnoreParenImplicitAsWritten = [](const Expr *E) -> const Expr * {
642     return IgnoreExprNodes(const_cast<Expr *>(E), IgnoreParensSingleStep,
643                            IgnoreImplicitAsWrittenSingleStep,
644                            IgnoreElidableImplicitConstructorSingleStep);
645   };
646 
647   const Expr *E = cast<ReturnStmt>(St)->getRetValue();
648   const auto *CE = dyn_cast_or_null<CallExpr>(IgnoreParenImplicitAsWritten(E));
649 
650   if (!CE) {
651     Diag(St->getBeginLoc(), diag::err_musttail_needs_call) << &MTA;
652     return false;
653   }
654 
655   if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) {
656     if (EWC->cleanupsHaveSideEffects()) {
657       Diag(St->getBeginLoc(), diag::err_musttail_needs_trivial_args) << &MTA;
658       return false;
659     }
660   }
661 
662   // We need to determine the full function type (including "this" type, if any)
663   // for both caller and callee.
664   struct FuncType {
665     enum {
666       ft_non_member,
667       ft_static_member,
668       ft_non_static_member,
669       ft_pointer_to_member,
670     } MemberType = ft_non_member;
671 
672     QualType This;
673     const FunctionProtoType *Func;
674     const CXXMethodDecl *Method = nullptr;
675   } CallerType, CalleeType;
676 
677   auto GetMethodType = [this, St, MTA](const CXXMethodDecl *CMD, FuncType &Type,
678                                        bool IsCallee) -> bool {
679     if (isa<CXXConstructorDecl, CXXDestructorDecl>(CMD)) {
680       Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
681           << IsCallee << isa<CXXDestructorDecl>(CMD);
682       if (IsCallee)
683         Diag(CMD->getBeginLoc(), diag::note_musttail_structors_forbidden)
684             << isa<CXXDestructorDecl>(CMD);
685       Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
686       return false;
687     }
688     if (CMD->isStatic())
689       Type.MemberType = FuncType::ft_static_member;
690     else {
691       Type.This = CMD->getThisType()->getPointeeType();
692       Type.MemberType = FuncType::ft_non_static_member;
693     }
694     Type.Func = CMD->getType()->castAs<FunctionProtoType>();
695     return true;
696   };
697 
698   const auto *CallerDecl = dyn_cast<FunctionDecl>(CurContext);
699 
700   // Find caller function signature.
701   if (!CallerDecl) {
702     int ContextType;
703     if (isa<BlockDecl>(CurContext))
704       ContextType = 0;
705     else if (isa<ObjCMethodDecl>(CurContext))
706       ContextType = 1;
707     else
708       ContextType = 2;
709     Diag(St->getBeginLoc(), diag::err_musttail_forbidden_from_this_context)
710         << &MTA << ContextType;
711     return false;
712   } else if (const auto *CMD = dyn_cast<CXXMethodDecl>(CurContext)) {
713     // Caller is a class/struct method.
714     if (!GetMethodType(CMD, CallerType, false))
715       return false;
716   } else {
717     // Caller is a non-method function.
718     CallerType.Func = CallerDecl->getType()->getAs<FunctionProtoType>();
719   }
720 
721   const Expr *CalleeExpr = CE->getCallee()->IgnoreParens();
722   const auto *CalleeBinOp = dyn_cast<BinaryOperator>(CalleeExpr);
723   SourceLocation CalleeLoc = CE->getCalleeDecl()
724                                  ? CE->getCalleeDecl()->getBeginLoc()
725                                  : St->getBeginLoc();
726 
727   // Find callee function signature.
728   if (const CXXMethodDecl *CMD =
729           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) {
730     // Call is: obj.method(), obj->method(), functor(), etc.
731     if (!GetMethodType(CMD, CalleeType, true))
732       return false;
733   } else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) {
734     // Call is: obj->*method_ptr or obj.*method_ptr
735     const auto *MPT =
736         CalleeBinOp->getRHS()->getType()->castAs<MemberPointerType>();
737     CalleeType.This = QualType(MPT->getClass(), 0);
738     CalleeType.Func = MPT->getPointeeType()->castAs<FunctionProtoType>();
739     CalleeType.MemberType = FuncType::ft_pointer_to_member;
740   } else if (isa<CXXPseudoDestructorExpr>(CalleeExpr)) {
741     Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
742         << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
743     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
744     return false;
745   } else {
746     // Non-method function.
747     CalleeType.Func =
748         CalleeExpr->getType()->getPointeeType()->getAs<FunctionProtoType>();
749   }
750 
751   // Both caller and callee must have a prototype (no K&R declarations).
752   if (!CalleeType.Func || !CallerType.Func) {
753     Diag(St->getBeginLoc(), diag::err_musttail_needs_prototype) << &MTA;
754     if (!CalleeType.Func && CE->getDirectCallee()) {
755       Diag(CE->getDirectCallee()->getBeginLoc(),
756            diag::note_musttail_fix_non_prototype);
757     }
758     if (!CallerType.Func)
759       Diag(CallerDecl->getBeginLoc(), diag::note_musttail_fix_non_prototype);
760     return false;
761   }
762 
763   // Caller and callee must have matching calling conventions.
764   //
765   // Some calling conventions are physically capable of supporting tail calls
766   // even if the function types don't perfectly match. LLVM is currently too
767   // strict to allow this, but if LLVM added support for this in the future, we
768   // could exit early here and skip the remaining checks if the functions are
769   // using such a calling convention.
770   if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) {
771     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
772       Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch)
773           << true << ND->getDeclName();
774     else
775       Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch) << false;
776     Diag(CalleeLoc, diag::note_musttail_callconv_mismatch)
777         << FunctionType::getNameForCallConv(CallerType.Func->getCallConv())
778         << FunctionType::getNameForCallConv(CalleeType.Func->getCallConv());
779     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
780     return false;
781   }
782 
783   if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) {
784     Diag(St->getBeginLoc(), diag::err_musttail_no_variadic) << &MTA;
785     return false;
786   }
787 
788   // Caller and callee must match in whether they have a "this" parameter.
789   if (CallerType.This.isNull() != CalleeType.This.isNull()) {
790     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
791       Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
792           << CallerType.MemberType << CalleeType.MemberType << true
793           << ND->getDeclName();
794       Diag(CalleeLoc, diag::note_musttail_callee_defined_here)
795           << ND->getDeclName();
796     } else
797       Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
798           << CallerType.MemberType << CalleeType.MemberType << false;
799     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
800     return false;
801   }
802 
803   auto CheckTypesMatch = [this](FuncType CallerType, FuncType CalleeType,
804                                 PartialDiagnostic &PD) -> bool {
805     enum {
806       ft_different_class,
807       ft_parameter_arity,
808       ft_parameter_mismatch,
809       ft_return_type,
810     };
811 
812     auto DoTypesMatch = [this, &PD](QualType A, QualType B,
813                                     unsigned Select) -> bool {
814       if (!Context.hasSimilarType(A, B)) {
815         PD << Select << A.getUnqualifiedType() << B.getUnqualifiedType();
816         return false;
817       }
818       return true;
819     };
820 
821     if (!CallerType.This.isNull() &&
822         !DoTypesMatch(CallerType.This, CalleeType.This, ft_different_class))
823       return false;
824 
825     if (!DoTypesMatch(CallerType.Func->getReturnType(),
826                       CalleeType.Func->getReturnType(), ft_return_type))
827       return false;
828 
829     if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) {
830       PD << ft_parameter_arity << CallerType.Func->getNumParams()
831          << CalleeType.Func->getNumParams();
832       return false;
833     }
834 
835     ArrayRef<QualType> CalleeParams = CalleeType.Func->getParamTypes();
836     ArrayRef<QualType> CallerParams = CallerType.Func->getParamTypes();
837     size_t N = CallerType.Func->getNumParams();
838     for (size_t I = 0; I < N; I++) {
839       if (!DoTypesMatch(CalleeParams[I], CallerParams[I],
840                         ft_parameter_mismatch)) {
841         PD << static_cast<int>(I) + 1;
842         return false;
843       }
844     }
845 
846     return true;
847   };
848 
849   PartialDiagnostic PD = PDiag(diag::note_musttail_mismatch);
850   if (!CheckTypesMatch(CallerType, CalleeType, PD)) {
851     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
852       Diag(St->getBeginLoc(), diag::err_musttail_mismatch)
853           << true << ND->getDeclName();
854     else
855       Diag(St->getBeginLoc(), diag::err_musttail_mismatch) << false;
856     Diag(CalleeLoc, PD);
857     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
858     return false;
859   }
860 
861   return true;
862 }
863 
864 namespace {
865 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
866   typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
867   Sema &SemaRef;
868 public:
869   CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
870   void VisitBinaryOperator(BinaryOperator *E) {
871     if (E->getOpcode() == BO_Comma)
872       SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
873     EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
874   }
875 };
876 }
877 
878 StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc,
879                              IfStatementKind StatementKind,
880                              SourceLocation LParenLoc, Stmt *InitStmt,
881                              ConditionResult Cond, SourceLocation RParenLoc,
882                              Stmt *thenStmt, SourceLocation ElseLoc,
883                              Stmt *elseStmt) {
884   if (Cond.isInvalid())
885     return StmtError();
886 
887   bool ConstevalOrNegatedConsteval =
888       StatementKind == IfStatementKind::ConstevalNonNegated ||
889       StatementKind == IfStatementKind::ConstevalNegated;
890 
891   Expr *CondExpr = Cond.get().second;
892   assert((CondExpr || ConstevalOrNegatedConsteval) &&
893          "If statement: missing condition");
894   // Only call the CommaVisitor when not C89 due to differences in scope flags.
895   if (CondExpr && (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
896       !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
897     CommaVisitor(*this).Visit(CondExpr);
898 
899   if (!ConstevalOrNegatedConsteval && !elseStmt)
900     DiagnoseEmptyStmtBody(RParenLoc, thenStmt, diag::warn_empty_if_body);
901 
902   if (ConstevalOrNegatedConsteval ||
903       StatementKind == IfStatementKind::Constexpr) {
904     auto DiagnoseLikelihood = [&](const Stmt *S) {
905       if (const Attr *A = Stmt::getLikelihoodAttr(S)) {
906         Diags.Report(A->getLocation(),
907                      diag::warn_attribute_has_no_effect_on_compile_time_if)
908             << A << ConstevalOrNegatedConsteval << A->getRange();
909         Diags.Report(IfLoc,
910                      diag::note_attribute_has_no_effect_on_compile_time_if_here)
911             << ConstevalOrNegatedConsteval
912             << SourceRange(IfLoc, (ConstevalOrNegatedConsteval
913                                        ? thenStmt->getBeginLoc()
914                                        : LParenLoc)
915                                       .getLocWithOffset(-1));
916       }
917     };
918     DiagnoseLikelihood(thenStmt);
919     DiagnoseLikelihood(elseStmt);
920   } else {
921     std::tuple<bool, const Attr *, const Attr *> LHC =
922         Stmt::determineLikelihoodConflict(thenStmt, elseStmt);
923     if (std::get<0>(LHC)) {
924       const Attr *ThenAttr = std::get<1>(LHC);
925       const Attr *ElseAttr = std::get<2>(LHC);
926       Diags.Report(ThenAttr->getLocation(),
927                    diag::warn_attributes_likelihood_ifstmt_conflict)
928           << ThenAttr << ThenAttr->getRange();
929       Diags.Report(ElseAttr->getLocation(), diag::note_conflicting_attribute)
930           << ElseAttr << ElseAttr->getRange();
931     }
932   }
933 
934   if (ConstevalOrNegatedConsteval) {
935     bool Immediate = isImmediateFunctionContext();
936     if (CurContext->isFunctionOrMethod()) {
937       const auto *FD =
938           dyn_cast<FunctionDecl>(Decl::castFromDeclContext(CurContext));
939       if (FD && FD->isConsteval())
940         Immediate = true;
941     }
942     if (isUnevaluatedContext() || Immediate)
943       Diags.Report(IfLoc, diag::warn_consteval_if_always_true) << Immediate;
944   }
945 
946   return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc,
947                      thenStmt, ElseLoc, elseStmt);
948 }
949 
950 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc,
951                              IfStatementKind StatementKind,
952                              SourceLocation LParenLoc, Stmt *InitStmt,
953                              ConditionResult Cond, SourceLocation RParenLoc,
954                              Stmt *thenStmt, SourceLocation ElseLoc,
955                              Stmt *elseStmt) {
956   if (Cond.isInvalid())
957     return StmtError();
958 
959   if (StatementKind != IfStatementKind::Ordinary ||
960       isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
961     setFunctionHasBranchProtectedScope();
962 
963   return IfStmt::Create(Context, IfLoc, StatementKind, InitStmt,
964                         Cond.get().first, Cond.get().second, LParenLoc,
965                         RParenLoc, thenStmt, ElseLoc, elseStmt);
966 }
967 
968 namespace {
969   struct CaseCompareFunctor {
970     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
971                     const llvm::APSInt &RHS) {
972       return LHS.first < RHS;
973     }
974     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
975                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
976       return LHS.first < RHS.first;
977     }
978     bool operator()(const llvm::APSInt &LHS,
979                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
980       return LHS < RHS.first;
981     }
982   };
983 }
984 
985 /// CmpCaseVals - Comparison predicate for sorting case values.
986 ///
987 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
988                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
989   if (lhs.first < rhs.first)
990     return true;
991 
992   if (lhs.first == rhs.first &&
993       lhs.second->getCaseLoc() < rhs.second->getCaseLoc())
994     return true;
995   return false;
996 }
997 
998 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
999 ///
1000 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1001                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1002 {
1003   return lhs.first < rhs.first;
1004 }
1005 
1006 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
1007 ///
1008 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1009                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1010 {
1011   return lhs.first == rhs.first;
1012 }
1013 
1014 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
1015 /// potentially integral-promoted expression @p expr.
1016 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
1017   if (const auto *FE = dyn_cast<FullExpr>(E))
1018     E = FE->getSubExpr();
1019   while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
1020     if (ImpCast->getCastKind() != CK_IntegralCast) break;
1021     E = ImpCast->getSubExpr();
1022   }
1023   return E->getType();
1024 }
1025 
1026 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
1027   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
1028     Expr *Cond;
1029 
1030   public:
1031     SwitchConvertDiagnoser(Expr *Cond)
1032         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
1033           Cond(Cond) {}
1034 
1035     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1036                                          QualType T) override {
1037       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
1038     }
1039 
1040     SemaDiagnosticBuilder diagnoseIncomplete(
1041         Sema &S, SourceLocation Loc, QualType T) override {
1042       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
1043                << T << Cond->getSourceRange();
1044     }
1045 
1046     SemaDiagnosticBuilder diagnoseExplicitConv(
1047         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1048       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
1049     }
1050 
1051     SemaDiagnosticBuilder noteExplicitConv(
1052         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1053       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
1054         << ConvTy->isEnumeralType() << ConvTy;
1055     }
1056 
1057     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1058                                             QualType T) override {
1059       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
1060     }
1061 
1062     SemaDiagnosticBuilder noteAmbiguous(
1063         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1064       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
1065       << ConvTy->isEnumeralType() << ConvTy;
1066     }
1067 
1068     SemaDiagnosticBuilder diagnoseConversion(
1069         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1070       llvm_unreachable("conversion functions are permitted");
1071     }
1072   } SwitchDiagnoser(Cond);
1073 
1074   ExprResult CondResult =
1075       PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
1076   if (CondResult.isInvalid())
1077     return ExprError();
1078 
1079   // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
1080   // failed and produced a diagnostic.
1081   Cond = CondResult.get();
1082   if (!Cond->isTypeDependent() &&
1083       !Cond->getType()->isIntegralOrEnumerationType())
1084     return ExprError();
1085 
1086   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
1087   return UsualUnaryConversions(Cond);
1088 }
1089 
1090 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1091                                         SourceLocation LParenLoc,
1092                                         Stmt *InitStmt, ConditionResult Cond,
1093                                         SourceLocation RParenLoc) {
1094   Expr *CondExpr = Cond.get().second;
1095   assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
1096 
1097   if (CondExpr && !CondExpr->isTypeDependent()) {
1098     // We have already converted the expression to an integral or enumeration
1099     // type, when we parsed the switch condition. There are cases where we don't
1100     // have an appropriate type, e.g. a typo-expr Cond was corrected to an
1101     // inappropriate-type expr, we just return an error.
1102     if (!CondExpr->getType()->isIntegralOrEnumerationType())
1103       return StmtError();
1104     if (CondExpr->isKnownToHaveBooleanValue()) {
1105       // switch(bool_expr) {...} is often a programmer error, e.g.
1106       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
1107       // One can always use an if statement instead of switch(bool_expr).
1108       Diag(SwitchLoc, diag::warn_bool_switch_condition)
1109           << CondExpr->getSourceRange();
1110     }
1111   }
1112 
1113   setFunctionHasBranchIntoScope();
1114 
1115   auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr,
1116                                 LParenLoc, RParenLoc);
1117   getCurFunction()->SwitchStack.push_back(
1118       FunctionScopeInfo::SwitchInfo(SS, false));
1119   return SS;
1120 }
1121 
1122 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
1123   Val = Val.extOrTrunc(BitWidth);
1124   Val.setIsSigned(IsSigned);
1125 }
1126 
1127 /// Check the specified case value is in range for the given unpromoted switch
1128 /// type.
1129 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
1130                            unsigned UnpromotedWidth, bool UnpromotedSign) {
1131   // In C++11 onwards, this is checked by the language rules.
1132   if (S.getLangOpts().CPlusPlus11)
1133     return;
1134 
1135   // If the case value was signed and negative and the switch expression is
1136   // unsigned, don't bother to warn: this is implementation-defined behavior.
1137   // FIXME: Introduce a second, default-ignored warning for this case?
1138   if (UnpromotedWidth < Val.getBitWidth()) {
1139     llvm::APSInt ConvVal(Val);
1140     AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
1141     AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
1142     // FIXME: Use different diagnostics for overflow  in conversion to promoted
1143     // type versus "switch expression cannot have this value". Use proper
1144     // IntRange checking rather than just looking at the unpromoted type here.
1145     if (ConvVal != Val)
1146       S.Diag(Loc, diag::warn_case_value_overflow) << toString(Val, 10)
1147                                                   << toString(ConvVal, 10);
1148   }
1149 }
1150 
1151 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
1152 
1153 /// Returns true if we should emit a diagnostic about this case expression not
1154 /// being a part of the enum used in the switch controlling expression.
1155 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
1156                                               const EnumDecl *ED,
1157                                               const Expr *CaseExpr,
1158                                               EnumValsTy::iterator &EI,
1159                                               EnumValsTy::iterator &EIEnd,
1160                                               const llvm::APSInt &Val) {
1161   if (!ED->isClosed())
1162     return false;
1163 
1164   if (const DeclRefExpr *DRE =
1165           dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
1166     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1167       QualType VarType = VD->getType();
1168       QualType EnumType = S.Context.getTypeDeclType(ED);
1169       if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
1170           S.Context.hasSameUnqualifiedType(EnumType, VarType))
1171         return false;
1172     }
1173   }
1174 
1175   if (ED->hasAttr<FlagEnumAttr>())
1176     return !S.IsValueInFlagEnum(ED, Val, false);
1177 
1178   while (EI != EIEnd && EI->first < Val)
1179     EI++;
1180 
1181   if (EI != EIEnd && EI->first == Val)
1182     return false;
1183 
1184   return true;
1185 }
1186 
1187 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
1188                                        const Expr *Case) {
1189   QualType CondType = Cond->getType();
1190   QualType CaseType = Case->getType();
1191 
1192   const EnumType *CondEnumType = CondType->getAs<EnumType>();
1193   const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
1194   if (!CondEnumType || !CaseEnumType)
1195     return;
1196 
1197   // Ignore anonymous enums.
1198   if (!CondEnumType->getDecl()->getIdentifier() &&
1199       !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
1200     return;
1201   if (!CaseEnumType->getDecl()->getIdentifier() &&
1202       !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
1203     return;
1204 
1205   if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
1206     return;
1207 
1208   S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
1209       << CondType << CaseType << Cond->getSourceRange()
1210       << Case->getSourceRange();
1211 }
1212 
1213 StmtResult
1214 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
1215                             Stmt *BodyStmt) {
1216   SwitchStmt *SS = cast<SwitchStmt>(Switch);
1217   bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
1218   assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
1219          "switch stack missing push/pop!");
1220 
1221   getCurFunction()->SwitchStack.pop_back();
1222 
1223   if (!BodyStmt) return StmtError();
1224   SS->setBody(BodyStmt, SwitchLoc);
1225 
1226   Expr *CondExpr = SS->getCond();
1227   if (!CondExpr) return StmtError();
1228 
1229   QualType CondType = CondExpr->getType();
1230 
1231   // C++ 6.4.2.p2:
1232   // Integral promotions are performed (on the switch condition).
1233   //
1234   // A case value unrepresentable by the original switch condition
1235   // type (before the promotion) doesn't make sense, even when it can
1236   // be represented by the promoted type.  Therefore we need to find
1237   // the pre-promotion type of the switch condition.
1238   const Expr *CondExprBeforePromotion = CondExpr;
1239   QualType CondTypeBeforePromotion =
1240       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
1241 
1242   // Get the bitwidth of the switched-on value after promotions. We must
1243   // convert the integer case values to this width before comparison.
1244   bool HasDependentValue
1245     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
1246   unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
1247   bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
1248 
1249   // Get the width and signedness that the condition might actually have, for
1250   // warning purposes.
1251   // FIXME: Grab an IntRange for the condition rather than using the unpromoted
1252   // type.
1253   unsigned CondWidthBeforePromotion
1254     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
1255   bool CondIsSignedBeforePromotion
1256     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
1257 
1258   // Accumulate all of the case values in a vector so that we can sort them
1259   // and detect duplicates.  This vector contains the APInt for the case after
1260   // it has been converted to the condition type.
1261   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
1262   CaseValsTy CaseVals;
1263 
1264   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
1265   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
1266   CaseRangesTy CaseRanges;
1267 
1268   DefaultStmt *TheDefaultStmt = nullptr;
1269 
1270   bool CaseListIsErroneous = false;
1271 
1272   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
1273        SC = SC->getNextSwitchCase()) {
1274 
1275     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
1276       if (TheDefaultStmt) {
1277         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
1278         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
1279 
1280         // FIXME: Remove the default statement from the switch block so that
1281         // we'll return a valid AST.  This requires recursing down the AST and
1282         // finding it, not something we are set up to do right now.  For now,
1283         // just lop the entire switch stmt out of the AST.
1284         CaseListIsErroneous = true;
1285       }
1286       TheDefaultStmt = DS;
1287 
1288     } else {
1289       CaseStmt *CS = cast<CaseStmt>(SC);
1290 
1291       Expr *Lo = CS->getLHS();
1292 
1293       if (Lo->isValueDependent()) {
1294         HasDependentValue = true;
1295         break;
1296       }
1297 
1298       // We already verified that the expression has a constant value;
1299       // get that value (prior to conversions).
1300       const Expr *LoBeforePromotion = Lo;
1301       GetTypeBeforeIntegralPromotion(LoBeforePromotion);
1302       llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
1303 
1304       // Check the unconverted value is within the range of possible values of
1305       // the switch expression.
1306       checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
1307                      CondIsSignedBeforePromotion);
1308 
1309       // FIXME: This duplicates the check performed for warn_not_in_enum below.
1310       checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
1311                                  LoBeforePromotion);
1312 
1313       // Convert the value to the same width/sign as the condition.
1314       AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
1315 
1316       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
1317       if (CS->getRHS()) {
1318         if (CS->getRHS()->isValueDependent()) {
1319           HasDependentValue = true;
1320           break;
1321         }
1322         CaseRanges.push_back(std::make_pair(LoVal, CS));
1323       } else
1324         CaseVals.push_back(std::make_pair(LoVal, CS));
1325     }
1326   }
1327 
1328   if (!HasDependentValue) {
1329     // If we don't have a default statement, check whether the
1330     // condition is constant.
1331     llvm::APSInt ConstantCondValue;
1332     bool HasConstantCond = false;
1333     if (!TheDefaultStmt) {
1334       Expr::EvalResult Result;
1335       HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
1336                                                 Expr::SE_AllowSideEffects);
1337       if (Result.Val.isInt())
1338         ConstantCondValue = Result.Val.getInt();
1339       assert(!HasConstantCond ||
1340              (ConstantCondValue.getBitWidth() == CondWidth &&
1341               ConstantCondValue.isSigned() == CondIsSigned));
1342     }
1343     bool ShouldCheckConstantCond = HasConstantCond;
1344 
1345     // Sort all the scalar case values so we can easily detect duplicates.
1346     llvm::stable_sort(CaseVals, CmpCaseVals);
1347 
1348     if (!CaseVals.empty()) {
1349       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
1350         if (ShouldCheckConstantCond &&
1351             CaseVals[i].first == ConstantCondValue)
1352           ShouldCheckConstantCond = false;
1353 
1354         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
1355           // If we have a duplicate, report it.
1356           // First, determine if either case value has a name
1357           StringRef PrevString, CurrString;
1358           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
1359           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
1360           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
1361             PrevString = DeclRef->getDecl()->getName();
1362           }
1363           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
1364             CurrString = DeclRef->getDecl()->getName();
1365           }
1366           SmallString<16> CaseValStr;
1367           CaseVals[i-1].first.toString(CaseValStr);
1368 
1369           if (PrevString == CurrString)
1370             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1371                  diag::err_duplicate_case)
1372                 << (PrevString.empty() ? CaseValStr.str() : PrevString);
1373           else
1374             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1375                  diag::err_duplicate_case_differing_expr)
1376                 << (PrevString.empty() ? CaseValStr.str() : PrevString)
1377                 << (CurrString.empty() ? CaseValStr.str() : CurrString)
1378                 << CaseValStr;
1379 
1380           Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
1381                diag::note_duplicate_case_prev);
1382           // FIXME: We really want to remove the bogus case stmt from the
1383           // substmt, but we have no way to do this right now.
1384           CaseListIsErroneous = true;
1385         }
1386       }
1387     }
1388 
1389     // Detect duplicate case ranges, which usually don't exist at all in
1390     // the first place.
1391     if (!CaseRanges.empty()) {
1392       // Sort all the case ranges by their low value so we can easily detect
1393       // overlaps between ranges.
1394       llvm::stable_sort(CaseRanges);
1395 
1396       // Scan the ranges, computing the high values and removing empty ranges.
1397       std::vector<llvm::APSInt> HiVals;
1398       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1399         llvm::APSInt &LoVal = CaseRanges[i].first;
1400         CaseStmt *CR = CaseRanges[i].second;
1401         Expr *Hi = CR->getRHS();
1402 
1403         const Expr *HiBeforePromotion = Hi;
1404         GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1405         llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1406 
1407         // Check the unconverted value is within the range of possible values of
1408         // the switch expression.
1409         checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1410                        CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1411 
1412         // Convert the value to the same width/sign as the condition.
1413         AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1414 
1415         // If the low value is bigger than the high value, the case is empty.
1416         if (LoVal > HiVal) {
1417           Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1418               << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1419           CaseRanges.erase(CaseRanges.begin()+i);
1420           --i;
1421           --e;
1422           continue;
1423         }
1424 
1425         if (ShouldCheckConstantCond &&
1426             LoVal <= ConstantCondValue &&
1427             ConstantCondValue <= HiVal)
1428           ShouldCheckConstantCond = false;
1429 
1430         HiVals.push_back(HiVal);
1431       }
1432 
1433       // Rescan the ranges, looking for overlap with singleton values and other
1434       // ranges.  Since the range list is sorted, we only need to compare case
1435       // ranges with their neighbors.
1436       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1437         llvm::APSInt &CRLo = CaseRanges[i].first;
1438         llvm::APSInt &CRHi = HiVals[i];
1439         CaseStmt *CR = CaseRanges[i].second;
1440 
1441         // Check to see whether the case range overlaps with any
1442         // singleton cases.
1443         CaseStmt *OverlapStmt = nullptr;
1444         llvm::APSInt OverlapVal(32);
1445 
1446         // Find the smallest value >= the lower bound.  If I is in the
1447         // case range, then we have overlap.
1448         CaseValsTy::iterator I =
1449             llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1450         if (I != CaseVals.end() && I->first < CRHi) {
1451           OverlapVal  = I->first;   // Found overlap with scalar.
1452           OverlapStmt = I->second;
1453         }
1454 
1455         // Find the smallest value bigger than the upper bound.
1456         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1457         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1458           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
1459           OverlapStmt = (I-1)->second;
1460         }
1461 
1462         // Check to see if this case stmt overlaps with the subsequent
1463         // case range.
1464         if (i && CRLo <= HiVals[i-1]) {
1465           OverlapVal  = HiVals[i-1];       // Found overlap with range.
1466           OverlapStmt = CaseRanges[i-1].second;
1467         }
1468 
1469         if (OverlapStmt) {
1470           // If we have a duplicate, report it.
1471           Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1472               << toString(OverlapVal, 10);
1473           Diag(OverlapStmt->getLHS()->getBeginLoc(),
1474                diag::note_duplicate_case_prev);
1475           // FIXME: We really want to remove the bogus case stmt from the
1476           // substmt, but we have no way to do this right now.
1477           CaseListIsErroneous = true;
1478         }
1479       }
1480     }
1481 
1482     // Complain if we have a constant condition and we didn't find a match.
1483     if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1484         ShouldCheckConstantCond) {
1485       // TODO: it would be nice if we printed enums as enums, chars as
1486       // chars, etc.
1487       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1488         << toString(ConstantCondValue, 10)
1489         << CondExpr->getSourceRange();
1490     }
1491 
1492     // Check to see if switch is over an Enum and handles all of its
1493     // values.  We only issue a warning if there is not 'default:', but
1494     // we still do the analysis to preserve this information in the AST
1495     // (which can be used by flow-based analyes).
1496     //
1497     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1498 
1499     // If switch has default case, then ignore it.
1500     if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1501         ET && ET->getDecl()->isCompleteDefinition() &&
1502         !ET->getDecl()->enumerators().empty()) {
1503       const EnumDecl *ED = ET->getDecl();
1504       EnumValsTy EnumVals;
1505 
1506       // Gather all enum values, set their type and sort them,
1507       // allowing easier comparison with CaseVals.
1508       for (auto *EDI : ED->enumerators()) {
1509         llvm::APSInt Val = EDI->getInitVal();
1510         AdjustAPSInt(Val, CondWidth, CondIsSigned);
1511         EnumVals.push_back(std::make_pair(Val, EDI));
1512       }
1513       llvm::stable_sort(EnumVals, CmpEnumVals);
1514       auto EI = EnumVals.begin(), EIEnd =
1515         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1516 
1517       // See which case values aren't in enum.
1518       for (CaseValsTy::const_iterator CI = CaseVals.begin();
1519           CI != CaseVals.end(); CI++) {
1520         Expr *CaseExpr = CI->second->getLHS();
1521         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1522                                               CI->first))
1523           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1524             << CondTypeBeforePromotion;
1525       }
1526 
1527       // See which of case ranges aren't in enum
1528       EI = EnumVals.begin();
1529       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1530           RI != CaseRanges.end(); RI++) {
1531         Expr *CaseExpr = RI->second->getLHS();
1532         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1533                                               RI->first))
1534           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1535             << CondTypeBeforePromotion;
1536 
1537         llvm::APSInt Hi =
1538           RI->second->getRHS()->EvaluateKnownConstInt(Context);
1539         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1540 
1541         CaseExpr = RI->second->getRHS();
1542         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1543                                               Hi))
1544           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1545             << CondTypeBeforePromotion;
1546       }
1547 
1548       // Check which enum vals aren't in switch
1549       auto CI = CaseVals.begin();
1550       auto RI = CaseRanges.begin();
1551       bool hasCasesNotInSwitch = false;
1552 
1553       SmallVector<DeclarationName,8> UnhandledNames;
1554 
1555       for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1556         // Don't warn about omitted unavailable EnumConstantDecls.
1557         switch (EI->second->getAvailability()) {
1558         case AR_Deprecated:
1559           // Omitting a deprecated constant is ok; it should never materialize.
1560         case AR_Unavailable:
1561           continue;
1562 
1563         case AR_NotYetIntroduced:
1564           // Partially available enum constants should be present. Note that we
1565           // suppress -Wunguarded-availability diagnostics for such uses.
1566         case AR_Available:
1567           break;
1568         }
1569 
1570         if (EI->second->hasAttr<UnusedAttr>())
1571           continue;
1572 
1573         // Drop unneeded case values
1574         while (CI != CaseVals.end() && CI->first < EI->first)
1575           CI++;
1576 
1577         if (CI != CaseVals.end() && CI->first == EI->first)
1578           continue;
1579 
1580         // Drop unneeded case ranges
1581         for (; RI != CaseRanges.end(); RI++) {
1582           llvm::APSInt Hi =
1583             RI->second->getRHS()->EvaluateKnownConstInt(Context);
1584           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1585           if (EI->first <= Hi)
1586             break;
1587         }
1588 
1589         if (RI == CaseRanges.end() || EI->first < RI->first) {
1590           hasCasesNotInSwitch = true;
1591           UnhandledNames.push_back(EI->second->getDeclName());
1592         }
1593       }
1594 
1595       if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1596         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1597 
1598       // Produce a nice diagnostic if multiple values aren't handled.
1599       if (!UnhandledNames.empty()) {
1600         auto DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt
1601                                                    ? diag::warn_def_missing_case
1602                                                    : diag::warn_missing_case)
1603                   << CondExpr->getSourceRange() << (int)UnhandledNames.size();
1604 
1605         for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1606              I != E; ++I)
1607           DB << UnhandledNames[I];
1608       }
1609 
1610       if (!hasCasesNotInSwitch)
1611         SS->setAllEnumCasesCovered();
1612     }
1613   }
1614 
1615   if (BodyStmt)
1616     DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1617                           diag::warn_empty_switch_body);
1618 
1619   // FIXME: If the case list was broken is some way, we don't have a good system
1620   // to patch it up.  Instead, just return the whole substmt as broken.
1621   if (CaseListIsErroneous)
1622     return StmtError();
1623 
1624   return SS;
1625 }
1626 
1627 void
1628 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1629                              Expr *SrcExpr) {
1630   if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1631     return;
1632 
1633   if (const EnumType *ET = DstType->getAs<EnumType>())
1634     if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1635         SrcType->isIntegerType()) {
1636       if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1637           SrcExpr->isIntegerConstantExpr(Context)) {
1638         // Get the bitwidth of the enum value before promotions.
1639         unsigned DstWidth = Context.getIntWidth(DstType);
1640         bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1641 
1642         llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1643         AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1644         const EnumDecl *ED = ET->getDecl();
1645 
1646         if (!ED->isClosed())
1647           return;
1648 
1649         if (ED->hasAttr<FlagEnumAttr>()) {
1650           if (!IsValueInFlagEnum(ED, RhsVal, true))
1651             Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1652               << DstType.getUnqualifiedType();
1653         } else {
1654           typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1655               EnumValsTy;
1656           EnumValsTy EnumVals;
1657 
1658           // Gather all enum values, set their type and sort them,
1659           // allowing easier comparison with rhs constant.
1660           for (auto *EDI : ED->enumerators()) {
1661             llvm::APSInt Val = EDI->getInitVal();
1662             AdjustAPSInt(Val, DstWidth, DstIsSigned);
1663             EnumVals.push_back(std::make_pair(Val, EDI));
1664           }
1665           if (EnumVals.empty())
1666             return;
1667           llvm::stable_sort(EnumVals, CmpEnumVals);
1668           EnumValsTy::iterator EIend =
1669               std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1670 
1671           // See which values aren't in the enum.
1672           EnumValsTy::const_iterator EI = EnumVals.begin();
1673           while (EI != EIend && EI->first < RhsVal)
1674             EI++;
1675           if (EI == EIend || EI->first != RhsVal) {
1676             Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1677                 << DstType.getUnqualifiedType();
1678           }
1679         }
1680       }
1681     }
1682 }
1683 
1684 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
1685                                 SourceLocation LParenLoc, ConditionResult Cond,
1686                                 SourceLocation RParenLoc, Stmt *Body) {
1687   if (Cond.isInvalid())
1688     return StmtError();
1689 
1690   auto CondVal = Cond.get();
1691   CheckBreakContinueBinding(CondVal.second);
1692 
1693   if (CondVal.second &&
1694       !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1695     CommaVisitor(*this).Visit(CondVal.second);
1696 
1697   if (isa<NullStmt>(Body))
1698     getCurCompoundScope().setHasEmptyLoopBodies();
1699 
1700   return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1701                            WhileLoc, LParenLoc, RParenLoc);
1702 }
1703 
1704 StmtResult
1705 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1706                   SourceLocation WhileLoc, SourceLocation CondLParen,
1707                   Expr *Cond, SourceLocation CondRParen) {
1708   assert(Cond && "ActOnDoStmt(): missing expression");
1709 
1710   CheckBreakContinueBinding(Cond);
1711   ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1712   if (CondResult.isInvalid())
1713     return StmtError();
1714   Cond = CondResult.get();
1715 
1716   CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1717   if (CondResult.isInvalid())
1718     return StmtError();
1719   Cond = CondResult.get();
1720 
1721   // Only call the CommaVisitor for C89 due to differences in scope flags.
1722   if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1723       !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1724     CommaVisitor(*this).Visit(Cond);
1725 
1726   return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1727 }
1728 
1729 namespace {
1730   // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1731   using DeclSetVector =
1732       llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1733                       llvm::SmallPtrSet<VarDecl *, 8>>;
1734 
1735   // This visitor will traverse a conditional statement and store all
1736   // the evaluated decls into a vector.  Simple is set to true if none
1737   // of the excluded constructs are used.
1738   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1739     DeclSetVector &Decls;
1740     SmallVectorImpl<SourceRange> &Ranges;
1741     bool Simple;
1742   public:
1743     typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1744 
1745     DeclExtractor(Sema &S, DeclSetVector &Decls,
1746                   SmallVectorImpl<SourceRange> &Ranges) :
1747         Inherited(S.Context),
1748         Decls(Decls),
1749         Ranges(Ranges),
1750         Simple(true) {}
1751 
1752     bool isSimple() { return Simple; }
1753 
1754     // Replaces the method in EvaluatedExprVisitor.
1755     void VisitMemberExpr(MemberExpr* E) {
1756       Simple = false;
1757     }
1758 
1759     // Any Stmt not explicitly listed will cause the condition to be marked
1760     // complex.
1761     void VisitStmt(Stmt *S) { Simple = false; }
1762 
1763     void VisitBinaryOperator(BinaryOperator *E) {
1764       Visit(E->getLHS());
1765       Visit(E->getRHS());
1766     }
1767 
1768     void VisitCastExpr(CastExpr *E) {
1769       Visit(E->getSubExpr());
1770     }
1771 
1772     void VisitUnaryOperator(UnaryOperator *E) {
1773       // Skip checking conditionals with derefernces.
1774       if (E->getOpcode() == UO_Deref)
1775         Simple = false;
1776       else
1777         Visit(E->getSubExpr());
1778     }
1779 
1780     void VisitConditionalOperator(ConditionalOperator *E) {
1781       Visit(E->getCond());
1782       Visit(E->getTrueExpr());
1783       Visit(E->getFalseExpr());
1784     }
1785 
1786     void VisitParenExpr(ParenExpr *E) {
1787       Visit(E->getSubExpr());
1788     }
1789 
1790     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1791       Visit(E->getOpaqueValue()->getSourceExpr());
1792       Visit(E->getFalseExpr());
1793     }
1794 
1795     void VisitIntegerLiteral(IntegerLiteral *E) { }
1796     void VisitFloatingLiteral(FloatingLiteral *E) { }
1797     void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1798     void VisitCharacterLiteral(CharacterLiteral *E) { }
1799     void VisitGNUNullExpr(GNUNullExpr *E) { }
1800     void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1801 
1802     void VisitDeclRefExpr(DeclRefExpr *E) {
1803       VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1804       if (!VD) {
1805         // Don't allow unhandled Decl types.
1806         Simple = false;
1807         return;
1808       }
1809 
1810       Ranges.push_back(E->getSourceRange());
1811 
1812       Decls.insert(VD);
1813     }
1814 
1815   }; // end class DeclExtractor
1816 
1817   // DeclMatcher checks to see if the decls are used in a non-evaluated
1818   // context.
1819   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1820     DeclSetVector &Decls;
1821     bool FoundDecl;
1822 
1823   public:
1824     typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1825 
1826     DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1827         Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1828       if (!Statement) return;
1829 
1830       Visit(Statement);
1831     }
1832 
1833     void VisitReturnStmt(ReturnStmt *S) {
1834       FoundDecl = true;
1835     }
1836 
1837     void VisitBreakStmt(BreakStmt *S) {
1838       FoundDecl = true;
1839     }
1840 
1841     void VisitGotoStmt(GotoStmt *S) {
1842       FoundDecl = true;
1843     }
1844 
1845     void VisitCastExpr(CastExpr *E) {
1846       if (E->getCastKind() == CK_LValueToRValue)
1847         CheckLValueToRValueCast(E->getSubExpr());
1848       else
1849         Visit(E->getSubExpr());
1850     }
1851 
1852     void CheckLValueToRValueCast(Expr *E) {
1853       E = E->IgnoreParenImpCasts();
1854 
1855       if (isa<DeclRefExpr>(E)) {
1856         return;
1857       }
1858 
1859       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1860         Visit(CO->getCond());
1861         CheckLValueToRValueCast(CO->getTrueExpr());
1862         CheckLValueToRValueCast(CO->getFalseExpr());
1863         return;
1864       }
1865 
1866       if (BinaryConditionalOperator *BCO =
1867               dyn_cast<BinaryConditionalOperator>(E)) {
1868         CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1869         CheckLValueToRValueCast(BCO->getFalseExpr());
1870         return;
1871       }
1872 
1873       Visit(E);
1874     }
1875 
1876     void VisitDeclRefExpr(DeclRefExpr *E) {
1877       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1878         if (Decls.count(VD))
1879           FoundDecl = true;
1880     }
1881 
1882     void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1883       // Only need to visit the semantics for POE.
1884       // SyntaticForm doesn't really use the Decal.
1885       for (auto *S : POE->semantics()) {
1886         if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1887           // Look past the OVE into the expression it binds.
1888           Visit(OVE->getSourceExpr());
1889         else
1890           Visit(S);
1891       }
1892     }
1893 
1894     bool FoundDeclInUse() { return FoundDecl; }
1895 
1896   };  // end class DeclMatcher
1897 
1898   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1899                                         Expr *Third, Stmt *Body) {
1900     // Condition is empty
1901     if (!Second) return;
1902 
1903     if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1904                           Second->getBeginLoc()))
1905       return;
1906 
1907     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1908     DeclSetVector Decls;
1909     SmallVector<SourceRange, 10> Ranges;
1910     DeclExtractor DE(S, Decls, Ranges);
1911     DE.Visit(Second);
1912 
1913     // Don't analyze complex conditionals.
1914     if (!DE.isSimple()) return;
1915 
1916     // No decls found.
1917     if (Decls.size() == 0) return;
1918 
1919     // Don't warn on volatile, static, or global variables.
1920     for (auto *VD : Decls)
1921       if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1922         return;
1923 
1924     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1925         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1926         DeclMatcher(S, Decls, Body).FoundDeclInUse())
1927       return;
1928 
1929     // Load decl names into diagnostic.
1930     if (Decls.size() > 4) {
1931       PDiag << 0;
1932     } else {
1933       PDiag << (unsigned)Decls.size();
1934       for (auto *VD : Decls)
1935         PDiag << VD->getDeclName();
1936     }
1937 
1938     for (auto Range : Ranges)
1939       PDiag << Range;
1940 
1941     S.Diag(Ranges.begin()->getBegin(), PDiag);
1942   }
1943 
1944   // If Statement is an incemement or decrement, return true and sets the
1945   // variables Increment and DRE.
1946   bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1947                             DeclRefExpr *&DRE) {
1948     if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1949       if (!Cleanups->cleanupsHaveSideEffects())
1950         Statement = Cleanups->getSubExpr();
1951 
1952     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1953       switch (UO->getOpcode()) {
1954         default: return false;
1955         case UO_PostInc:
1956         case UO_PreInc:
1957           Increment = true;
1958           break;
1959         case UO_PostDec:
1960         case UO_PreDec:
1961           Increment = false;
1962           break;
1963       }
1964       DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1965       return DRE;
1966     }
1967 
1968     if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1969       FunctionDecl *FD = Call->getDirectCallee();
1970       if (!FD || !FD->isOverloadedOperator()) return false;
1971       switch (FD->getOverloadedOperator()) {
1972         default: return false;
1973         case OO_PlusPlus:
1974           Increment = true;
1975           break;
1976         case OO_MinusMinus:
1977           Increment = false;
1978           break;
1979       }
1980       DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1981       return DRE;
1982     }
1983 
1984     return false;
1985   }
1986 
1987   // A visitor to determine if a continue or break statement is a
1988   // subexpression.
1989   class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1990     SourceLocation BreakLoc;
1991     SourceLocation ContinueLoc;
1992     bool InSwitch = false;
1993 
1994   public:
1995     BreakContinueFinder(Sema &S, const Stmt* Body) :
1996         Inherited(S.Context) {
1997       Visit(Body);
1998     }
1999 
2000     typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
2001 
2002     void VisitContinueStmt(const ContinueStmt* E) {
2003       ContinueLoc = E->getContinueLoc();
2004     }
2005 
2006     void VisitBreakStmt(const BreakStmt* E) {
2007       if (!InSwitch)
2008         BreakLoc = E->getBreakLoc();
2009     }
2010 
2011     void VisitSwitchStmt(const SwitchStmt* S) {
2012       if (const Stmt *Init = S->getInit())
2013         Visit(Init);
2014       if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
2015         Visit(CondVar);
2016       if (const Stmt *Cond = S->getCond())
2017         Visit(Cond);
2018 
2019       // Don't return break statements from the body of a switch.
2020       InSwitch = true;
2021       if (const Stmt *Body = S->getBody())
2022         Visit(Body);
2023       InSwitch = false;
2024     }
2025 
2026     void VisitForStmt(const ForStmt *S) {
2027       // Only visit the init statement of a for loop; the body
2028       // has a different break/continue scope.
2029       if (const Stmt *Init = S->getInit())
2030         Visit(Init);
2031     }
2032 
2033     void VisitWhileStmt(const WhileStmt *) {
2034       // Do nothing; the children of a while loop have a different
2035       // break/continue scope.
2036     }
2037 
2038     void VisitDoStmt(const DoStmt *) {
2039       // Do nothing; the children of a while loop have a different
2040       // break/continue scope.
2041     }
2042 
2043     void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2044       // Only visit the initialization of a for loop; the body
2045       // has a different break/continue scope.
2046       if (const Stmt *Init = S->getInit())
2047         Visit(Init);
2048       if (const Stmt *Range = S->getRangeStmt())
2049         Visit(Range);
2050       if (const Stmt *Begin = S->getBeginStmt())
2051         Visit(Begin);
2052       if (const Stmt *End = S->getEndStmt())
2053         Visit(End);
2054     }
2055 
2056     void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
2057       // Only visit the initialization of a for loop; the body
2058       // has a different break/continue scope.
2059       if (const Stmt *Element = S->getElement())
2060         Visit(Element);
2061       if (const Stmt *Collection = S->getCollection())
2062         Visit(Collection);
2063     }
2064 
2065     bool ContinueFound() { return ContinueLoc.isValid(); }
2066     bool BreakFound() { return BreakLoc.isValid(); }
2067     SourceLocation GetContinueLoc() { return ContinueLoc; }
2068     SourceLocation GetBreakLoc() { return BreakLoc; }
2069 
2070   };  // end class BreakContinueFinder
2071 
2072   // Emit a warning when a loop increment/decrement appears twice per loop
2073   // iteration.  The conditions which trigger this warning are:
2074   // 1) The last statement in the loop body and the third expression in the
2075   //    for loop are both increment or both decrement of the same variable
2076   // 2) No continue statements in the loop body.
2077   void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
2078     // Return when there is nothing to check.
2079     if (!Body || !Third) return;
2080 
2081     if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
2082                           Third->getBeginLoc()))
2083       return;
2084 
2085     // Get the last statement from the loop body.
2086     CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
2087     if (!CS || CS->body_empty()) return;
2088     Stmt *LastStmt = CS->body_back();
2089     if (!LastStmt) return;
2090 
2091     bool LoopIncrement, LastIncrement;
2092     DeclRefExpr *LoopDRE, *LastDRE;
2093 
2094     if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
2095     if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
2096 
2097     // Check that the two statements are both increments or both decrements
2098     // on the same variable.
2099     if (LoopIncrement != LastIncrement ||
2100         LoopDRE->getDecl() != LastDRE->getDecl()) return;
2101 
2102     if (BreakContinueFinder(S, Body).ContinueFound()) return;
2103 
2104     S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
2105          << LastDRE->getDecl() << LastIncrement;
2106     S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
2107          << LoopIncrement;
2108   }
2109 
2110 } // end namespace
2111 
2112 
2113 void Sema::CheckBreakContinueBinding(Expr *E) {
2114   if (!E || getLangOpts().CPlusPlus)
2115     return;
2116   BreakContinueFinder BCFinder(*this, E);
2117   Scope *BreakParent = CurScope->getBreakParent();
2118   if (BCFinder.BreakFound() && BreakParent) {
2119     if (BreakParent->getFlags() & Scope::SwitchScope) {
2120       Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
2121     } else {
2122       Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
2123           << "break";
2124     }
2125   } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
2126     Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
2127         << "continue";
2128   }
2129 }
2130 
2131 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
2132                               Stmt *First, ConditionResult Second,
2133                               FullExprArg third, SourceLocation RParenLoc,
2134                               Stmt *Body) {
2135   if (Second.isInvalid())
2136     return StmtError();
2137 
2138   if (!getLangOpts().CPlusPlus) {
2139     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
2140       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2141       // declare identifiers for objects having storage class 'auto' or
2142       // 'register'.
2143       const Decl *NonVarSeen = nullptr;
2144       bool VarDeclSeen = false;
2145       for (auto *DI : DS->decls()) {
2146         if (VarDecl *VD = dyn_cast<VarDecl>(DI)) {
2147           VarDeclSeen = true;
2148           if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) {
2149             Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
2150             DI->setInvalidDecl();
2151           }
2152         } else if (!NonVarSeen) {
2153           // Keep track of the first non-variable declaration we saw so that
2154           // we can diagnose if we don't see any variable declarations. This
2155           // covers a case like declaring a typedef, function, or structure
2156           // type rather than a variable.
2157           NonVarSeen = DI;
2158         }
2159       }
2160       // Diagnose if we saw a non-variable declaration but no variable
2161       // declarations.
2162       if (NonVarSeen && !VarDeclSeen)
2163         Diag(NonVarSeen->getLocation(), diag::err_non_variable_decl_in_for);
2164     }
2165   }
2166 
2167   CheckBreakContinueBinding(Second.get().second);
2168   CheckBreakContinueBinding(third.get());
2169 
2170   if (!Second.get().first)
2171     CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
2172                                      Body);
2173   CheckForRedundantIteration(*this, third.get(), Body);
2174 
2175   if (Second.get().second &&
2176       !Diags.isIgnored(diag::warn_comma_operator,
2177                        Second.get().second->getExprLoc()))
2178     CommaVisitor(*this).Visit(Second.get().second);
2179 
2180   Expr *Third  = third.release().getAs<Expr>();
2181   if (isa<NullStmt>(Body))
2182     getCurCompoundScope().setHasEmptyLoopBodies();
2183 
2184   return new (Context)
2185       ForStmt(Context, First, Second.get().second, Second.get().first, Third,
2186               Body, ForLoc, LParenLoc, RParenLoc);
2187 }
2188 
2189 /// In an Objective C collection iteration statement:
2190 ///   for (x in y)
2191 /// x can be an arbitrary l-value expression.  Bind it up as a
2192 /// full-expression.
2193 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
2194   // Reduce placeholder expressions here.  Note that this rejects the
2195   // use of pseudo-object l-values in this position.
2196   ExprResult result = CheckPlaceholderExpr(E);
2197   if (result.isInvalid()) return StmtError();
2198   E = result.get();
2199 
2200   ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2201   if (FullExpr.isInvalid())
2202     return StmtError();
2203   return StmtResult(static_cast<Stmt*>(FullExpr.get()));
2204 }
2205 
2206 ExprResult
2207 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
2208   if (!collection)
2209     return ExprError();
2210 
2211   ExprResult result = CorrectDelayedTyposInExpr(collection);
2212   if (!result.isUsable())
2213     return ExprError();
2214   collection = result.get();
2215 
2216   // Bail out early if we've got a type-dependent expression.
2217   if (collection->isTypeDependent()) return collection;
2218 
2219   // Perform normal l-value conversion.
2220   result = DefaultFunctionArrayLvalueConversion(collection);
2221   if (result.isInvalid())
2222     return ExprError();
2223   collection = result.get();
2224 
2225   // The operand needs to have object-pointer type.
2226   // TODO: should we do a contextual conversion?
2227   const ObjCObjectPointerType *pointerType =
2228     collection->getType()->getAs<ObjCObjectPointerType>();
2229   if (!pointerType)
2230     return Diag(forLoc, diag::err_collection_expr_type)
2231              << collection->getType() << collection->getSourceRange();
2232 
2233   // Check that the operand provides
2234   //   - countByEnumeratingWithState:objects:count:
2235   const ObjCObjectType *objectType = pointerType->getObjectType();
2236   ObjCInterfaceDecl *iface = objectType->getInterface();
2237 
2238   // If we have a forward-declared type, we can't do this check.
2239   // Under ARC, it is an error not to have a forward-declared class.
2240   if (iface &&
2241       (getLangOpts().ObjCAutoRefCount
2242            ? RequireCompleteType(forLoc, QualType(objectType, 0),
2243                                  diag::err_arc_collection_forward, collection)
2244            : !isCompleteType(forLoc, QualType(objectType, 0)))) {
2245     // Otherwise, if we have any useful type information, check that
2246     // the type declares the appropriate method.
2247   } else if (iface || !objectType->qual_empty()) {
2248     IdentifierInfo *selectorIdents[] = {
2249       &Context.Idents.get("countByEnumeratingWithState"),
2250       &Context.Idents.get("objects"),
2251       &Context.Idents.get("count")
2252     };
2253     Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
2254 
2255     ObjCMethodDecl *method = nullptr;
2256 
2257     // If there's an interface, look in both the public and private APIs.
2258     if (iface) {
2259       method = iface->lookupInstanceMethod(selector);
2260       if (!method) method = iface->lookupPrivateMethod(selector);
2261     }
2262 
2263     // Also check protocol qualifiers.
2264     if (!method)
2265       method = LookupMethodInQualifiedType(selector, pointerType,
2266                                            /*instance*/ true);
2267 
2268     // If we didn't find it anywhere, give up.
2269     if (!method) {
2270       Diag(forLoc, diag::warn_collection_expr_type)
2271         << collection->getType() << selector << collection->getSourceRange();
2272     }
2273 
2274     // TODO: check for an incompatible signature?
2275   }
2276 
2277   // Wrap up any cleanups in the expression.
2278   return collection;
2279 }
2280 
2281 StmtResult
2282 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
2283                                  Stmt *First, Expr *collection,
2284                                  SourceLocation RParenLoc) {
2285   setFunctionHasBranchProtectedScope();
2286 
2287   ExprResult CollectionExprResult =
2288     CheckObjCForCollectionOperand(ForLoc, collection);
2289 
2290   if (First) {
2291     QualType FirstType;
2292     if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
2293       if (!DS->isSingleDecl())
2294         return StmtError(Diag((*DS->decl_begin())->getLocation(),
2295                          diag::err_toomany_element_decls));
2296 
2297       VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
2298       if (!D || D->isInvalidDecl())
2299         return StmtError();
2300 
2301       FirstType = D->getType();
2302       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2303       // declare identifiers for objects having storage class 'auto' or
2304       // 'register'.
2305       if (!D->hasLocalStorage())
2306         return StmtError(Diag(D->getLocation(),
2307                               diag::err_non_local_variable_decl_in_for));
2308 
2309       // If the type contained 'auto', deduce the 'auto' to 'id'.
2310       if (FirstType->getContainedAutoType()) {
2311         SourceLocation Loc = D->getLocation();
2312         OpaqueValueExpr OpaqueId(Loc, Context.getObjCIdType(), VK_PRValue);
2313         Expr *DeducedInit = &OpaqueId;
2314         TemplateDeductionInfo Info(Loc);
2315         FirstType = QualType();
2316         TemplateDeductionResult Result = DeduceAutoType(
2317             D->getTypeSourceInfo()->getTypeLoc(), DeducedInit, FirstType, Info);
2318         if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
2319           DiagnoseAutoDeductionFailure(D, DeducedInit);
2320         if (FirstType.isNull()) {
2321           D->setInvalidDecl();
2322           return StmtError();
2323         }
2324 
2325         D->setType(FirstType);
2326 
2327         if (!inTemplateInstantiation()) {
2328           SourceLocation Loc =
2329               D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
2330           Diag(Loc, diag::warn_auto_var_is_id)
2331             << D->getDeclName();
2332         }
2333       }
2334 
2335     } else {
2336       Expr *FirstE = cast<Expr>(First);
2337       if (!FirstE->isTypeDependent() && !FirstE->isLValue())
2338         return StmtError(
2339             Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
2340             << First->getSourceRange());
2341 
2342       FirstType = static_cast<Expr*>(First)->getType();
2343       if (FirstType.isConstQualified())
2344         Diag(ForLoc, diag::err_selector_element_const_type)
2345           << FirstType << First->getSourceRange();
2346     }
2347     if (!FirstType->isDependentType() &&
2348         !FirstType->isObjCObjectPointerType() &&
2349         !FirstType->isBlockPointerType())
2350         return StmtError(Diag(ForLoc, diag::err_selector_element_type)
2351                            << FirstType << First->getSourceRange());
2352   }
2353 
2354   if (CollectionExprResult.isInvalid())
2355     return StmtError();
2356 
2357   CollectionExprResult =
2358       ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
2359   if (CollectionExprResult.isInvalid())
2360     return StmtError();
2361 
2362   return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
2363                                              nullptr, ForLoc, RParenLoc);
2364 }
2365 
2366 /// Finish building a variable declaration for a for-range statement.
2367 /// \return true if an error occurs.
2368 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
2369                                   SourceLocation Loc, int DiagID) {
2370   if (Decl->getType()->isUndeducedType()) {
2371     ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
2372     if (!Res.isUsable()) {
2373       Decl->setInvalidDecl();
2374       return true;
2375     }
2376     Init = Res.get();
2377   }
2378 
2379   // Deduce the type for the iterator variable now rather than leaving it to
2380   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2381   QualType InitType;
2382   if (!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) {
2383     SemaRef.Diag(Loc, DiagID) << Init->getType();
2384   } else {
2385     TemplateDeductionInfo Info(Init->getExprLoc());
2386     Sema::TemplateDeductionResult Result = SemaRef.DeduceAutoType(
2387         Decl->getTypeSourceInfo()->getTypeLoc(), Init, InitType, Info);
2388     if (Result != Sema::TDK_Success && Result != Sema::TDK_AlreadyDiagnosed)
2389       SemaRef.Diag(Loc, DiagID) << Init->getType();
2390   }
2391 
2392   if (InitType.isNull()) {
2393     Decl->setInvalidDecl();
2394     return true;
2395   }
2396   Decl->setType(InitType);
2397 
2398   // In ARC, infer lifetime.
2399   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2400   // we're doing the equivalent of fast iteration.
2401   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2402       SemaRef.inferObjCARCLifetime(Decl))
2403     Decl->setInvalidDecl();
2404 
2405   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2406   SemaRef.FinalizeDeclaration(Decl);
2407   SemaRef.CurContext->addHiddenDecl(Decl);
2408   return false;
2409 }
2410 
2411 namespace {
2412 // An enum to represent whether something is dealing with a call to begin()
2413 // or a call to end() in a range-based for loop.
2414 enum BeginEndFunction {
2415   BEF_begin,
2416   BEF_end
2417 };
2418 
2419 /// Produce a note indicating which begin/end function was implicitly called
2420 /// by a C++11 for-range statement. This is often not obvious from the code,
2421 /// nor from the diagnostics produced when analysing the implicit expressions
2422 /// required in a for-range statement.
2423 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2424                                   BeginEndFunction BEF) {
2425   CallExpr *CE = dyn_cast<CallExpr>(E);
2426   if (!CE)
2427     return;
2428   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2429   if (!D)
2430     return;
2431   SourceLocation Loc = D->getLocation();
2432 
2433   std::string Description;
2434   bool IsTemplate = false;
2435   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2436     Description = SemaRef.getTemplateArgumentBindingsText(
2437       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2438     IsTemplate = true;
2439   }
2440 
2441   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2442     << BEF << IsTemplate << Description << E->getType();
2443 }
2444 
2445 /// Build a variable declaration for a for-range statement.
2446 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2447                               QualType Type, StringRef Name) {
2448   DeclContext *DC = SemaRef.CurContext;
2449   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2450   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2451   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2452                                   TInfo, SC_None);
2453   Decl->setImplicit();
2454   return Decl;
2455 }
2456 
2457 }
2458 
2459 static bool ObjCEnumerationCollection(Expr *Collection) {
2460   return !Collection->isTypeDependent()
2461           && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2462 }
2463 
2464 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2465 ///
2466 /// C++11 [stmt.ranged]:
2467 ///   A range-based for statement is equivalent to
2468 ///
2469 ///   {
2470 ///     auto && __range = range-init;
2471 ///     for ( auto __begin = begin-expr,
2472 ///           __end = end-expr;
2473 ///           __begin != __end;
2474 ///           ++__begin ) {
2475 ///       for-range-declaration = *__begin;
2476 ///       statement
2477 ///     }
2478 ///   }
2479 ///
2480 /// The body of the loop is not available yet, since it cannot be analysed until
2481 /// we have determined the type of the for-range-declaration.
2482 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2483                                       SourceLocation CoawaitLoc, Stmt *InitStmt,
2484                                       Stmt *First, SourceLocation ColonLoc,
2485                                       Expr *Range, SourceLocation RParenLoc,
2486                                       BuildForRangeKind Kind) {
2487   // FIXME: recover in order to allow the body to be parsed.
2488   if (!First)
2489     return StmtError();
2490 
2491   if (Range && ObjCEnumerationCollection(Range)) {
2492     // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2493     if (InitStmt)
2494       return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2495                  << InitStmt->getSourceRange();
2496     return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2497   }
2498 
2499   DeclStmt *DS = dyn_cast<DeclStmt>(First);
2500   assert(DS && "first part of for range not a decl stmt");
2501 
2502   if (!DS->isSingleDecl()) {
2503     Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2504     return StmtError();
2505   }
2506 
2507   // This function is responsible for attaching an initializer to LoopVar. We
2508   // must call ActOnInitializerError if we fail to do so.
2509   Decl *LoopVar = DS->getSingleDecl();
2510   if (LoopVar->isInvalidDecl() || !Range ||
2511       DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2512     ActOnInitializerError(LoopVar);
2513     return StmtError();
2514   }
2515 
2516   // Build the coroutine state immediately and not later during template
2517   // instantiation
2518   if (!CoawaitLoc.isInvalid()) {
2519     if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
2520       ActOnInitializerError(LoopVar);
2521       return StmtError();
2522     }
2523   }
2524 
2525   // Build  auto && __range = range-init
2526   // Divide by 2, since the variables are in the inner scope (loop body).
2527   const auto DepthStr = std::to_string(S->getDepth() / 2);
2528   SourceLocation RangeLoc = Range->getBeginLoc();
2529   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2530                                            Context.getAutoRRefDeductType(),
2531                                            std::string("__range") + DepthStr);
2532   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2533                             diag::err_for_range_deduction_failure)) {
2534     ActOnInitializerError(LoopVar);
2535     return StmtError();
2536   }
2537 
2538   // Claim the type doesn't contain auto: we've already done the checking.
2539   DeclGroupPtrTy RangeGroup =
2540       BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2541   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2542   if (RangeDecl.isInvalid()) {
2543     ActOnInitializerError(LoopVar);
2544     return StmtError();
2545   }
2546 
2547   StmtResult R = BuildCXXForRangeStmt(
2548       ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2549       /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2550       /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2551   if (R.isInvalid()) {
2552     ActOnInitializerError(LoopVar);
2553     return StmtError();
2554   }
2555 
2556   return R;
2557 }
2558 
2559 /// Create the initialization, compare, and increment steps for
2560 /// the range-based for loop expression.
2561 /// This function does not handle array-based for loops,
2562 /// which are created in Sema::BuildCXXForRangeStmt.
2563 ///
2564 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2565 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2566 /// CandidateSet and BEF are set and some non-success value is returned on
2567 /// failure.
2568 static Sema::ForRangeStatus
2569 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2570                       QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2571                       SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2572                       OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2573                       ExprResult *EndExpr, BeginEndFunction *BEF) {
2574   DeclarationNameInfo BeginNameInfo(
2575       &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2576   DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2577                                   ColonLoc);
2578 
2579   LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2580                                  Sema::LookupMemberName);
2581   LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2582 
2583   auto BuildBegin = [&] {
2584     *BEF = BEF_begin;
2585     Sema::ForRangeStatus RangeStatus =
2586         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2587                                           BeginMemberLookup, CandidateSet,
2588                                           BeginRange, BeginExpr);
2589 
2590     if (RangeStatus != Sema::FRS_Success) {
2591       if (RangeStatus == Sema::FRS_DiagnosticIssued)
2592         SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2593             << ColonLoc << BEF_begin << BeginRange->getType();
2594       return RangeStatus;
2595     }
2596     if (!CoawaitLoc.isInvalid()) {
2597       // FIXME: getCurScope() should not be used during template instantiation.
2598       // We should pick up the set of unqualified lookup results for operator
2599       // co_await during the initial parse.
2600       *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2601                                             BeginExpr->get());
2602       if (BeginExpr->isInvalid())
2603         return Sema::FRS_DiagnosticIssued;
2604     }
2605     if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2606                               diag::err_for_range_iter_deduction_failure)) {
2607       NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2608       return Sema::FRS_DiagnosticIssued;
2609     }
2610     return Sema::FRS_Success;
2611   };
2612 
2613   auto BuildEnd = [&] {
2614     *BEF = BEF_end;
2615     Sema::ForRangeStatus RangeStatus =
2616         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2617                                           EndMemberLookup, CandidateSet,
2618                                           EndRange, EndExpr);
2619     if (RangeStatus != Sema::FRS_Success) {
2620       if (RangeStatus == Sema::FRS_DiagnosticIssued)
2621         SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2622             << ColonLoc << BEF_end << EndRange->getType();
2623       return RangeStatus;
2624     }
2625     if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2626                               diag::err_for_range_iter_deduction_failure)) {
2627       NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2628       return Sema::FRS_DiagnosticIssued;
2629     }
2630     return Sema::FRS_Success;
2631   };
2632 
2633   if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2634     // - if _RangeT is a class type, the unqualified-ids begin and end are
2635     //   looked up in the scope of class _RangeT as if by class member access
2636     //   lookup (3.4.5), and if either (or both) finds at least one
2637     //   declaration, begin-expr and end-expr are __range.begin() and
2638     //   __range.end(), respectively;
2639     SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2640     if (BeginMemberLookup.isAmbiguous())
2641       return Sema::FRS_DiagnosticIssued;
2642 
2643     SemaRef.LookupQualifiedName(EndMemberLookup, D);
2644     if (EndMemberLookup.isAmbiguous())
2645       return Sema::FRS_DiagnosticIssued;
2646 
2647     if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2648       // Look up the non-member form of the member we didn't find, first.
2649       // This way we prefer a "no viable 'end'" diagnostic over a "i found
2650       // a 'begin' but ignored it because there was no member 'end'"
2651       // diagnostic.
2652       auto BuildNonmember = [&](
2653           BeginEndFunction BEFFound, LookupResult &Found,
2654           llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2655           llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2656         LookupResult OldFound = std::move(Found);
2657         Found.clear();
2658 
2659         if (Sema::ForRangeStatus Result = BuildNotFound())
2660           return Result;
2661 
2662         switch (BuildFound()) {
2663         case Sema::FRS_Success:
2664           return Sema::FRS_Success;
2665 
2666         case Sema::FRS_NoViableFunction:
2667           CandidateSet->NoteCandidates(
2668               PartialDiagnosticAt(BeginRange->getBeginLoc(),
2669                                   SemaRef.PDiag(diag::err_for_range_invalid)
2670                                       << BeginRange->getType() << BEFFound),
2671               SemaRef, OCD_AllCandidates, BeginRange);
2672           [[fallthrough]];
2673 
2674         case Sema::FRS_DiagnosticIssued:
2675           for (NamedDecl *D : OldFound) {
2676             SemaRef.Diag(D->getLocation(),
2677                          diag::note_for_range_member_begin_end_ignored)
2678                 << BeginRange->getType() << BEFFound;
2679           }
2680           return Sema::FRS_DiagnosticIssued;
2681         }
2682         llvm_unreachable("unexpected ForRangeStatus");
2683       };
2684       if (BeginMemberLookup.empty())
2685         return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2686       return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2687     }
2688   } else {
2689     // - otherwise, begin-expr and end-expr are begin(__range) and
2690     //   end(__range), respectively, where begin and end are looked up with
2691     //   argument-dependent lookup (3.4.2). For the purposes of this name
2692     //   lookup, namespace std is an associated namespace.
2693   }
2694 
2695   if (Sema::ForRangeStatus Result = BuildBegin())
2696     return Result;
2697   return BuildEnd();
2698 }
2699 
2700 /// Speculatively attempt to dereference an invalid range expression.
2701 /// If the attempt fails, this function will return a valid, null StmtResult
2702 /// and emit no diagnostics.
2703 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2704                                                  SourceLocation ForLoc,
2705                                                  SourceLocation CoawaitLoc,
2706                                                  Stmt *InitStmt,
2707                                                  Stmt *LoopVarDecl,
2708                                                  SourceLocation ColonLoc,
2709                                                  Expr *Range,
2710                                                  SourceLocation RangeLoc,
2711                                                  SourceLocation RParenLoc) {
2712   // Determine whether we can rebuild the for-range statement with a
2713   // dereferenced range expression.
2714   ExprResult AdjustedRange;
2715   {
2716     Sema::SFINAETrap Trap(SemaRef);
2717 
2718     AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2719     if (AdjustedRange.isInvalid())
2720       return StmtResult();
2721 
2722     StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2723         S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2724         AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2725     if (SR.isInvalid())
2726       return StmtResult();
2727   }
2728 
2729   // The attempt to dereference worked well enough that it could produce a valid
2730   // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2731   // case there are any other (non-fatal) problems with it.
2732   SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2733     << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2734   return SemaRef.ActOnCXXForRangeStmt(
2735       S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2736       AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2737 }
2738 
2739 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2740 StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2741                                       SourceLocation CoawaitLoc, Stmt *InitStmt,
2742                                       SourceLocation ColonLoc, Stmt *RangeDecl,
2743                                       Stmt *Begin, Stmt *End, Expr *Cond,
2744                                       Expr *Inc, Stmt *LoopVarDecl,
2745                                       SourceLocation RParenLoc,
2746                                       BuildForRangeKind Kind) {
2747   // FIXME: This should not be used during template instantiation. We should
2748   // pick up the set of unqualified lookup results for the != and + operators
2749   // in the initial parse.
2750   //
2751   // Testcase (accepts-invalid):
2752   //   template<typename T> void f() { for (auto x : T()) {} }
2753   //   namespace N { struct X { X begin(); X end(); int operator*(); }; }
2754   //   bool operator!=(N::X, N::X); void operator++(N::X);
2755   //   void g() { f<N::X>(); }
2756   Scope *S = getCurScope();
2757 
2758   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2759   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2760   QualType RangeVarType = RangeVar->getType();
2761 
2762   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2763   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2764 
2765   StmtResult BeginDeclStmt = Begin;
2766   StmtResult EndDeclStmt = End;
2767   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2768 
2769   if (RangeVarType->isDependentType()) {
2770     // The range is implicitly used as a placeholder when it is dependent.
2771     RangeVar->markUsed(Context);
2772 
2773     // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2774     // them in properly when we instantiate the loop.
2775     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2776       if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2777         for (auto *Binding : DD->bindings())
2778           Binding->setType(Context.DependentTy);
2779       LoopVar->setType(SubstAutoTypeDependent(LoopVar->getType()));
2780     }
2781   } else if (!BeginDeclStmt.get()) {
2782     SourceLocation RangeLoc = RangeVar->getLocation();
2783 
2784     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2785 
2786     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2787                                                 VK_LValue, ColonLoc);
2788     if (BeginRangeRef.isInvalid())
2789       return StmtError();
2790 
2791     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2792                                               VK_LValue, ColonLoc);
2793     if (EndRangeRef.isInvalid())
2794       return StmtError();
2795 
2796     QualType AutoType = Context.getAutoDeductType();
2797     Expr *Range = RangeVar->getInit();
2798     if (!Range)
2799       return StmtError();
2800     QualType RangeType = Range->getType();
2801 
2802     if (RequireCompleteType(RangeLoc, RangeType,
2803                             diag::err_for_range_incomplete_type))
2804       return StmtError();
2805 
2806     // Build auto __begin = begin-expr, __end = end-expr.
2807     // Divide by 2, since the variables are in the inner scope (loop body).
2808     const auto DepthStr = std::to_string(S->getDepth() / 2);
2809     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2810                                              std::string("__begin") + DepthStr);
2811     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2812                                            std::string("__end") + DepthStr);
2813 
2814     // Build begin-expr and end-expr and attach to __begin and __end variables.
2815     ExprResult BeginExpr, EndExpr;
2816     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2817       // - if _RangeT is an array type, begin-expr and end-expr are __range and
2818       //   __range + __bound, respectively, where __bound is the array bound. If
2819       //   _RangeT is an array of unknown size or an array of incomplete type,
2820       //   the program is ill-formed;
2821 
2822       // begin-expr is __range.
2823       BeginExpr = BeginRangeRef;
2824       if (!CoawaitLoc.isInvalid()) {
2825         BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2826         if (BeginExpr.isInvalid())
2827           return StmtError();
2828       }
2829       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2830                                 diag::err_for_range_iter_deduction_failure)) {
2831         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2832         return StmtError();
2833       }
2834 
2835       // Find the array bound.
2836       ExprResult BoundExpr;
2837       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2838         BoundExpr = IntegerLiteral::Create(
2839             Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2840       else if (const VariableArrayType *VAT =
2841                dyn_cast<VariableArrayType>(UnqAT)) {
2842         // For a variably modified type we can't just use the expression within
2843         // the array bounds, since we don't want that to be re-evaluated here.
2844         // Rather, we need to determine what it was when the array was first
2845         // created - so we resort to using sizeof(vla)/sizeof(element).
2846         // For e.g.
2847         //  void f(int b) {
2848         //    int vla[b];
2849         //    b = -1;   <-- This should not affect the num of iterations below
2850         //    for (int &c : vla) { .. }
2851         //  }
2852 
2853         // FIXME: This results in codegen generating IR that recalculates the
2854         // run-time number of elements (as opposed to just using the IR Value
2855         // that corresponds to the run-time value of each bound that was
2856         // generated when the array was created.) If this proves too embarrassing
2857         // even for unoptimized IR, consider passing a magic-value/cookie to
2858         // codegen that then knows to simply use that initial llvm::Value (that
2859         // corresponds to the bound at time of array creation) within
2860         // getelementptr.  But be prepared to pay the price of increasing a
2861         // customized form of coupling between the two components - which  could
2862         // be hard to maintain as the codebase evolves.
2863 
2864         ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2865             EndVar->getLocation(), UETT_SizeOf,
2866             /*IsType=*/true,
2867             CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2868                                                  VAT->desugar(), RangeLoc))
2869                 .getAsOpaquePtr(),
2870             EndVar->getSourceRange());
2871         if (SizeOfVLAExprR.isInvalid())
2872           return StmtError();
2873 
2874         ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2875             EndVar->getLocation(), UETT_SizeOf,
2876             /*IsType=*/true,
2877             CreateParsedType(VAT->desugar(),
2878                              Context.getTrivialTypeSourceInfo(
2879                                  VAT->getElementType(), RangeLoc))
2880                 .getAsOpaquePtr(),
2881             EndVar->getSourceRange());
2882         if (SizeOfEachElementExprR.isInvalid())
2883           return StmtError();
2884 
2885         BoundExpr =
2886             ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2887                        SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2888         if (BoundExpr.isInvalid())
2889           return StmtError();
2890 
2891       } else {
2892         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2893         // UnqAT is not incomplete and Range is not type-dependent.
2894         llvm_unreachable("Unexpected array type in for-range");
2895       }
2896 
2897       // end-expr is __range + __bound.
2898       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2899                            BoundExpr.get());
2900       if (EndExpr.isInvalid())
2901         return StmtError();
2902       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2903                                 diag::err_for_range_iter_deduction_failure)) {
2904         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2905         return StmtError();
2906       }
2907     } else {
2908       OverloadCandidateSet CandidateSet(RangeLoc,
2909                                         OverloadCandidateSet::CSK_Normal);
2910       BeginEndFunction BEFFailure;
2911       ForRangeStatus RangeStatus = BuildNonArrayForRange(
2912           *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2913           EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2914           &BEFFailure);
2915 
2916       if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2917           BEFFailure == BEF_begin) {
2918         // If the range is being built from an array parameter, emit a
2919         // a diagnostic that it is being treated as a pointer.
2920         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2921           if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2922             QualType ArrayTy = PVD->getOriginalType();
2923             QualType PointerTy = PVD->getType();
2924             if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2925               Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2926                   << RangeLoc << PVD << ArrayTy << PointerTy;
2927               Diag(PVD->getLocation(), diag::note_declared_at);
2928               return StmtError();
2929             }
2930           }
2931         }
2932 
2933         // If building the range failed, try dereferencing the range expression
2934         // unless a diagnostic was issued or the end function is problematic.
2935         StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2936                                                        CoawaitLoc, InitStmt,
2937                                                        LoopVarDecl, ColonLoc,
2938                                                        Range, RangeLoc,
2939                                                        RParenLoc);
2940         if (SR.isInvalid() || SR.isUsable())
2941           return SR;
2942       }
2943 
2944       // Otherwise, emit diagnostics if we haven't already.
2945       if (RangeStatus == FRS_NoViableFunction) {
2946         Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2947         CandidateSet.NoteCandidates(
2948             PartialDiagnosticAt(Range->getBeginLoc(),
2949                                 PDiag(diag::err_for_range_invalid)
2950                                     << RangeLoc << Range->getType()
2951                                     << BEFFailure),
2952             *this, OCD_AllCandidates, Range);
2953       }
2954       // Return an error if no fix was discovered.
2955       if (RangeStatus != FRS_Success)
2956         return StmtError();
2957     }
2958 
2959     assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2960            "invalid range expression in for loop");
2961 
2962     // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2963     // C++1z removes this restriction.
2964     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2965     if (!Context.hasSameType(BeginType, EndType)) {
2966       Diag(RangeLoc, getLangOpts().CPlusPlus17
2967                          ? diag::warn_for_range_begin_end_types_differ
2968                          : diag::ext_for_range_begin_end_types_differ)
2969           << BeginType << EndType;
2970       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2971       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2972     }
2973 
2974     BeginDeclStmt =
2975         ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2976     EndDeclStmt =
2977         ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2978 
2979     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2980     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2981                                            VK_LValue, ColonLoc);
2982     if (BeginRef.isInvalid())
2983       return StmtError();
2984 
2985     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2986                                          VK_LValue, ColonLoc);
2987     if (EndRef.isInvalid())
2988       return StmtError();
2989 
2990     // Build and check __begin != __end expression.
2991     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2992                            BeginRef.get(), EndRef.get());
2993     if (!NotEqExpr.isInvalid())
2994       NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2995     if (!NotEqExpr.isInvalid())
2996       NotEqExpr =
2997           ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2998     if (NotEqExpr.isInvalid()) {
2999       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3000         << RangeLoc << 0 << BeginRangeRef.get()->getType();
3001       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
3002       if (!Context.hasSameType(BeginType, EndType))
3003         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
3004       return StmtError();
3005     }
3006 
3007     // Build and check ++__begin expression.
3008     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
3009                                 VK_LValue, ColonLoc);
3010     if (BeginRef.isInvalid())
3011       return StmtError();
3012 
3013     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
3014     if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
3015       // FIXME: getCurScope() should not be used during template instantiation.
3016       // We should pick up the set of unqualified lookup results for operator
3017       // co_await during the initial parse.
3018       IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
3019     if (!IncrExpr.isInvalid())
3020       IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
3021     if (IncrExpr.isInvalid()) {
3022       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3023         << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
3024       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
3025       return StmtError();
3026     }
3027 
3028     // Build and check *__begin  expression.
3029     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
3030                                 VK_LValue, ColonLoc);
3031     if (BeginRef.isInvalid())
3032       return StmtError();
3033 
3034     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
3035     if (DerefExpr.isInvalid()) {
3036       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3037         << RangeLoc << 1 << BeginRangeRef.get()->getType();
3038       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
3039       return StmtError();
3040     }
3041 
3042     // Attach  *__begin  as initializer for VD. Don't touch it if we're just
3043     // trying to determine whether this would be a valid range.
3044     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
3045       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
3046       if (LoopVar->isInvalidDecl() ||
3047           (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
3048         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
3049     }
3050   }
3051 
3052   // Don't bother to actually allocate the result if we're just trying to
3053   // determine whether it would be valid.
3054   if (Kind == BFRK_Check)
3055     return StmtResult();
3056 
3057   // In OpenMP loop region loop control variable must be private. Perform
3058   // analysis of first part (if any).
3059   if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
3060     ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
3061 
3062   return new (Context) CXXForRangeStmt(
3063       InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
3064       cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
3065       IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
3066       ColonLoc, RParenLoc);
3067 }
3068 
3069 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
3070 /// statement.
3071 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
3072   if (!S || !B)
3073     return StmtError();
3074   ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
3075 
3076   ForStmt->setBody(B);
3077   return S;
3078 }
3079 
3080 // Warn when the loop variable is a const reference that creates a copy.
3081 // Suggest using the non-reference type for copies.  If a copy can be prevented
3082 // suggest the const reference type that would do so.
3083 // For instance, given "for (const &Foo : Range)", suggest
3084 // "for (const Foo : Range)" to denote a copy is made for the loop.  If
3085 // possible, also suggest "for (const &Bar : Range)" if this type prevents
3086 // the copy altogether.
3087 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
3088                                                     const VarDecl *VD,
3089                                                     QualType RangeInitType) {
3090   const Expr *InitExpr = VD->getInit();
3091   if (!InitExpr)
3092     return;
3093 
3094   QualType VariableType = VD->getType();
3095 
3096   if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
3097     if (!Cleanups->cleanupsHaveSideEffects())
3098       InitExpr = Cleanups->getSubExpr();
3099 
3100   const MaterializeTemporaryExpr *MTE =
3101       dyn_cast<MaterializeTemporaryExpr>(InitExpr);
3102 
3103   // No copy made.
3104   if (!MTE)
3105     return;
3106 
3107   const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
3108 
3109   // Searching for either UnaryOperator for dereference of a pointer or
3110   // CXXOperatorCallExpr for handling iterators.
3111   while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
3112     if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
3113       E = CCE->getArg(0);
3114     } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
3115       const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
3116       E = ME->getBase();
3117     } else {
3118       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
3119       E = MTE->getSubExpr();
3120     }
3121     E = E->IgnoreImpCasts();
3122   }
3123 
3124   QualType ReferenceReturnType;
3125   if (isa<UnaryOperator>(E)) {
3126     ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
3127   } else {
3128     const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
3129     const FunctionDecl *FD = Call->getDirectCallee();
3130     QualType ReturnType = FD->getReturnType();
3131     if (ReturnType->isReferenceType())
3132       ReferenceReturnType = ReturnType;
3133   }
3134 
3135   if (!ReferenceReturnType.isNull()) {
3136     // Loop variable creates a temporary.  Suggest either to go with
3137     // non-reference loop variable to indicate a copy is made, or
3138     // the correct type to bind a const reference.
3139     SemaRef.Diag(VD->getLocation(),
3140                  diag::warn_for_range_const_ref_binds_temp_built_from_ref)
3141         << VD << VariableType << ReferenceReturnType;
3142     QualType NonReferenceType = VariableType.getNonReferenceType();
3143     NonReferenceType.removeLocalConst();
3144     QualType NewReferenceType =
3145         SemaRef.Context.getLValueReferenceType(E->getType().withConst());
3146     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
3147         << NonReferenceType << NewReferenceType << VD->getSourceRange()
3148         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3149   } else if (!VariableType->isRValueReferenceType()) {
3150     // The range always returns a copy, so a temporary is always created.
3151     // Suggest removing the reference from the loop variable.
3152     // If the type is a rvalue reference do not warn since that changes the
3153     // semantic of the code.
3154     SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
3155         << VD << RangeInitType;
3156     QualType NonReferenceType = VariableType.getNonReferenceType();
3157     NonReferenceType.removeLocalConst();
3158     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
3159         << NonReferenceType << VD->getSourceRange()
3160         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3161   }
3162 }
3163 
3164 /// Determines whether the @p VariableType's declaration is a record with the
3165 /// clang::trivial_abi attribute.
3166 static bool hasTrivialABIAttr(QualType VariableType) {
3167   if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3168     return RD->hasAttr<TrivialABIAttr>();
3169 
3170   return false;
3171 }
3172 
3173 // Warns when the loop variable can be changed to a reference type to
3174 // prevent a copy.  For instance, if given "for (const Foo x : Range)" suggest
3175 // "for (const Foo &x : Range)" if this form does not make a copy.
3176 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
3177                                                 const VarDecl *VD) {
3178   const Expr *InitExpr = VD->getInit();
3179   if (!InitExpr)
3180     return;
3181 
3182   QualType VariableType = VD->getType();
3183 
3184   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
3185     if (!CE->getConstructor()->isCopyConstructor())
3186       return;
3187   } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
3188     if (CE->getCastKind() != CK_LValueToRValue)
3189       return;
3190   } else {
3191     return;
3192   }
3193 
3194   // Small trivially copyable types are cheap to copy. Do not emit the
3195   // diagnostic for these instances. 64 bytes is a common size of a cache line.
3196   // (The function `getTypeSize` returns the size in bits.)
3197   ASTContext &Ctx = SemaRef.Context;
3198   if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
3199       (VariableType.isTriviallyCopyableType(Ctx) ||
3200        hasTrivialABIAttr(VariableType)))
3201     return;
3202 
3203   // Suggest changing from a const variable to a const reference variable
3204   // if doing so will prevent a copy.
3205   SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
3206       << VD << VariableType;
3207   SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
3208       << SemaRef.Context.getLValueReferenceType(VariableType)
3209       << VD->getSourceRange()
3210       << FixItHint::CreateInsertion(VD->getLocation(), "&");
3211 }
3212 
3213 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3214 /// 1) for (const foo &x : foos) where foos only returns a copy.  Suggest
3215 ///    using "const foo x" to show that a copy is made
3216 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3217 ///    Suggest either "const bar x" to keep the copying or "const foo& x" to
3218 ///    prevent the copy.
3219 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
3220 ///    Suggest "const foo &x" to prevent the copy.
3221 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
3222                                            const CXXForRangeStmt *ForStmt) {
3223   if (SemaRef.inTemplateInstantiation())
3224     return;
3225 
3226   if (SemaRef.Diags.isIgnored(
3227           diag::warn_for_range_const_ref_binds_temp_built_from_ref,
3228           ForStmt->getBeginLoc()) &&
3229       SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
3230                               ForStmt->getBeginLoc()) &&
3231       SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
3232                               ForStmt->getBeginLoc())) {
3233     return;
3234   }
3235 
3236   const VarDecl *VD = ForStmt->getLoopVariable();
3237   if (!VD)
3238     return;
3239 
3240   QualType VariableType = VD->getType();
3241 
3242   if (VariableType->isIncompleteType())
3243     return;
3244 
3245   const Expr *InitExpr = VD->getInit();
3246   if (!InitExpr)
3247     return;
3248 
3249   if (InitExpr->getExprLoc().isMacroID())
3250     return;
3251 
3252   if (VariableType->isReferenceType()) {
3253     DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
3254                                             ForStmt->getRangeInit()->getType());
3255   } else if (VariableType.isConstQualified()) {
3256     DiagnoseForRangeConstVariableCopies(SemaRef, VD);
3257   }
3258 }
3259 
3260 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
3261 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
3262 /// body cannot be performed until after the type of the range variable is
3263 /// determined.
3264 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
3265   if (!S || !B)
3266     return StmtError();
3267 
3268   if (isa<ObjCForCollectionStmt>(S))
3269     return FinishObjCForCollectionStmt(S, B);
3270 
3271   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
3272   ForStmt->setBody(B);
3273 
3274   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
3275                         diag::warn_empty_range_based_for_body);
3276 
3277   DiagnoseForRangeVariableCopies(*this, ForStmt);
3278 
3279   return S;
3280 }
3281 
3282 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
3283                                SourceLocation LabelLoc,
3284                                LabelDecl *TheDecl) {
3285   setFunctionHasBranchIntoScope();
3286   TheDecl->markUsed(Context);
3287   return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
3288 }
3289 
3290 StmtResult
3291 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
3292                             Expr *E) {
3293   // Convert operand to void*
3294   if (!E->isTypeDependent()) {
3295     QualType ETy = E->getType();
3296     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
3297     ExprResult ExprRes = E;
3298     AssignConvertType ConvTy =
3299       CheckSingleAssignmentConstraints(DestTy, ExprRes);
3300     if (ExprRes.isInvalid())
3301       return StmtError();
3302     E = ExprRes.get();
3303     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
3304       return StmtError();
3305   }
3306 
3307   ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
3308   if (ExprRes.isInvalid())
3309     return StmtError();
3310   E = ExprRes.get();
3311 
3312   setFunctionHasIndirectGoto();
3313 
3314   return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
3315 }
3316 
3317 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
3318                                      const Scope &DestScope) {
3319   if (!S.CurrentSEHFinally.empty() &&
3320       DestScope.Contains(*S.CurrentSEHFinally.back())) {
3321     S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
3322   }
3323 }
3324 
3325 StmtResult
3326 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
3327   Scope *S = CurScope->getContinueParent();
3328   if (!S) {
3329     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3330     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
3331   }
3332   if (S->isConditionVarScope()) {
3333     // We cannot 'continue;' from within a statement expression in the
3334     // initializer of a condition variable because we would jump past the
3335     // initialization of that variable.
3336     return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3337   }
3338   CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
3339 
3340   return new (Context) ContinueStmt(ContinueLoc);
3341 }
3342 
3343 StmtResult
3344 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
3345   Scope *S = CurScope->getBreakParent();
3346   if (!S) {
3347     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3348     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
3349   }
3350   if (S->isOpenMPLoopScope())
3351     return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
3352                      << "break");
3353   CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
3354 
3355   return new (Context) BreakStmt(BreakLoc);
3356 }
3357 
3358 /// Determine whether the given expression might be move-eligible or
3359 /// copy-elidable in either a (co_)return statement or throw expression,
3360 /// without considering function return type, if applicable.
3361 ///
3362 /// \param E The expression being returned from the function or block,
3363 /// being thrown, or being co_returned from a coroutine. This expression
3364 /// might be modified by the implementation.
3365 ///
3366 /// \param Mode Overrides detection of current language mode
3367 /// and uses the rules for C++2b.
3368 ///
3369 /// \returns An aggregate which contains the Candidate and isMoveEligible
3370 /// and isCopyElidable methods. If Candidate is non-null, it means
3371 /// isMoveEligible() would be true under the most permissive language standard.
3372 Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E,
3373                                                SimplerImplicitMoveMode Mode) {
3374   if (!E)
3375     return NamedReturnInfo();
3376   // - in a return statement in a function [where] ...
3377   // ... the expression is the name of a non-volatile automatic object ...
3378   const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
3379   if (!DR || DR->refersToEnclosingVariableOrCapture())
3380     return NamedReturnInfo();
3381   const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
3382   if (!VD)
3383     return NamedReturnInfo();
3384   NamedReturnInfo Res = getNamedReturnInfo(VD);
3385   if (Res.Candidate && !E->isXValue() &&
3386       (Mode == SimplerImplicitMoveMode::ForceOn ||
3387        (Mode != SimplerImplicitMoveMode::ForceOff &&
3388         getLangOpts().CPlusPlus2b))) {
3389     E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(),
3390                                  CK_NoOp, E, nullptr, VK_XValue,
3391                                  FPOptionsOverride());
3392   }
3393   return Res;
3394 }
3395 
3396 /// Determine whether the given NRVO candidate variable is move-eligible or
3397 /// copy-elidable, without considering function return type.
3398 ///
3399 /// \param VD The NRVO candidate variable.
3400 ///
3401 /// \returns An aggregate which contains the Candidate and isMoveEligible
3402 /// and isCopyElidable methods. If Candidate is non-null, it means
3403 /// isMoveEligible() would be true under the most permissive language standard.
3404 Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) {
3405   NamedReturnInfo Info{VD, NamedReturnInfo::MoveEligibleAndCopyElidable};
3406 
3407   // C++20 [class.copy.elision]p3:
3408   // - in a return statement in a function with ...
3409   // (other than a function ... parameter)
3410   if (VD->getKind() == Decl::ParmVar)
3411     Info.S = NamedReturnInfo::MoveEligible;
3412   else if (VD->getKind() != Decl::Var)
3413     return NamedReturnInfo();
3414 
3415   // (other than ... a catch-clause parameter)
3416   if (VD->isExceptionVariable())
3417     Info.S = NamedReturnInfo::MoveEligible;
3418 
3419   // ...automatic...
3420   if (!VD->hasLocalStorage())
3421     return NamedReturnInfo();
3422 
3423   // We don't want to implicitly move out of a __block variable during a return
3424   // because we cannot assume the variable will no longer be used.
3425   if (VD->hasAttr<BlocksAttr>())
3426     return NamedReturnInfo();
3427 
3428   QualType VDType = VD->getType();
3429   if (VDType->isObjectType()) {
3430     // C++17 [class.copy.elision]p3:
3431     // ...non-volatile automatic object...
3432     if (VDType.isVolatileQualified())
3433       return NamedReturnInfo();
3434   } else if (VDType->isRValueReferenceType()) {
3435     // C++20 [class.copy.elision]p3:
3436     // ...either a non-volatile object or an rvalue reference to a non-volatile
3437     // object type...
3438     QualType VDReferencedType = VDType.getNonReferenceType();
3439     if (VDReferencedType.isVolatileQualified() ||
3440         !VDReferencedType->isObjectType())
3441       return NamedReturnInfo();
3442     Info.S = NamedReturnInfo::MoveEligible;
3443   } else {
3444     return NamedReturnInfo();
3445   }
3446 
3447   // Variables with higher required alignment than their type's ABI
3448   // alignment cannot use NRVO.
3449   if (!VD->hasDependentAlignment() &&
3450       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType))
3451     Info.S = NamedReturnInfo::MoveEligible;
3452 
3453   return Info;
3454 }
3455 
3456 /// Updates given NamedReturnInfo's move-eligible and
3457 /// copy-elidable statuses, considering the function
3458 /// return type criteria as applicable to return statements.
3459 ///
3460 /// \param Info The NamedReturnInfo object to update.
3461 ///
3462 /// \param ReturnType This is the return type of the function.
3463 /// \returns The copy elision candidate, in case the initial return expression
3464 /// was copy elidable, or nullptr otherwise.
3465 const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info,
3466                                              QualType ReturnType) {
3467   if (!Info.Candidate)
3468     return nullptr;
3469 
3470   auto invalidNRVO = [&] {
3471     Info = NamedReturnInfo();
3472     return nullptr;
3473   };
3474 
3475   // If we got a non-deduced auto ReturnType, we are in a dependent context and
3476   // there is no point in allowing copy elision since we won't have it deduced
3477   // by the point the VardDecl is instantiated, which is the last chance we have
3478   // of deciding if the candidate is really copy elidable.
3479   if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3480        ReturnType->isCanonicalUnqualified()) ||
3481       ReturnType->isSpecificBuiltinType(BuiltinType::Dependent))
3482     return invalidNRVO();
3483 
3484   if (!ReturnType->isDependentType()) {
3485     // - in a return statement in a function with ...
3486     // ... a class return type ...
3487     if (!ReturnType->isRecordType())
3488       return invalidNRVO();
3489 
3490     QualType VDType = Info.Candidate->getType();
3491     // ... the same cv-unqualified type as the function return type ...
3492     // When considering moving this expression out, allow dissimilar types.
3493     if (!VDType->isDependentType() &&
3494         !Context.hasSameUnqualifiedType(ReturnType, VDType))
3495       Info.S = NamedReturnInfo::MoveEligible;
3496   }
3497   return Info.isCopyElidable() ? Info.Candidate : nullptr;
3498 }
3499 
3500 /// Verify that the initialization sequence that was picked for the
3501 /// first overload resolution is permissible under C++98.
3502 ///
3503 /// Reject (possibly converting) constructors not taking an rvalue reference,
3504 /// or user conversion operators which are not ref-qualified.
3505 static bool
3506 VerifyInitializationSequenceCXX98(const Sema &S,
3507                                   const InitializationSequence &Seq) {
3508   const auto *Step = llvm::find_if(Seq.steps(), [](const auto &Step) {
3509     return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3510            Step.Kind == InitializationSequence::SK_UserConversion;
3511   });
3512   if (Step != Seq.step_end()) {
3513     const auto *FD = Step->Function.Function;
3514     if (isa<CXXConstructorDecl>(FD)
3515             ? !FD->getParamDecl(0)->getType()->isRValueReferenceType()
3516             : cast<CXXMethodDecl>(FD)->getRefQualifier() == RQ_None)
3517       return false;
3518   }
3519   return true;
3520 }
3521 
3522 /// Perform the initialization of a potentially-movable value, which
3523 /// is the result of return value.
3524 ///
3525 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
3526 /// treat returned lvalues as rvalues in certain cases (to prefer move
3527 /// construction), then falls back to treating them as lvalues if that failed.
3528 ExprResult Sema::PerformMoveOrCopyInitialization(
3529     const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3530     bool SupressSimplerImplicitMoves) {
3531   if (getLangOpts().CPlusPlus &&
3532       (!getLangOpts().CPlusPlus2b || SupressSimplerImplicitMoves) &&
3533       NRInfo.isMoveEligible()) {
3534     ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3535                               CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3536     Expr *InitExpr = &AsRvalue;
3537     auto Kind = InitializationKind::CreateCopy(Value->getBeginLoc(),
3538                                                Value->getBeginLoc());
3539     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3540     auto Res = Seq.getFailedOverloadResult();
3541     if ((Res == OR_Success || Res == OR_Deleted) &&
3542         (getLangOpts().CPlusPlus11 ||
3543          VerifyInitializationSequenceCXX98(*this, Seq))) {
3544       // Promote "AsRvalue" to the heap, since we now need this
3545       // expression node to persist.
3546       Value =
3547           ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp, Value,
3548                                    nullptr, VK_XValue, FPOptionsOverride());
3549       // Complete type-checking the initialization of the return type
3550       // using the constructor we found.
3551       return Seq.Perform(*this, Entity, Kind, Value);
3552     }
3553   }
3554   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3555   // above, or overload resolution failed. Either way, we need to try
3556   // (again) now with the return value expression as written.
3557   return PerformCopyInitialization(Entity, SourceLocation(), Value);
3558 }
3559 
3560 /// Determine whether the declared return type of the specified function
3561 /// contains 'auto'.
3562 static bool hasDeducedReturnType(FunctionDecl *FD) {
3563   const FunctionProtoType *FPT =
3564       FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3565   return FPT->getReturnType()->isUndeducedType();
3566 }
3567 
3568 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3569 /// for capturing scopes.
3570 ///
3571 StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,
3572                                          Expr *RetValExp,
3573                                          NamedReturnInfo &NRInfo,
3574                                          bool SupressSimplerImplicitMoves) {
3575   // If this is the first return we've seen, infer the return type.
3576   // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3577   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3578   QualType FnRetType = CurCap->ReturnType;
3579   LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3580   bool HasDeducedReturnType =
3581       CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3582 
3583   if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3584       (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3585     if (RetValExp) {
3586       ExprResult ER =
3587           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3588       if (ER.isInvalid())
3589         return StmtError();
3590       RetValExp = ER.get();
3591     }
3592     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3593                               /* NRVOCandidate=*/nullptr);
3594   }
3595 
3596   if (HasDeducedReturnType) {
3597     FunctionDecl *FD = CurLambda->CallOperator;
3598     // If we've already decided this lambda is invalid, e.g. because
3599     // we saw a `return` whose expression had an error, don't keep
3600     // trying to deduce its return type.
3601     if (FD->isInvalidDecl())
3602       return StmtError();
3603     // In C++1y, the return type may involve 'auto'.
3604     // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3605     if (CurCap->ReturnType.isNull())
3606       CurCap->ReturnType = FD->getReturnType();
3607 
3608     AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3609     assert(AT && "lost auto type from lambda return type");
3610     if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3611       FD->setInvalidDecl();
3612       // FIXME: preserve the ill-formed return expression.
3613       return StmtError();
3614     }
3615     CurCap->ReturnType = FnRetType = FD->getReturnType();
3616   } else if (CurCap->HasImplicitReturnType) {
3617     // For blocks/lambdas with implicit return types, we check each return
3618     // statement individually, and deduce the common return type when the block
3619     // or lambda is completed.
3620     // FIXME: Fold this into the 'auto' codepath above.
3621     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3622       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3623       if (Result.isInvalid())
3624         return StmtError();
3625       RetValExp = Result.get();
3626 
3627       // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3628       // when deducing a return type for a lambda-expression (or by extension
3629       // for a block). These rules differ from the stated C++11 rules only in
3630       // that they remove top-level cv-qualifiers.
3631       if (!CurContext->isDependentContext())
3632         FnRetType = RetValExp->getType().getUnqualifiedType();
3633       else
3634         FnRetType = CurCap->ReturnType = Context.DependentTy;
3635     } else {
3636       if (RetValExp) {
3637         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3638         // initializer list, because it is not an expression (even
3639         // though we represent it as one). We still deduce 'void'.
3640         Diag(ReturnLoc, diag::err_lambda_return_init_list)
3641           << RetValExp->getSourceRange();
3642       }
3643 
3644       FnRetType = Context.VoidTy;
3645     }
3646 
3647     // Although we'll properly infer the type of the block once it's completed,
3648     // make sure we provide a return type now for better error recovery.
3649     if (CurCap->ReturnType.isNull())
3650       CurCap->ReturnType = FnRetType;
3651   }
3652   const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3653 
3654   if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3655     if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3656       Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3657       return StmtError();
3658     }
3659   } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3660     Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3661     return StmtError();
3662   } else {
3663     assert(CurLambda && "unknown kind of captured scope");
3664     if (CurLambda->CallOperator->getType()
3665             ->castAs<FunctionType>()
3666             ->getNoReturnAttr()) {
3667       Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3668       return StmtError();
3669     }
3670   }
3671 
3672   // Otherwise, verify that this result type matches the previous one.  We are
3673   // pickier with blocks than for normal functions because we don't have GCC
3674   // compatibility to worry about here.
3675   if (FnRetType->isDependentType()) {
3676     // Delay processing for now.  TODO: there are lots of dependent
3677     // types we can conclusively prove aren't void.
3678   } else if (FnRetType->isVoidType()) {
3679     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3680         !(getLangOpts().CPlusPlus &&
3681           (RetValExp->isTypeDependent() ||
3682            RetValExp->getType()->isVoidType()))) {
3683       if (!getLangOpts().CPlusPlus &&
3684           RetValExp->getType()->isVoidType())
3685         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3686       else {
3687         Diag(ReturnLoc, diag::err_return_block_has_expr);
3688         RetValExp = nullptr;
3689       }
3690     }
3691   } else if (!RetValExp) {
3692     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3693   } else if (!RetValExp->isTypeDependent()) {
3694     // we have a non-void block with an expression, continue checking
3695 
3696     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3697     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3698     // function return.
3699 
3700     // In C++ the return statement is handled via a copy initialization.
3701     // the C version of which boils down to CheckSingleAssignmentConstraints.
3702     InitializedEntity Entity =
3703         InitializedEntity::InitializeResult(ReturnLoc, FnRetType);
3704     ExprResult Res = PerformMoveOrCopyInitialization(
3705         Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
3706     if (Res.isInvalid()) {
3707       // FIXME: Cleanup temporaries here, anyway?
3708       return StmtError();
3709     }
3710     RetValExp = Res.get();
3711     CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3712   }
3713 
3714   if (RetValExp) {
3715     ExprResult ER =
3716         ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3717     if (ER.isInvalid())
3718       return StmtError();
3719     RetValExp = ER.get();
3720   }
3721   auto *Result =
3722       ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3723 
3724   // If we need to check for the named return value optimization,
3725   // or if we need to infer the return type,
3726   // save the return statement in our scope for later processing.
3727   if (CurCap->HasImplicitReturnType || NRVOCandidate)
3728     FunctionScopes.back()->Returns.push_back(Result);
3729 
3730   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3731     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3732 
3733   return Result;
3734 }
3735 
3736 namespace {
3737 /// Marks all typedefs in all local classes in a type referenced.
3738 ///
3739 /// In a function like
3740 /// auto f() {
3741 ///   struct S { typedef int a; };
3742 ///   return S();
3743 /// }
3744 ///
3745 /// the local type escapes and could be referenced in some TUs but not in
3746 /// others. Pretend that all local typedefs are always referenced, to not warn
3747 /// on this. This isn't necessary if f has internal linkage, or the typedef
3748 /// is private.
3749 class LocalTypedefNameReferencer
3750     : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3751 public:
3752   LocalTypedefNameReferencer(Sema &S) : S(S) {}
3753   bool VisitRecordType(const RecordType *RT);
3754 private:
3755   Sema &S;
3756 };
3757 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3758   auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3759   if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3760       R->isDependentType())
3761     return true;
3762   for (auto *TmpD : R->decls())
3763     if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3764       if (T->getAccess() != AS_private || R->hasFriends())
3765         S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3766   return true;
3767 }
3768 }
3769 
3770 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3771   return FD->getTypeSourceInfo()
3772       ->getTypeLoc()
3773       .getAsAdjusted<FunctionProtoTypeLoc>()
3774       .getReturnLoc();
3775 }
3776 
3777 /// Deduce the return type for a function from a returned expression, per
3778 /// C++1y [dcl.spec.auto]p6.
3779 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3780                                             SourceLocation ReturnLoc,
3781                                             Expr *RetExpr, const AutoType *AT) {
3782   // If this is the conversion function for a lambda, we choose to deduce its
3783   // type from the corresponding call operator, not from the synthesized return
3784   // statement within it. See Sema::DeduceReturnType.
3785   if (isLambdaConversionOperator(FD))
3786     return false;
3787 
3788   if (RetExpr && isa<InitListExpr>(RetExpr)) {
3789     //  If the deduction is for a return statement and the initializer is
3790     //  a braced-init-list, the program is ill-formed.
3791     Diag(RetExpr->getExprLoc(),
3792          getCurLambda() ? diag::err_lambda_return_init_list
3793                         : diag::err_auto_fn_return_init_list)
3794         << RetExpr->getSourceRange();
3795     return true;
3796   }
3797 
3798   if (FD->isDependentContext()) {
3799     // C++1y [dcl.spec.auto]p12:
3800     //   Return type deduction [...] occurs when the definition is
3801     //   instantiated even if the function body contains a return
3802     //   statement with a non-type-dependent operand.
3803     assert(AT->isDeduced() && "should have deduced to dependent type");
3804     return false;
3805   }
3806 
3807   TypeLoc OrigResultType = getReturnTypeLoc(FD);
3808   //  In the case of a return with no operand, the initializer is considered
3809   //  to be void().
3810   CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation());
3811   if (!RetExpr) {
3812     // For a function with a deduced result type to return with omitted
3813     // expression, the result type as written must be 'auto' or
3814     // 'decltype(auto)', possibly cv-qualified or constrained, but not
3815     // ref-qualified.
3816     if (!OrigResultType.getType()->getAs<AutoType>()) {
3817       Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3818           << OrigResultType.getType();
3819       return true;
3820     }
3821     RetExpr = &VoidVal;
3822   }
3823 
3824   QualType Deduced = AT->getDeducedType();
3825   {
3826     //  Otherwise, [...] deduce a value for U using the rules of template
3827     //  argument deduction.
3828     TemplateDeductionInfo Info(RetExpr->getExprLoc());
3829     TemplateDeductionResult Res =
3830         DeduceAutoType(OrigResultType, RetExpr, Deduced, Info);
3831     if (Res != TDK_Success && FD->isInvalidDecl())
3832       return true;
3833     switch (Res) {
3834     case TDK_Success:
3835       break;
3836     case TDK_AlreadyDiagnosed:
3837       return true;
3838     case TDK_Inconsistent: {
3839       //  If a function with a declared return type that contains a placeholder
3840       //  type has multiple return statements, the return type is deduced for
3841       //  each return statement. [...] if the type deduced is not the same in
3842       //  each deduction, the program is ill-formed.
3843       const LambdaScopeInfo *LambdaSI = getCurLambda();
3844       if (LambdaSI && LambdaSI->HasImplicitReturnType)
3845         Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3846             << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
3847       else
3848         Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3849             << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
3850             << Info.FirstArg;
3851       return true;
3852     }
3853     default:
3854       Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3855           << OrigResultType.getType() << RetExpr->getType();
3856       return true;
3857     }
3858   }
3859 
3860   // If a local type is part of the returned type, mark its fields as
3861   // referenced.
3862   LocalTypedefNameReferencer(*this).TraverseType(RetExpr->getType());
3863 
3864   // CUDA: Kernel function must have 'void' return type.
3865   if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
3866       !Deduced->isVoidType()) {
3867     Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3868         << FD->getType() << FD->getSourceRange();
3869     return true;
3870   }
3871 
3872   if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
3873     // Update all declarations of the function to have the deduced return type.
3874     Context.adjustDeducedFunctionResultType(FD, Deduced);
3875 
3876   return false;
3877 }
3878 
3879 StmtResult
3880 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3881                       Scope *CurScope) {
3882   // Correct typos, in case the containing function returns 'auto' and
3883   // RetValExp should determine the deduced type.
3884   ExprResult RetVal = CorrectDelayedTyposInExpr(
3885       RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true);
3886   if (RetVal.isInvalid())
3887     return StmtError();
3888   StmtResult R =
3889       BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true);
3890   if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
3891     return R;
3892 
3893   VarDecl *VD =
3894       const_cast<VarDecl *>(cast<ReturnStmt>(R.get())->getNRVOCandidate());
3895 
3896   CurScope->updateNRVOCandidate(VD);
3897 
3898   CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3899 
3900   return R;
3901 }
3902 
3903 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S,
3904                                                     const Expr *E) {
3905   if (!E || !S.getLangOpts().CPlusPlus2b || !S.getLangOpts().MSVCCompat)
3906     return false;
3907   const Decl *D = E->getReferencedDeclOfCallee();
3908   if (!D || !S.SourceMgr.isInSystemHeader(D->getLocation()))
3909     return false;
3910   for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
3911     if (DC->isStdNamespace())
3912       return true;
3913   }
3914   return false;
3915 }
3916 
3917 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3918                                  bool AllowRecovery) {
3919   // Check for unexpanded parameter packs.
3920   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3921     return StmtError();
3922 
3923   // HACK: We suppress simpler implicit move here in msvc compatibility mode
3924   // just as a temporary work around, as the MSVC STL has issues with
3925   // this change.
3926   bool SupressSimplerImplicitMoves =
3927       CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp);
3928   NamedReturnInfo NRInfo = getNamedReturnInfo(
3929       RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3930                                              : SimplerImplicitMoveMode::Normal);
3931 
3932   if (isa<CapturingScopeInfo>(getCurFunction()))
3933     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3934                                    SupressSimplerImplicitMoves);
3935 
3936   QualType FnRetType;
3937   QualType RelatedRetType;
3938   const AttrVec *Attrs = nullptr;
3939   bool isObjCMethod = false;
3940 
3941   if (const FunctionDecl *FD = getCurFunctionDecl()) {
3942     FnRetType = FD->getReturnType();
3943     if (FD->hasAttrs())
3944       Attrs = &FD->getAttrs();
3945     if (FD->isNoReturn())
3946       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
3947     if (FD->isMain() && RetValExp)
3948       if (isa<CXXBoolLiteralExpr>(RetValExp))
3949         Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3950             << RetValExp->getSourceRange();
3951     if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3952       if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
3953         if (RT->getDecl()->isOrContainsUnion())
3954           Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3955       }
3956     }
3957   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3958     FnRetType = MD->getReturnType();
3959     isObjCMethod = true;
3960     if (MD->hasAttrs())
3961       Attrs = &MD->getAttrs();
3962     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3963       // In the implementation of a method with a related return type, the
3964       // type used to type-check the validity of return statements within the
3965       // method body is a pointer to the type of the class being implemented.
3966       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3967       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3968     }
3969   } else // If we don't have a function/method context, bail.
3970     return StmtError();
3971 
3972   // C++1z: discarded return statements are not considered when deducing a
3973   // return type.
3974   if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3975       FnRetType->getContainedAutoType()) {
3976     if (RetValExp) {
3977       ExprResult ER =
3978           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3979       if (ER.isInvalid())
3980         return StmtError();
3981       RetValExp = ER.get();
3982     }
3983     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3984                               /* NRVOCandidate=*/nullptr);
3985   }
3986 
3987   // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3988   // deduction.
3989   if (getLangOpts().CPlusPlus14) {
3990     if (AutoType *AT = FnRetType->getContainedAutoType()) {
3991       FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3992       // If we've already decided this function is invalid, e.g. because
3993       // we saw a `return` whose expression had an error, don't keep
3994       // trying to deduce its return type.
3995       // (Some return values may be needlessly wrapped in RecoveryExpr).
3996       if (FD->isInvalidDecl() ||
3997           DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3998         FD->setInvalidDecl();
3999         if (!AllowRecovery)
4000           return StmtError();
4001         // The deduction failure is diagnosed and marked, try to recover.
4002         if (RetValExp) {
4003           // Wrap return value with a recovery expression of the previous type.
4004           // If no deduction yet, use DependentTy.
4005           auto Recovery = CreateRecoveryExpr(
4006               RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp,
4007               AT->isDeduced() ? FnRetType : QualType());
4008           if (Recovery.isInvalid())
4009             return StmtError();
4010           RetValExp = Recovery.get();
4011         } else {
4012           // Nothing to do: a ReturnStmt with no value is fine recovery.
4013         }
4014       } else {
4015         FnRetType = FD->getReturnType();
4016       }
4017     }
4018   }
4019   const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
4020 
4021   bool HasDependentReturnType = FnRetType->isDependentType();
4022 
4023   ReturnStmt *Result = nullptr;
4024   if (FnRetType->isVoidType()) {
4025     if (RetValExp) {
4026       if (auto *ILE = dyn_cast<InitListExpr>(RetValExp)) {
4027         // We simply never allow init lists as the return value of void
4028         // functions. This is compatible because this was never allowed before,
4029         // so there's no legacy code to deal with.
4030         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4031         int FunctionKind = 0;
4032         if (isa<ObjCMethodDecl>(CurDecl))
4033           FunctionKind = 1;
4034         else if (isa<CXXConstructorDecl>(CurDecl))
4035           FunctionKind = 2;
4036         else if (isa<CXXDestructorDecl>(CurDecl))
4037           FunctionKind = 3;
4038 
4039         Diag(ReturnLoc, diag::err_return_init_list)
4040             << CurDecl << FunctionKind << RetValExp->getSourceRange();
4041 
4042         // Preserve the initializers in the AST.
4043         RetValExp = AllowRecovery
4044                         ? CreateRecoveryExpr(ILE->getLBraceLoc(),
4045                                              ILE->getRBraceLoc(), ILE->inits())
4046                               .get()
4047                         : nullptr;
4048       } else if (!RetValExp->isTypeDependent()) {
4049         // C99 6.8.6.4p1 (ext_ since GCC warns)
4050         unsigned D = diag::ext_return_has_expr;
4051         if (RetValExp->getType()->isVoidType()) {
4052           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4053           if (isa<CXXConstructorDecl>(CurDecl) ||
4054               isa<CXXDestructorDecl>(CurDecl))
4055             D = diag::err_ctor_dtor_returns_void;
4056           else
4057             D = diag::ext_return_has_void_expr;
4058         }
4059         else {
4060           ExprResult Result = RetValExp;
4061           Result = IgnoredValueConversions(Result.get());
4062           if (Result.isInvalid())
4063             return StmtError();
4064           RetValExp = Result.get();
4065           RetValExp = ImpCastExprToType(RetValExp,
4066                                         Context.VoidTy, CK_ToVoid).get();
4067         }
4068         // return of void in constructor/destructor is illegal in C++.
4069         if (D == diag::err_ctor_dtor_returns_void) {
4070           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4071           Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl)
4072                              << RetValExp->getSourceRange();
4073         }
4074         // return (some void expression); is legal in C++.
4075         else if (D != diag::ext_return_has_void_expr ||
4076                  !getLangOpts().CPlusPlus) {
4077           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4078 
4079           int FunctionKind = 0;
4080           if (isa<ObjCMethodDecl>(CurDecl))
4081             FunctionKind = 1;
4082           else if (isa<CXXConstructorDecl>(CurDecl))
4083             FunctionKind = 2;
4084           else if (isa<CXXDestructorDecl>(CurDecl))
4085             FunctionKind = 3;
4086 
4087           Diag(ReturnLoc, D)
4088               << CurDecl << FunctionKind << RetValExp->getSourceRange();
4089         }
4090       }
4091 
4092       if (RetValExp) {
4093         ExprResult ER =
4094             ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4095         if (ER.isInvalid())
4096           return StmtError();
4097         RetValExp = ER.get();
4098       }
4099     }
4100 
4101     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
4102                                 /* NRVOCandidate=*/nullptr);
4103   } else if (!RetValExp && !HasDependentReturnType) {
4104     FunctionDecl *FD = getCurFunctionDecl();
4105 
4106     if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
4107       // The intended return type might have been "void", so don't warn.
4108     } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
4109       // C++11 [stmt.return]p2
4110       Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
4111           << FD << FD->isConsteval();
4112       FD->setInvalidDecl();
4113     } else {
4114       // C99 6.8.6.4p1 (ext_ since GCC warns)
4115       // C90 6.6.6.4p4
4116       unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4117                                           : diag::warn_return_missing_expr;
4118       // Note that at this point one of getCurFunctionDecl() or
4119       // getCurMethodDecl() must be non-null (see above).
4120       assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4121              "Not in a FunctionDecl or ObjCMethodDecl?");
4122       bool IsMethod = FD == nullptr;
4123       const NamedDecl *ND =
4124           IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD);
4125       Diag(ReturnLoc, DiagID) << ND << IsMethod;
4126     }
4127 
4128     Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
4129                                 /* NRVOCandidate=*/nullptr);
4130   } else {
4131     assert(RetValExp || HasDependentReturnType);
4132     QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
4133 
4134     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4135     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4136     // function return.
4137 
4138     // In C++ the return statement is handled via a copy initialization,
4139     // the C version of which boils down to CheckSingleAssignmentConstraints.
4140     if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
4141       // we have a non-void function with an expression, continue checking
4142       InitializedEntity Entity =
4143           InitializedEntity::InitializeResult(ReturnLoc, RetType);
4144       ExprResult Res = PerformMoveOrCopyInitialization(
4145           Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
4146       if (Res.isInvalid() && AllowRecovery)
4147         Res = CreateRecoveryExpr(RetValExp->getBeginLoc(),
4148                                  RetValExp->getEndLoc(), RetValExp, RetType);
4149       if (Res.isInvalid()) {
4150         // FIXME: Clean up temporaries here anyway?
4151         return StmtError();
4152       }
4153       RetValExp = Res.getAs<Expr>();
4154 
4155       // If we have a related result type, we need to implicitly
4156       // convert back to the formal result type.  We can't pretend to
4157       // initialize the result again --- we might end double-retaining
4158       // --- so instead we initialize a notional temporary.
4159       if (!RelatedRetType.isNull()) {
4160         Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
4161                                                             FnRetType);
4162         Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
4163         if (Res.isInvalid()) {
4164           // FIXME: Clean up temporaries here anyway?
4165           return StmtError();
4166         }
4167         RetValExp = Res.getAs<Expr>();
4168       }
4169 
4170       CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
4171                          getCurFunctionDecl());
4172     }
4173 
4174     if (RetValExp) {
4175       ExprResult ER =
4176           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4177       if (ER.isInvalid())
4178         return StmtError();
4179       RetValExp = ER.get();
4180     }
4181     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
4182   }
4183 
4184   // If we need to check for the named return value optimization, save the
4185   // return statement in our scope for later processing.
4186   if (Result->getNRVOCandidate())
4187     FunctionScopes.back()->Returns.push_back(Result);
4188 
4189   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4190     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4191 
4192   return Result;
4193 }
4194 
4195 StmtResult
4196 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
4197                            SourceLocation RParen, Decl *Parm,
4198                            Stmt *Body) {
4199   VarDecl *Var = cast_or_null<VarDecl>(Parm);
4200   if (Var && Var->isInvalidDecl())
4201     return StmtError();
4202 
4203   return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
4204 }
4205 
4206 StmtResult
4207 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
4208   return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
4209 }
4210 
4211 StmtResult
4212 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4213                          MultiStmtArg CatchStmts, Stmt *Finally) {
4214   if (!getLangOpts().ObjCExceptions)
4215     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
4216 
4217   // Objective-C try is incompatible with SEH __try.
4218   sema::FunctionScopeInfo *FSI = getCurFunction();
4219   if (FSI->FirstSEHTryLoc.isValid()) {
4220     Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
4221     Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4222   }
4223 
4224   FSI->setHasObjCTry(AtLoc);
4225   unsigned NumCatchStmts = CatchStmts.size();
4226   return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
4227                                NumCatchStmts, Finally);
4228 }
4229 
4230 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
4231   if (Throw) {
4232     ExprResult Result = DefaultLvalueConversion(Throw);
4233     if (Result.isInvalid())
4234       return StmtError();
4235 
4236     Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
4237     if (Result.isInvalid())
4238       return StmtError();
4239     Throw = Result.get();
4240 
4241     QualType ThrowType = Throw->getType();
4242     // Make sure the expression type is an ObjC pointer or "void *".
4243     if (!ThrowType->isDependentType() &&
4244         !ThrowType->isObjCObjectPointerType()) {
4245       const PointerType *PT = ThrowType->getAs<PointerType>();
4246       if (!PT || !PT->getPointeeType()->isVoidType())
4247         return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
4248                          << Throw->getType() << Throw->getSourceRange());
4249     }
4250   }
4251 
4252   return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
4253 }
4254 
4255 StmtResult
4256 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4257                            Scope *CurScope) {
4258   if (!getLangOpts().ObjCExceptions)
4259     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
4260 
4261   if (!Throw) {
4262     // @throw without an expression designates a rethrow (which must occur
4263     // in the context of an @catch clause).
4264     Scope *AtCatchParent = CurScope;
4265     while (AtCatchParent && !AtCatchParent->isAtCatchScope())
4266       AtCatchParent = AtCatchParent->getParent();
4267     if (!AtCatchParent)
4268       return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
4269   }
4270   return BuildObjCAtThrowStmt(AtLoc, Throw);
4271 }
4272 
4273 ExprResult
4274 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
4275   ExprResult result = DefaultLvalueConversion(operand);
4276   if (result.isInvalid())
4277     return ExprError();
4278   operand = result.get();
4279 
4280   // Make sure the expression type is an ObjC pointer or "void *".
4281   QualType type = operand->getType();
4282   if (!type->isDependentType() &&
4283       !type->isObjCObjectPointerType()) {
4284     const PointerType *pointerType = type->getAs<PointerType>();
4285     if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
4286       if (getLangOpts().CPlusPlus) {
4287         if (RequireCompleteType(atLoc, type,
4288                                 diag::err_incomplete_receiver_type))
4289           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4290                    << type << operand->getSourceRange();
4291 
4292         ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
4293         if (result.isInvalid())
4294           return ExprError();
4295         if (!result.isUsable())
4296           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4297                    << type << operand->getSourceRange();
4298 
4299         operand = result.get();
4300       } else {
4301           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4302                    << type << operand->getSourceRange();
4303       }
4304     }
4305   }
4306 
4307   // The operand to @synchronized is a full-expression.
4308   return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
4309 }
4310 
4311 StmtResult
4312 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
4313                                   Stmt *SyncBody) {
4314   // We can't jump into or indirect-jump out of a @synchronized block.
4315   setFunctionHasBranchProtectedScope();
4316   return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
4317 }
4318 
4319 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
4320 /// and creates a proper catch handler from them.
4321 StmtResult
4322 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
4323                          Stmt *HandlerBlock) {
4324   // There's nothing to test that ActOnExceptionDecl didn't already test.
4325   return new (Context)
4326       CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
4327 }
4328 
4329 StmtResult
4330 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
4331   setFunctionHasBranchProtectedScope();
4332   return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
4333 }
4334 
4335 namespace {
4336 class CatchHandlerType {
4337   QualType QT;
4338   unsigned IsPointer : 1;
4339 
4340   // This is a special constructor to be used only with DenseMapInfo's
4341   // getEmptyKey() and getTombstoneKey() functions.
4342   friend struct llvm::DenseMapInfo<CatchHandlerType>;
4343   enum Unique { ForDenseMap };
4344   CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
4345 
4346 public:
4347   /// Used when creating a CatchHandlerType from a handler type; will determine
4348   /// whether the type is a pointer or reference and will strip off the top
4349   /// level pointer and cv-qualifiers.
4350   CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4351     if (QT->isPointerType())
4352       IsPointer = true;
4353 
4354     if (IsPointer || QT->isReferenceType())
4355       QT = QT->getPointeeType();
4356     QT = QT.getUnqualifiedType();
4357   }
4358 
4359   /// Used when creating a CatchHandlerType from a base class type; pretends the
4360   /// type passed in had the pointer qualifier, does not need to get an
4361   /// unqualified type.
4362   CatchHandlerType(QualType QT, bool IsPointer)
4363       : QT(QT), IsPointer(IsPointer) {}
4364 
4365   QualType underlying() const { return QT; }
4366   bool isPointer() const { return IsPointer; }
4367 
4368   friend bool operator==(const CatchHandlerType &LHS,
4369                          const CatchHandlerType &RHS) {
4370     // If the pointer qualification does not match, we can return early.
4371     if (LHS.IsPointer != RHS.IsPointer)
4372       return false;
4373     // Otherwise, check the underlying type without cv-qualifiers.
4374     return LHS.QT == RHS.QT;
4375   }
4376 };
4377 } // namespace
4378 
4379 namespace llvm {
4380 template <> struct DenseMapInfo<CatchHandlerType> {
4381   static CatchHandlerType getEmptyKey() {
4382     return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4383                        CatchHandlerType::ForDenseMap);
4384   }
4385 
4386   static CatchHandlerType getTombstoneKey() {
4387     return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4388                        CatchHandlerType::ForDenseMap);
4389   }
4390 
4391   static unsigned getHashValue(const CatchHandlerType &Base) {
4392     return DenseMapInfo<QualType>::getHashValue(Base.underlying());
4393   }
4394 
4395   static bool isEqual(const CatchHandlerType &LHS,
4396                       const CatchHandlerType &RHS) {
4397     return LHS == RHS;
4398   }
4399 };
4400 }
4401 
4402 namespace {
4403 class CatchTypePublicBases {
4404   ASTContext &Ctx;
4405   const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
4406   const bool CheckAgainstPointer;
4407 
4408   CXXCatchStmt *FoundHandler;
4409   CanQualType FoundHandlerType;
4410 
4411 public:
4412   CatchTypePublicBases(
4413       ASTContext &Ctx,
4414       const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
4415       : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
4416         FoundHandler(nullptr) {}
4417 
4418   CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
4419   CanQualType getFoundHandlerType() const { return FoundHandlerType; }
4420 
4421   bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4422     if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4423       CatchHandlerType Check(S->getType(), CheckAgainstPointer);
4424       const auto &M = TypesToCheck;
4425       auto I = M.find(Check);
4426       if (I != M.end()) {
4427         FoundHandler = I->second;
4428         FoundHandlerType = Ctx.getCanonicalType(S->getType());
4429         return true;
4430       }
4431     }
4432     return false;
4433   }
4434 };
4435 }
4436 
4437 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4438 /// handlers and creates a try statement from them.
4439 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4440                                   ArrayRef<Stmt *> Handlers) {
4441   // Don't report an error if 'try' is used in system headers.
4442   if (!getLangOpts().CXXExceptions &&
4443       !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
4444     // Delay error emission for the OpenMP device code.
4445     targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4446   }
4447 
4448   // Exceptions aren't allowed in CUDA device code.
4449   if (getLangOpts().CUDA)
4450     CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4451         << "try" << CurrentCUDATarget();
4452 
4453   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4454     Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4455 
4456   sema::FunctionScopeInfo *FSI = getCurFunction();
4457 
4458   // C++ try is incompatible with SEH __try.
4459   if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4460     Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
4461     Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4462   }
4463 
4464   const unsigned NumHandlers = Handlers.size();
4465   assert(!Handlers.empty() &&
4466          "The parser shouldn't call this if there are no handlers.");
4467 
4468   llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4469   for (unsigned i = 0; i < NumHandlers; ++i) {
4470     CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4471 
4472     // Diagnose when the handler is a catch-all handler, but it isn't the last
4473     // handler for the try block. [except.handle]p5. Also, skip exception
4474     // declarations that are invalid, since we can't usefully report on them.
4475     if (!H->getExceptionDecl()) {
4476       if (i < NumHandlers - 1)
4477         return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4478       continue;
4479     } else if (H->getExceptionDecl()->isInvalidDecl())
4480       continue;
4481 
4482     // Walk the type hierarchy to diagnose when this type has already been
4483     // handled (duplication), or cannot be handled (derivation inversion). We
4484     // ignore top-level cv-qualifiers, per [except.handle]p3
4485     CatchHandlerType HandlerCHT =
4486         (QualType)Context.getCanonicalType(H->getCaughtType());
4487 
4488     // We can ignore whether the type is a reference or a pointer; we need the
4489     // underlying declaration type in order to get at the underlying record
4490     // decl, if there is one.
4491     QualType Underlying = HandlerCHT.underlying();
4492     if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4493       if (!RD->hasDefinition())
4494         continue;
4495       // Check that none of the public, unambiguous base classes are in the
4496       // map ([except.handle]p1). Give the base classes the same pointer
4497       // qualification as the original type we are basing off of. This allows
4498       // comparison against the handler type using the same top-level pointer
4499       // as the original type.
4500       CXXBasePaths Paths;
4501       Paths.setOrigin(RD);
4502       CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4503       if (RD->lookupInBases(CTPB, Paths)) {
4504         const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4505         if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4506           Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4507                diag::warn_exception_caught_by_earlier_handler)
4508               << H->getCaughtType();
4509           Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4510                 diag::note_previous_exception_handler)
4511               << Problem->getCaughtType();
4512         }
4513       }
4514     }
4515 
4516     // Add the type the list of ones we have handled; diagnose if we've already
4517     // handled it.
4518     auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4519     if (!R.second) {
4520       const CXXCatchStmt *Problem = R.first->second;
4521       Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4522            diag::warn_exception_caught_by_earlier_handler)
4523           << H->getCaughtType();
4524       Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4525            diag::note_previous_exception_handler)
4526           << Problem->getCaughtType();
4527     }
4528   }
4529 
4530   FSI->setHasCXXTry(TryLoc);
4531 
4532   return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4533 }
4534 
4535 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4536                                   Stmt *TryBlock, Stmt *Handler) {
4537   assert(TryBlock && Handler);
4538 
4539   sema::FunctionScopeInfo *FSI = getCurFunction();
4540 
4541   // SEH __try is incompatible with C++ try. Borland appears to support this,
4542   // however.
4543   if (!getLangOpts().Borland) {
4544     if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4545       Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4546       Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
4547           << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
4548                   ? "'try'"
4549                   : "'@try'");
4550     }
4551   }
4552 
4553   FSI->setHasSEHTry(TryLoc);
4554 
4555   // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4556   // track if they use SEH.
4557   DeclContext *DC = CurContext;
4558   while (DC && !DC->isFunctionOrMethod())
4559     DC = DC->getParent();
4560   FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4561   if (FD)
4562     FD->setUsesSEHTry(true);
4563   else
4564     Diag(TryLoc, diag::err_seh_try_outside_functions);
4565 
4566   // Reject __try on unsupported targets.
4567   if (!Context.getTargetInfo().isSEHTrySupported())
4568     Diag(TryLoc, diag::err_seh_try_unsupported);
4569 
4570   return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4571 }
4572 
4573 StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4574                                      Stmt *Block) {
4575   assert(FilterExpr && Block);
4576   QualType FTy = FilterExpr->getType();
4577   if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4578     return StmtError(
4579         Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4580         << FTy);
4581   }
4582   return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
4583 }
4584 
4585 void Sema::ActOnStartSEHFinallyBlock() {
4586   CurrentSEHFinally.push_back(CurScope);
4587 }
4588 
4589 void Sema::ActOnAbortSEHFinallyBlock() {
4590   CurrentSEHFinally.pop_back();
4591 }
4592 
4593 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4594   assert(Block);
4595   CurrentSEHFinally.pop_back();
4596   return SEHFinallyStmt::Create(Context, Loc, Block);
4597 }
4598 
4599 StmtResult
4600 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4601   Scope *SEHTryParent = CurScope;
4602   while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4603     SEHTryParent = SEHTryParent->getParent();
4604   if (!SEHTryParent)
4605     return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4606   CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4607 
4608   return new (Context) SEHLeaveStmt(Loc);
4609 }
4610 
4611 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4612                                             bool IsIfExists,
4613                                             NestedNameSpecifierLoc QualifierLoc,
4614                                             DeclarationNameInfo NameInfo,
4615                                             Stmt *Nested)
4616 {
4617   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4618                                              QualifierLoc, NameInfo,
4619                                              cast<CompoundStmt>(Nested));
4620 }
4621 
4622 
4623 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4624                                             bool IsIfExists,
4625                                             CXXScopeSpec &SS,
4626                                             UnqualifiedId &Name,
4627                                             Stmt *Nested) {
4628   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4629                                     SS.getWithLocInContext(Context),
4630                                     GetNameFromUnqualifiedId(Name),
4631                                     Nested);
4632 }
4633 
4634 RecordDecl*
4635 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4636                                    unsigned NumParams) {
4637   DeclContext *DC = CurContext;
4638   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4639     DC = DC->getParent();
4640 
4641   RecordDecl *RD = nullptr;
4642   if (getLangOpts().CPlusPlus)
4643     RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4644                                /*Id=*/nullptr);
4645   else
4646     RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4647 
4648   RD->setCapturedRecord();
4649   DC->addDecl(RD);
4650   RD->setImplicit();
4651   RD->startDefinition();
4652 
4653   assert(NumParams > 0 && "CapturedStmt requires context parameter");
4654   CD = CapturedDecl::Create(Context, CurContext, NumParams);
4655   DC->addDecl(CD);
4656   return RD;
4657 }
4658 
4659 static bool
4660 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4661                              SmallVectorImpl<CapturedStmt::Capture> &Captures,
4662                              SmallVectorImpl<Expr *> &CaptureInits) {
4663   for (const sema::Capture &Cap : RSI->Captures) {
4664     if (Cap.isInvalid())
4665       continue;
4666 
4667     // Form the initializer for the capture.
4668     ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4669                                          RSI->CapRegionKind == CR_OpenMP);
4670 
4671     // FIXME: Bail out now if the capture is not used and the initializer has
4672     // no side-effects.
4673 
4674     // Create a field for this capture.
4675     FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4676 
4677     // Add the capture to our list of captures.
4678     if (Cap.isThisCapture()) {
4679       Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4680                                                CapturedStmt::VCK_This));
4681     } else if (Cap.isVLATypeCapture()) {
4682       Captures.push_back(
4683           CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4684     } else {
4685       assert(Cap.isVariableCapture() && "unknown kind of capture");
4686 
4687       if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4688         S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
4689 
4690       Captures.push_back(CapturedStmt::Capture(
4691           Cap.getLocation(),
4692           Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4693                                    : CapturedStmt::VCK_ByCopy,
4694           cast<VarDecl>(Cap.getVariable())));
4695     }
4696     CaptureInits.push_back(Init.get());
4697   }
4698   return false;
4699 }
4700 
4701 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4702                                     CapturedRegionKind Kind,
4703                                     unsigned NumParams) {
4704   CapturedDecl *CD = nullptr;
4705   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4706 
4707   // Build the context parameter
4708   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4709   IdentifierInfo *ParamName = &Context.Idents.get("__context");
4710   QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4711   auto *Param =
4712       ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4713                                 ImplicitParamDecl::CapturedContext);
4714   DC->addDecl(Param);
4715 
4716   CD->setContextParam(0, Param);
4717 
4718   // Enter the capturing scope for this captured region.
4719   PushCapturedRegionScope(CurScope, CD, RD, Kind);
4720 
4721   if (CurScope)
4722     PushDeclContext(CurScope, CD);
4723   else
4724     CurContext = CD;
4725 
4726   PushExpressionEvaluationContext(
4727       ExpressionEvaluationContext::PotentiallyEvaluated);
4728 }
4729 
4730 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4731                                     CapturedRegionKind Kind,
4732                                     ArrayRef<CapturedParamNameType> Params,
4733                                     unsigned OpenMPCaptureLevel) {
4734   CapturedDecl *CD = nullptr;
4735   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4736 
4737   // Build the context parameter
4738   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4739   bool ContextIsFound = false;
4740   unsigned ParamNum = 0;
4741   for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4742                                                  E = Params.end();
4743        I != E; ++I, ++ParamNum) {
4744     if (I->second.isNull()) {
4745       assert(!ContextIsFound &&
4746              "null type has been found already for '__context' parameter");
4747       IdentifierInfo *ParamName = &Context.Idents.get("__context");
4748       QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4749                                .withConst()
4750                                .withRestrict();
4751       auto *Param =
4752           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4753                                     ImplicitParamDecl::CapturedContext);
4754       DC->addDecl(Param);
4755       CD->setContextParam(ParamNum, Param);
4756       ContextIsFound = true;
4757     } else {
4758       IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4759       auto *Param =
4760           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4761                                     ImplicitParamDecl::CapturedContext);
4762       DC->addDecl(Param);
4763       CD->setParam(ParamNum, Param);
4764     }
4765   }
4766   assert(ContextIsFound && "no null type for '__context' parameter");
4767   if (!ContextIsFound) {
4768     // Add __context implicitly if it is not specified.
4769     IdentifierInfo *ParamName = &Context.Idents.get("__context");
4770     QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4771     auto *Param =
4772         ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4773                                   ImplicitParamDecl::CapturedContext);
4774     DC->addDecl(Param);
4775     CD->setContextParam(ParamNum, Param);
4776   }
4777   // Enter the capturing scope for this captured region.
4778   PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
4779 
4780   if (CurScope)
4781     PushDeclContext(CurScope, CD);
4782   else
4783     CurContext = CD;
4784 
4785   PushExpressionEvaluationContext(
4786       ExpressionEvaluationContext::PotentiallyEvaluated);
4787 }
4788 
4789 void Sema::ActOnCapturedRegionError() {
4790   DiscardCleanupsInEvaluationContext();
4791   PopExpressionEvaluationContext();
4792   PopDeclContext();
4793   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4794   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4795 
4796   RecordDecl *Record = RSI->TheRecordDecl;
4797   Record->setInvalidDecl();
4798 
4799   SmallVector<Decl*, 4> Fields(Record->fields());
4800   ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4801               SourceLocation(), SourceLocation(), ParsedAttributesView());
4802 }
4803 
4804 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4805   // Leave the captured scope before we start creating captures in the
4806   // enclosing scope.
4807   DiscardCleanupsInEvaluationContext();
4808   PopExpressionEvaluationContext();
4809   PopDeclContext();
4810   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4811   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4812 
4813   SmallVector<CapturedStmt::Capture, 4> Captures;
4814   SmallVector<Expr *, 4> CaptureInits;
4815   if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4816     return StmtError();
4817 
4818   CapturedDecl *CD = RSI->TheCapturedDecl;
4819   RecordDecl *RD = RSI->TheRecordDecl;
4820 
4821   CapturedStmt *Res = CapturedStmt::Create(
4822       getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4823       Captures, CaptureInits, CD, RD);
4824 
4825   CD->setBody(Res->getCapturedStmt());
4826   RD->completeDefinition();
4827 
4828   return Res;
4829 }
4830