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