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