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