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