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