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