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