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