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