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