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