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