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