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