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