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