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