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