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