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