SemaStmt.cpp revision d226f65006733ed7f709c3174f22ce33391cb58f
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/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/StmtObjC.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/TypeLoc.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVector.h"
28using namespace clang;
29
30Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
31  Expr *E = expr->takeAs<Expr>();
32  assert(E && "ActOnExprStmt(): missing expression");
33  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
34  // void expression for its side effects.  Conversion to void allows any
35  // operand, even incomplete types.
36
37  // Same thing in for stmt first clause (when expr) and third clause.
38  return Owned(static_cast<Stmt*>(E));
39}
40
41
42Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
43  return Owned(new (Context) NullStmt(SemiLoc));
44}
45
46Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
47                                           SourceLocation StartLoc,
48                                           SourceLocation EndLoc) {
49  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
50
51  // If we have an invalid decl, just return an error.
52  if (DG.isNull()) return StmtError();
53
54  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
55}
56
57void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
58  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
59
60  // If we have an invalid decl, just return.
61  if (DG.isNull() || !DG.isSingleDecl()) return;
62  // suppress any potential 'unused variable' warning.
63  DG.getSingleDecl()->setUsed();
64}
65
66void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
67  const Expr *E = dyn_cast_or_null<Expr>(S);
68  if (!E)
69    return;
70
71  SourceLocation Loc;
72  SourceRange R1, R2;
73  if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
74    return;
75
76  // Okay, we have an unused result.  Depending on what the base expression is,
77  // we might want to make a more specific diagnostic.  Check for one of these
78  // cases now.
79  unsigned DiagID = diag::warn_unused_expr;
80  E = E->IgnoreParens();
81  if (isa<ObjCImplicitSetterGetterRefExpr>(E))
82    DiagID = diag::warn_unused_property_expr;
83
84  if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E))
85    E = Temps->getSubExpr();
86
87  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
88    if (E->getType()->isVoidType())
89      return;
90
91    // If the callee has attribute pure, const, or warn_unused_result, warn with
92    // a more specific message to make it clear what is happening.
93    if (const Decl *FD = CE->getCalleeDecl()) {
94      if (FD->getAttr<WarnUnusedResultAttr>()) {
95        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
96        return;
97      }
98      if (FD->getAttr<PureAttr>()) {
99        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
100        return;
101      }
102      if (FD->getAttr<ConstAttr>()) {
103        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
104        return;
105      }
106    }
107  }
108  else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
109    const ObjCMethodDecl *MD = ME->getMethodDecl();
110    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
111      Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
112      return;
113    }
114  } else if (const CXXFunctionalCastExpr *FC
115                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
116    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
117        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
118      return;
119  }
120  // Diagnose "(void*) blah" as a typo for "(void) blah".
121  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
122    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
123    QualType T = TI->getType();
124
125    // We really do want to use the non-canonical type here.
126    if (T == Context.VoidPtrTy) {
127      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
128
129      Diag(Loc, diag::warn_unused_voidptr)
130        << FixItHint::CreateRemoval(TL.getStarLoc());
131      return;
132    }
133  }
134
135  DiagRuntimeBehavior(Loc, PDiag(DiagID) << R1 << R2);
136}
137
138Action::OwningStmtResult
139Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
140                        MultiStmtArg elts, bool isStmtExpr) {
141  unsigned NumElts = elts.size();
142  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
143  // If we're in C89 mode, check that we don't have any decls after stmts.  If
144  // so, emit an extension diagnostic.
145  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
146    // Note that __extension__ can be around a decl.
147    unsigned i = 0;
148    // Skip over all declarations.
149    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
150      /*empty*/;
151
152    // We found the end of the list or a statement.  Scan for another declstmt.
153    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
154      /*empty*/;
155
156    if (i != NumElts) {
157      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
158      Diag(D->getLocation(), diag::ext_mixed_decls_code);
159    }
160  }
161  // Warn about unused expressions in statements.
162  for (unsigned i = 0; i != NumElts; ++i) {
163    // Ignore statements that are last in a statement expression.
164    if (isStmtExpr && i == NumElts - 1)
165      continue;
166
167    DiagnoseUnusedExprResult(Elts[i]);
168  }
169
170  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
171}
172
173Action::OwningStmtResult
174Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
175                    SourceLocation DotDotDotLoc, ExprArg rhsval,
176                    SourceLocation ColonLoc) {
177  assert((lhsval.get() != 0) && "missing expression in case statement");
178
179  // C99 6.8.4.2p3: The expression shall be an integer constant.
180  // However, GCC allows any evaluatable integer expression.
181  Expr *LHSVal = static_cast<Expr*>(lhsval.get());
182  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
183      VerifyIntegerConstantExpression(LHSVal))
184    return StmtError();
185
186  // GCC extension: The expression shall be an integer constant.
187
188  Expr *RHSVal = static_cast<Expr*>(rhsval.get());
189  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
190      VerifyIntegerConstantExpression(RHSVal)) {
191    RHSVal = 0;  // Recover by just forgetting about it.
192    rhsval = 0;
193  }
194
195  if (getSwitchStack().empty()) {
196    Diag(CaseLoc, diag::err_case_not_in_switch);
197    return StmtError();
198  }
199
200  // Only now release the smart pointers.
201  lhsval.release();
202  rhsval.release();
203  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
204                                        ColonLoc);
205  getSwitchStack().back()->addSwitchCase(CS);
206  return Owned(CS);
207}
208
209/// ActOnCaseStmtBody - This installs a statement as the body of a case.
210void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
211  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
212  Stmt *SubStmt = subStmt.takeAs<Stmt>();
213  CS->setSubStmt(SubStmt);
214}
215
216Action::OwningStmtResult
217Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
218                       StmtArg subStmt, Scope *CurScope) {
219  Stmt *SubStmt = subStmt.takeAs<Stmt>();
220
221  if (getSwitchStack().empty()) {
222    Diag(DefaultLoc, diag::err_default_not_in_switch);
223    return Owned(SubStmt);
224  }
225
226  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
227  getSwitchStack().back()->addSwitchCase(DS);
228  return Owned(DS);
229}
230
231Action::OwningStmtResult
232Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
233                     SourceLocation ColonLoc, StmtArg subStmt) {
234  Stmt *SubStmt = subStmt.takeAs<Stmt>();
235  // Look up the record for this label identifier.
236  LabelStmt *&LabelDecl = getLabelMap()[II];
237
238  // If not forward referenced or defined already, just create a new LabelStmt.
239  if (LabelDecl == 0)
240    return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
241
242  assert(LabelDecl->getID() == II && "Label mismatch!");
243
244  // Otherwise, this label was either forward reference or multiply defined.  If
245  // multiply defined, reject it now.
246  if (LabelDecl->getSubStmt()) {
247    Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
248    Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
249    return Owned(SubStmt);
250  }
251
252  // Otherwise, this label was forward declared, and we just found its real
253  // definition.  Fill in the forward definition and return it.
254  LabelDecl->setIdentLoc(IdentLoc);
255  LabelDecl->setSubStmt(SubStmt);
256  return Owned(LabelDecl);
257}
258
259Action::OwningStmtResult
260Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
261                  StmtArg ThenVal, SourceLocation ElseLoc,
262                  StmtArg ElseVal) {
263  OwningExprResult CondResult(CondVal.release());
264
265  VarDecl *ConditionVar = 0;
266  if (CondVar) {
267    ConditionVar = cast<VarDecl>(CondVar);
268    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
269    if (CondResult.isInvalid())
270      return StmtError();
271  }
272  Expr *ConditionExpr = CondResult.takeAs<Expr>();
273  if (!ConditionExpr)
274    return StmtError();
275
276  Stmt *thenStmt = ThenVal.takeAs<Stmt>();
277  DiagnoseUnusedExprResult(thenStmt);
278
279  // Warn if the if block has a null body without an else value.
280  // this helps prevent bugs due to typos, such as
281  // if (condition);
282  //   do_stuff();
283  if (!ElseVal.get()) {
284    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
285      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
286  }
287
288  Stmt *elseStmt = ElseVal.takeAs<Stmt>();
289  DiagnoseUnusedExprResult(elseStmt);
290
291  CondResult.release();
292  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
293                                    thenStmt, ElseLoc, elseStmt));
294}
295
296/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
297/// the specified width and sign.  If an overflow occurs, detect it and emit
298/// the specified diagnostic.
299void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
300                                              unsigned NewWidth, bool NewSign,
301                                              SourceLocation Loc,
302                                              unsigned DiagID) {
303  // Perform a conversion to the promoted condition type if needed.
304  if (NewWidth > Val.getBitWidth()) {
305    // If this is an extension, just do it.
306    Val.extend(NewWidth);
307    Val.setIsSigned(NewSign);
308
309    // If the input was signed and negative and the output is
310    // unsigned, don't bother to warn: this is implementation-defined
311    // behavior.
312    // FIXME: Introduce a second, default-ignored warning for this case?
313  } else if (NewWidth < Val.getBitWidth()) {
314    // If this is a truncation, check for overflow.
315    llvm::APSInt ConvVal(Val);
316    ConvVal.trunc(NewWidth);
317    ConvVal.setIsSigned(NewSign);
318    ConvVal.extend(Val.getBitWidth());
319    ConvVal.setIsSigned(Val.isSigned());
320    if (ConvVal != Val)
321      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
322
323    // Regardless of whether a diagnostic was emitted, really do the
324    // truncation.
325    Val.trunc(NewWidth);
326    Val.setIsSigned(NewSign);
327  } else if (NewSign != Val.isSigned()) {
328    // Convert the sign to match the sign of the condition.  This can cause
329    // overflow as well: unsigned(INTMIN)
330    // We don't diagnose this overflow, because it is implementation-defined
331    // behavior.
332    // FIXME: Introduce a second, default-ignored warning for this case?
333    llvm::APSInt OldVal(Val);
334    Val.setIsSigned(NewSign);
335  }
336}
337
338namespace {
339  struct CaseCompareFunctor {
340    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
341                    const llvm::APSInt &RHS) {
342      return LHS.first < RHS;
343    }
344    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
345                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
346      return LHS.first < RHS.first;
347    }
348    bool operator()(const llvm::APSInt &LHS,
349                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
350      return LHS < RHS.first;
351    }
352  };
353}
354
355/// CmpCaseVals - Comparison predicate for sorting case values.
356///
357static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
358                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
359  if (lhs.first < rhs.first)
360    return true;
361
362  if (lhs.first == rhs.first &&
363      lhs.second->getCaseLoc().getRawEncoding()
364       < rhs.second->getCaseLoc().getRawEncoding())
365    return true;
366  return false;
367}
368
369/// CmpEnumVals - Comparison predicate for sorting enumeration values.
370///
371static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
372                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
373{
374  return lhs.first < rhs.first;
375}
376
377/// EqEnumVals - Comparison preficate for uniqing enumeration values.
378///
379static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
380                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
381{
382  return lhs.first == rhs.first;
383}
384
385/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
386/// potentially integral-promoted expression @p expr.
387static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
388  if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
389    const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
390    QualType TypeBeforePromotion = ExprBeforePromotion->getType();
391    if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
392      return TypeBeforePromotion;
393    }
394  }
395  return expr->getType();
396}
397
398Action::OwningStmtResult
399Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, ExprArg Cond,
400                             Decl *CondVar) {
401  VarDecl *ConditionVar = 0;
402  if (CondVar) {
403    ConditionVar = cast<VarDecl>(CondVar);
404    OwningExprResult CondE = CheckConditionVariable(ConditionVar, SourceLocation(), false);
405    if (CondE.isInvalid())
406      return StmtError();
407
408    Cond = move(CondE);
409  }
410
411  if (!Cond.get())
412    return StmtError();
413
414  Expr *CondExpr = static_cast<Expr *>(Cond.get());
415  OwningExprResult ConvertedCond
416    = ConvertToIntegralOrEnumerationType(SwitchLoc, move(Cond),
417                          PDiag(diag::err_typecheck_statement_requires_integer),
418                                   PDiag(diag::err_switch_incomplete_class_type)
419                                     << CondExpr->getSourceRange(),
420                                   PDiag(diag::err_switch_explicit_conversion),
421                                         PDiag(diag::note_switch_conversion),
422                                   PDiag(diag::err_switch_multiple_conversions),
423                                         PDiag(diag::note_switch_conversion),
424                                         PDiag(0));
425  if (ConvertedCond.isInvalid())
426    return StmtError();
427
428  CondExpr = ConvertedCond.takeAs<Expr>();
429
430  if (!CondVar) {
431    CondExpr = MaybeCreateCXXExprWithTemporaries(CondExpr);
432    if (!CondExpr)
433      return StmtError();
434  }
435
436  setFunctionHasBranchIntoScope();
437
438  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, CondExpr);
439  getSwitchStack().push_back(SS);
440  return Owned(SS);
441}
442
443Action::OwningStmtResult
444Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
445                            StmtArg Body) {
446  Stmt *BodyStmt = Body.takeAs<Stmt>();
447
448  SwitchStmt *SS = getSwitchStack().back();
449  assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
450
451  SS->setBody(BodyStmt, SwitchLoc);
452  getSwitchStack().pop_back();
453
454  if (SS->getCond() == 0)
455    return StmtError();
456
457  Expr *CondExpr = SS->getCond();
458  Expr *CondExprBeforePromotion = CondExpr;
459  QualType CondTypeBeforePromotion =
460      GetTypeBeforeIntegralPromotion(CondExpr);
461
462  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
463  UsualUnaryConversions(CondExpr);
464  QualType CondType = CondExpr->getType();
465  SS->setCond(CondExpr);
466
467  // C++ 6.4.2.p2:
468  // Integral promotions are performed (on the switch condition).
469  //
470  // A case value unrepresentable by the original switch condition
471  // type (before the promotion) doesn't make sense, even when it can
472  // be represented by the promoted type.  Therefore we need to find
473  // the pre-promotion type of the switch condition.
474  if (!CondExpr->isTypeDependent()) {
475    // We have already converted the expression to an integral or enumeration
476    // type, when we started the switch statement. If we don't have an
477    // appropriate type now, just return an error.
478    if (!CondType->isIntegralOrEnumerationType())
479      return StmtError();
480
481    if (CondExpr->isKnownToHaveBooleanValue()) {
482      // switch(bool_expr) {...} is often a programmer error, e.g.
483      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
484      // One can always use an if statement instead of switch(bool_expr).
485      Diag(SwitchLoc, diag::warn_bool_switch_condition)
486          << CondExpr->getSourceRange();
487    }
488  }
489
490  // Get the bitwidth of the switched-on value before promotions.  We must
491  // convert the integer case values to this width before comparison.
492  bool HasDependentValue
493    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
494  unsigned CondWidth
495    = HasDependentValue? 0
496      : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
497  bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
498
499  // Accumulate all of the case values in a vector so that we can sort them
500  // and detect duplicates.  This vector contains the APInt for the case after
501  // it has been converted to the condition type.
502  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
503  CaseValsTy CaseVals;
504
505  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
506  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
507  CaseRangesTy CaseRanges;
508
509  DefaultStmt *TheDefaultStmt = 0;
510
511  bool CaseListIsErroneous = false;
512
513  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
514       SC = SC->getNextSwitchCase()) {
515
516    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
517      if (TheDefaultStmt) {
518        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
519        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
520
521        // FIXME: Remove the default statement from the switch block so that
522        // we'll return a valid AST.  This requires recursing down the AST and
523        // finding it, not something we are set up to do right now.  For now,
524        // just lop the entire switch stmt out of the AST.
525        CaseListIsErroneous = true;
526      }
527      TheDefaultStmt = DS;
528
529    } else {
530      CaseStmt *CS = cast<CaseStmt>(SC);
531
532      // We already verified that the expression has a i-c-e value (C99
533      // 6.8.4.2p3) - get that value now.
534      Expr *Lo = CS->getLHS();
535
536      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
537        HasDependentValue = true;
538        break;
539      }
540
541      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
542
543      // Convert the value to the same width/sign as the condition.
544      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
545                                         CS->getLHS()->getLocStart(),
546                                         diag::warn_case_value_overflow);
547
548      // If the LHS is not the same type as the condition, insert an implicit
549      // cast.
550      ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast);
551      CS->setLHS(Lo);
552
553      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
554      if (CS->getRHS()) {
555        if (CS->getRHS()->isTypeDependent() ||
556            CS->getRHS()->isValueDependent()) {
557          HasDependentValue = true;
558          break;
559        }
560        CaseRanges.push_back(std::make_pair(LoVal, CS));
561      } else
562        CaseVals.push_back(std::make_pair(LoVal, CS));
563    }
564  }
565
566  if (!HasDependentValue) {
567    // If we don't have a default statement, check whether the
568    // condition is constant.
569    llvm::APSInt ConstantCondValue;
570    bool HasConstantCond = false;
571    bool ShouldCheckConstantCond = false;
572    if (!HasDependentValue && !TheDefaultStmt) {
573      Expr::EvalResult Result;
574      HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
575      if (HasConstantCond) {
576        assert(Result.Val.isInt() && "switch condition evaluated to non-int");
577        ConstantCondValue = Result.Val.getInt();
578        ShouldCheckConstantCond = true;
579
580        assert(ConstantCondValue.getBitWidth() == CondWidth &&
581               ConstantCondValue.isSigned() == CondIsSigned);
582      }
583    }
584
585    // Sort all the scalar case values so we can easily detect duplicates.
586    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
587
588    if (!CaseVals.empty()) {
589      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
590        if (ShouldCheckConstantCond &&
591            CaseVals[i].first == ConstantCondValue)
592          ShouldCheckConstantCond = false;
593
594        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
595          // If we have a duplicate, report it.
596          Diag(CaseVals[i].second->getLHS()->getLocStart(),
597               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
598          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
599               diag::note_duplicate_case_prev);
600          // FIXME: We really want to remove the bogus case stmt from the
601          // substmt, but we have no way to do this right now.
602          CaseListIsErroneous = true;
603        }
604      }
605    }
606
607    // Detect duplicate case ranges, which usually don't exist at all in
608    // the first place.
609    if (!CaseRanges.empty()) {
610      // Sort all the case ranges by their low value so we can easily detect
611      // overlaps between ranges.
612      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
613
614      // Scan the ranges, computing the high values and removing empty ranges.
615      std::vector<llvm::APSInt> HiVals;
616      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
617        llvm::APSInt &LoVal = CaseRanges[i].first;
618        CaseStmt *CR = CaseRanges[i].second;
619        Expr *Hi = CR->getRHS();
620        llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
621
622        // Convert the value to the same width/sign as the condition.
623        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
624                                           CR->getRHS()->getLocStart(),
625                                           diag::warn_case_value_overflow);
626
627        // If the LHS is not the same type as the condition, insert an implicit
628        // cast.
629        ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast);
630        CR->setRHS(Hi);
631
632        // If the low value is bigger than the high value, the case is empty.
633        if (LoVal > HiVal) {
634          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
635            << SourceRange(CR->getLHS()->getLocStart(),
636                           CR->getRHS()->getLocEnd());
637          CaseRanges.erase(CaseRanges.begin()+i);
638          --i, --e;
639          continue;
640        }
641
642        if (ShouldCheckConstantCond &&
643            LoVal <= ConstantCondValue &&
644            ConstantCondValue <= HiVal)
645          ShouldCheckConstantCond = false;
646
647        HiVals.push_back(HiVal);
648      }
649
650      // Rescan the ranges, looking for overlap with singleton values and other
651      // ranges.  Since the range list is sorted, we only need to compare case
652      // ranges with their neighbors.
653      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
654        llvm::APSInt &CRLo = CaseRanges[i].first;
655        llvm::APSInt &CRHi = HiVals[i];
656        CaseStmt *CR = CaseRanges[i].second;
657
658        // Check to see whether the case range overlaps with any
659        // singleton cases.
660        CaseStmt *OverlapStmt = 0;
661        llvm::APSInt OverlapVal(32);
662
663        // Find the smallest value >= the lower bound.  If I is in the
664        // case range, then we have overlap.
665        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
666                                                  CaseVals.end(), CRLo,
667                                                  CaseCompareFunctor());
668        if (I != CaseVals.end() && I->first < CRHi) {
669          OverlapVal  = I->first;   // Found overlap with scalar.
670          OverlapStmt = I->second;
671        }
672
673        // Find the smallest value bigger than the upper bound.
674        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
675        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
676          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
677          OverlapStmt = (I-1)->second;
678        }
679
680        // Check to see if this case stmt overlaps with the subsequent
681        // case range.
682        if (i && CRLo <= HiVals[i-1]) {
683          OverlapVal  = HiVals[i-1];       // Found overlap with range.
684          OverlapStmt = CaseRanges[i-1].second;
685        }
686
687        if (OverlapStmt) {
688          // If we have a duplicate, report it.
689          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
690            << OverlapVal.toString(10);
691          Diag(OverlapStmt->getLHS()->getLocStart(),
692               diag::note_duplicate_case_prev);
693          // FIXME: We really want to remove the bogus case stmt from the
694          // substmt, but we have no way to do this right now.
695          CaseListIsErroneous = true;
696        }
697      }
698    }
699
700    // Complain if we have a constant condition and we didn't find a match.
701    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
702      // TODO: it would be nice if we printed enums as enums, chars as
703      // chars, etc.
704      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
705        << ConstantCondValue.toString(10)
706        << CondExpr->getSourceRange();
707    }
708
709    // Check to see if switch is over an Enum and handles all of its
710    // values.  We don't need to do this if there's a default
711    // statement or if we have a constant condition.
712    //
713    // TODO: we might want to check whether case values are out of the
714    // enum even if we don't want to check whether all cases are handled.
715    const EnumType* ET = CondTypeBeforePromotion->getAs<EnumType>();
716    // If switch has default case, then ignore it.
717    if (!CaseListIsErroneous && !TheDefaultStmt && !HasConstantCond && ET) {
718      const EnumDecl *ED = ET->getDecl();
719      typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
720      EnumValsTy EnumVals;
721
722      // Gather all enum values, set their type and sort them,
723      // allowing easier comparison with CaseVals.
724      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
725             EDI != ED->enumerator_end(); EDI++) {
726        llvm::APSInt Val = (*EDI)->getInitVal();
727        if(Val.getBitWidth() < CondWidth)
728          Val.extend(CondWidth);
729        else if (Val.getBitWidth() > CondWidth)
730          Val.trunc(CondWidth);
731        Val.setIsSigned(CondIsSigned);
732        EnumVals.push_back(std::make_pair(Val, (*EDI)));
733      }
734      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
735      EnumValsTy::iterator EIend =
736        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
737      // See which case values aren't in enum
738      EnumValsTy::const_iterator EI = EnumVals.begin();
739      for (CaseValsTy::const_iterator CI = CaseVals.begin();
740             CI != CaseVals.end(); CI++) {
741        while (EI != EIend && EI->first < CI->first)
742          EI++;
743        if (EI == EIend || EI->first > CI->first)
744            Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
745              << ED->getDeclName();
746      }
747      // See which of case ranges aren't in enum
748      EI = EnumVals.begin();
749      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
750             RI != CaseRanges.end() && EI != EIend; RI++) {
751        while (EI != EIend && EI->first < RI->first)
752          EI++;
753
754        if (EI == EIend || EI->first != RI->first) {
755          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
756            << ED->getDeclName();
757        }
758
759        llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
760        while (EI != EIend && EI->first < Hi)
761          EI++;
762        if (EI == EIend || EI->first != Hi)
763          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
764            << ED->getDeclName();
765      }
766      //Check which enum vals aren't in switch
767      CaseValsTy::const_iterator CI = CaseVals.begin();
768      CaseRangesTy::const_iterator RI = CaseRanges.begin();
769      EI = EnumVals.begin();
770      for (; EI != EIend; EI++) {
771        //Drop unneeded case values
772        llvm::APSInt CIVal;
773        while (CI != CaseVals.end() && CI->first < EI->first)
774          CI++;
775
776        if (CI != CaseVals.end() && CI->first == EI->first)
777          continue;
778
779        //Drop unneeded case ranges
780        for (; RI != CaseRanges.end(); RI++) {
781          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
782          if (EI->first <= Hi)
783            break;
784        }
785
786        if (RI == CaseRanges.end() || EI->first < RI->first)
787          Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
788            << EI->second->getDeclName();
789      }
790    }
791  }
792
793  // FIXME: If the case list was broken is some way, we don't have a good system
794  // to patch it up.  Instead, just return the whole substmt as broken.
795  if (CaseListIsErroneous)
796    return StmtError();
797
798  Switch.release();
799  return Owned(SS);
800}
801
802Action::OwningStmtResult
803Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
804                     Decl *CondVar, StmtArg Body) {
805  OwningExprResult CondResult(Cond.release());
806
807  VarDecl *ConditionVar = 0;
808  if (CondVar) {
809    ConditionVar = cast<VarDecl>(CondVar);
810    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
811    if (CondResult.isInvalid())
812      return StmtError();
813  }
814  Expr *ConditionExpr = CondResult.takeAs<Expr>();
815  if (!ConditionExpr)
816    return StmtError();
817
818  Stmt *bodyStmt = Body.takeAs<Stmt>();
819  DiagnoseUnusedExprResult(bodyStmt);
820
821  CondResult.release();
822  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
823                                       bodyStmt, WhileLoc));
824}
825
826Action::OwningStmtResult
827Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
828                  SourceLocation WhileLoc, SourceLocation CondLParen,
829                  ExprArg Cond, SourceLocation CondRParen) {
830  Expr *condExpr = Cond.takeAs<Expr>();
831  assert(condExpr && "ActOnDoStmt(): missing expression");
832
833  if (CheckBooleanCondition(condExpr, DoLoc)) {
834    Cond = condExpr;
835    return StmtError();
836  }
837
838  condExpr = MaybeCreateCXXExprWithTemporaries(condExpr);
839  if (!condExpr)
840    return StmtError();
841
842  Stmt *bodyStmt = Body.takeAs<Stmt>();
843  DiagnoseUnusedExprResult(bodyStmt);
844
845  Cond.release();
846  return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
847                                    WhileLoc, CondRParen));
848}
849
850Action::OwningStmtResult
851Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
852                   StmtArg first, FullExprArg second, Decl *secondVar,
853                   FullExprArg third,
854                   SourceLocation RParenLoc, StmtArg body) {
855  Stmt *First  = static_cast<Stmt*>(first.get());
856
857  if (!getLangOptions().CPlusPlus) {
858    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
859      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
860      // declare identifiers for objects having storage class 'auto' or
861      // 'register'.
862      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
863           DI!=DE; ++DI) {
864        VarDecl *VD = dyn_cast<VarDecl>(*DI);
865        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
866          VD = 0;
867        if (VD == 0)
868          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
869        // FIXME: mark decl erroneous!
870      }
871    }
872  }
873
874  OwningExprResult SecondResult(second.release());
875  VarDecl *ConditionVar = 0;
876  if (secondVar) {
877    ConditionVar = cast<VarDecl>(secondVar);
878    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
879    if (SecondResult.isInvalid())
880      return StmtError();
881  }
882
883  Expr *Third  = third.release().takeAs<Expr>();
884  Stmt *Body  = static_cast<Stmt*>(body.get());
885
886  DiagnoseUnusedExprResult(First);
887  DiagnoseUnusedExprResult(Third);
888  DiagnoseUnusedExprResult(Body);
889
890  first.release();
891  body.release();
892  return Owned(new (Context) ForStmt(Context, First,
893                                     SecondResult.takeAs<Expr>(), ConditionVar,
894                                     Third, Body, ForLoc, LParenLoc,
895                                     RParenLoc));
896}
897
898Action::OwningStmtResult
899Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
900                                 SourceLocation LParenLoc,
901                                 StmtArg first, ExprArg second,
902                                 SourceLocation RParenLoc, StmtArg body) {
903  Stmt *First  = static_cast<Stmt*>(first.get());
904  Expr *Second = static_cast<Expr*>(second.get());
905  Stmt *Body  = static_cast<Stmt*>(body.get());
906  if (First) {
907    QualType FirstType;
908    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
909      if (!DS->isSingleDecl())
910        return StmtError(Diag((*DS->decl_begin())->getLocation(),
911                         diag::err_toomany_element_decls));
912
913      Decl *D = DS->getSingleDecl();
914      FirstType = cast<ValueDecl>(D)->getType();
915      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
916      // declare identifiers for objects having storage class 'auto' or
917      // 'register'.
918      VarDecl *VD = cast<VarDecl>(D);
919      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
920        return StmtError(Diag(VD->getLocation(),
921                              diag::err_non_variable_decl_in_for));
922    } else {
923      Expr *FirstE = cast<Expr>(First);
924      if (!FirstE->isTypeDependent() &&
925          FirstE->isLvalue(Context) != Expr::LV_Valid)
926        return StmtError(Diag(First->getLocStart(),
927                   diag::err_selector_element_not_lvalue)
928          << First->getSourceRange());
929
930      FirstType = static_cast<Expr*>(First)->getType();
931    }
932    if (!FirstType->isDependentType() &&
933        !FirstType->isObjCObjectPointerType() &&
934        !FirstType->isBlockPointerType())
935        Diag(ForLoc, diag::err_selector_element_type)
936          << FirstType << First->getSourceRange();
937  }
938  if (Second && !Second->isTypeDependent()) {
939    DefaultFunctionArrayLvalueConversion(Second);
940    QualType SecondType = Second->getType();
941    if (!SecondType->isObjCObjectPointerType())
942      Diag(ForLoc, diag::err_collection_expr_type)
943        << SecondType << Second->getSourceRange();
944    else if (const ObjCObjectPointerType *OPT =
945             SecondType->getAsObjCInterfacePointerType()) {
946      llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
947      IdentifierInfo* selIdent =
948        &Context.Idents.get("countByEnumeratingWithState");
949      KeyIdents.push_back(selIdent);
950      selIdent = &Context.Idents.get("objects");
951      KeyIdents.push_back(selIdent);
952      selIdent = &Context.Idents.get("count");
953      KeyIdents.push_back(selIdent);
954      Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
955      if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
956        if (!IDecl->isForwardDecl() &&
957            !IDecl->lookupInstanceMethod(CSelector)) {
958          // Must further look into private implementation methods.
959          if (!LookupPrivateInstanceMethod(CSelector, IDecl))
960            Diag(ForLoc, diag::warn_collection_expr_type)
961              << SecondType << CSelector << Second->getSourceRange();
962        }
963      }
964    }
965  }
966  first.release();
967  second.release();
968  body.release();
969  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
970                                                   ForLoc, RParenLoc));
971}
972
973Action::OwningStmtResult
974Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
975                    IdentifierInfo *LabelII) {
976  // Look up the record for this label identifier.
977  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
978
979  setFunctionHasBranchIntoScope();
980
981  // If we haven't seen this label yet, create a forward reference.
982  if (LabelDecl == 0)
983    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
984
985  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
986}
987
988Action::OwningStmtResult
989Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
990                            ExprArg DestExp) {
991  // Convert operand to void*
992  Expr* E = DestExp.takeAs<Expr>();
993  if (!E->isTypeDependent()) {
994    QualType ETy = E->getType();
995    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
996    AssignConvertType ConvTy =
997      CheckSingleAssignmentConstraints(DestTy, E);
998    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
999      return StmtError();
1000  }
1001
1002  setFunctionHasIndirectGoto();
1003
1004  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1005}
1006
1007Action::OwningStmtResult
1008Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1009  Scope *S = CurScope->getContinueParent();
1010  if (!S) {
1011    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1012    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1013  }
1014
1015  return Owned(new (Context) ContinueStmt(ContinueLoc));
1016}
1017
1018Action::OwningStmtResult
1019Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1020  Scope *S = CurScope->getBreakParent();
1021  if (!S) {
1022    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1023    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1024  }
1025
1026  return Owned(new (Context) BreakStmt(BreakLoc));
1027}
1028
1029/// \brief Determine whether a return statement is a candidate for the named
1030/// return value optimization (C++0x 12.8p34, bullet 1).
1031///
1032/// \param Ctx The context in which the return expression and type occur.
1033///
1034/// \param RetType The return type of the function or block.
1035///
1036/// \param RetExpr The expression being returned from the function or block.
1037///
1038/// \returns The NRVO candidate variable, if the return statement may use the
1039/// NRVO, or NULL if there is no such candidate.
1040static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1041                                       Expr *RetExpr) {
1042  QualType ExprType = RetExpr->getType();
1043  // - in a return statement in a function with ...
1044  // ... a class return type ...
1045  if (!RetType->isRecordType())
1046    return 0;
1047  // ... the same cv-unqualified type as the function return type ...
1048  if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1049    return 0;
1050  // ... the expression is the name of a non-volatile automatic object ...
1051  // We ignore parentheses here.
1052  // FIXME: Is this compliant? (Everyone else does it)
1053  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1054  if (!DR)
1055    return 0;
1056  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1057  if (!VD)
1058    return 0;
1059
1060  if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
1061      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1062      !VD->getType().isVolatileQualified())
1063    return VD;
1064
1065  return 0;
1066}
1067
1068/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1069///
1070Action::OwningStmtResult
1071Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1072  // If this is the first return we've seen in the block, infer the type of
1073  // the block from it.
1074  BlockScopeInfo *CurBlock = getCurBlock();
1075  if (CurBlock->ReturnType.isNull()) {
1076    if (RetValExp) {
1077      // Don't call UsualUnaryConversions(), since we don't want to do
1078      // integer promotions here.
1079      DefaultFunctionArrayLvalueConversion(RetValExp);
1080      CurBlock->ReturnType = RetValExp->getType();
1081      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1082        // We have to remove a 'const' added to copied-in variable which was
1083        // part of the implementation spec. and not the actual qualifier for
1084        // the variable.
1085        if (CDRE->isConstQualAdded())
1086           CurBlock->ReturnType.removeConst();
1087      }
1088    } else
1089      CurBlock->ReturnType = Context.VoidTy;
1090  }
1091  QualType FnRetType = CurBlock->ReturnType;
1092
1093  if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
1094    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1095      << getCurFunctionOrMethodDecl()->getDeclName();
1096    return StmtError();
1097  }
1098
1099  // Otherwise, verify that this result type matches the previous one.  We are
1100  // pickier with blocks than for normal functions because we don't have GCC
1101  // compatibility to worry about here.
1102  ReturnStmt *Result = 0;
1103  if (CurBlock->ReturnType->isVoidType()) {
1104    if (RetValExp) {
1105      Diag(ReturnLoc, diag::err_return_block_has_expr);
1106      RetValExp = 0;
1107    }
1108    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1109  } else if (!RetValExp) {
1110    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1111  } else {
1112    const VarDecl *NRVOCandidate = 0;
1113
1114    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1115      // we have a non-void block with an expression, continue checking
1116
1117      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1118      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1119      // function return.
1120
1121      // In C++ the return statement is handled via a copy initialization.
1122      // the C version of which boils down to CheckSingleAssignmentConstraints.
1123      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1124      OwningExprResult Res = PerformCopyInitialization(
1125                               InitializedEntity::InitializeResult(ReturnLoc,
1126                                                                   FnRetType,
1127                                                            NRVOCandidate != 0),
1128                               SourceLocation(),
1129                               Owned(RetValExp));
1130      if (Res.isInvalid()) {
1131        // FIXME: Cleanup temporaries here, anyway?
1132        return StmtError();
1133      }
1134
1135      if (RetValExp)
1136        RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1137
1138      RetValExp = Res.takeAs<Expr>();
1139      if (RetValExp)
1140        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1141    }
1142
1143    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1144  }
1145
1146  // If we need to check for the named return value optimization, save the
1147  // return statement in our scope for later processing.
1148  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1149      !CurContext->isDependentContext())
1150    FunctionScopes.back()->Returns.push_back(Result);
1151
1152  return Owned(Result);
1153}
1154
1155Action::OwningStmtResult
1156Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
1157  Expr *RetValExp = rex.takeAs<Expr>();
1158  if (getCurBlock())
1159    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1160
1161  QualType FnRetType;
1162  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1163    FnRetType = FD->getResultType();
1164    if (FD->hasAttr<NoReturnAttr>() ||
1165        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1166      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1167        << getCurFunctionOrMethodDecl()->getDeclName();
1168  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1169    FnRetType = MD->getResultType();
1170  else // If we don't have a function/method context, bail.
1171    return StmtError();
1172
1173  ReturnStmt *Result = 0;
1174  if (FnRetType->isVoidType()) {
1175    if (RetValExp && !RetValExp->isTypeDependent()) {
1176      // C99 6.8.6.4p1 (ext_ since GCC warns)
1177      unsigned D = diag::ext_return_has_expr;
1178      if (RetValExp->getType()->isVoidType())
1179        D = diag::ext_return_has_void_expr;
1180
1181      // return (some void expression); is legal in C++.
1182      if (D != diag::ext_return_has_void_expr ||
1183          !getLangOptions().CPlusPlus) {
1184        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1185        Diag(ReturnLoc, D)
1186          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1187          << RetValExp->getSourceRange();
1188      }
1189
1190      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1191    }
1192
1193    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1194  } else if (!RetValExp && !FnRetType->isDependentType()) {
1195    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1196    // C99 6.8.6.4p1 (ext_ since GCC warns)
1197    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1198
1199    if (FunctionDecl *FD = getCurFunctionDecl())
1200      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1201    else
1202      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1203    Result = new (Context) ReturnStmt(ReturnLoc);
1204  } else {
1205    const VarDecl *NRVOCandidate = 0;
1206    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1207      // we have a non-void function with an expression, continue checking
1208
1209      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1210      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1211      // function return.
1212
1213      // In C++ the return statement is handled via a copy initialization.
1214      // the C version of which boils down to CheckSingleAssignmentConstraints.
1215      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1216      OwningExprResult Res = PerformCopyInitialization(
1217                               InitializedEntity::InitializeResult(ReturnLoc,
1218                                                                   FnRetType,
1219                                                            NRVOCandidate != 0),
1220                               SourceLocation(),
1221                               Owned(RetValExp));
1222      if (Res.isInvalid()) {
1223        // FIXME: Cleanup temporaries here, anyway?
1224        return StmtError();
1225      }
1226
1227      RetValExp = Res.takeAs<Expr>();
1228      if (RetValExp)
1229        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1230    }
1231
1232    if (RetValExp)
1233      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1234    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1235  }
1236
1237  // If we need to check for the named return value optimization, save the
1238  // return statement in our scope for later processing.
1239  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1240      !CurContext->isDependentContext())
1241    FunctionScopes.back()->Returns.push_back(Result);
1242
1243  return Owned(Result);
1244}
1245
1246/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1247/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1248/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1249/// provide a strong guidance to not use it.
1250///
1251/// This method checks to see if the argument is an acceptable l-value and
1252/// returns false if it is a case we can handle.
1253static bool CheckAsmLValue(const Expr *E, Sema &S) {
1254  // Type dependent expressions will be checked during instantiation.
1255  if (E->isTypeDependent())
1256    return false;
1257
1258  if (E->isLvalue(S.Context) == Expr::LV_Valid)
1259    return false;  // Cool, this is an lvalue.
1260
1261  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1262  // are supposed to allow.
1263  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1264  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1265    if (!S.getLangOptions().HeinousExtensions)
1266      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1267        << E->getSourceRange();
1268    else
1269      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1270        << E->getSourceRange();
1271    // Accept, even if we emitted an error diagnostic.
1272    return false;
1273  }
1274
1275  // None of the above, just randomly invalid non-lvalue.
1276  return true;
1277}
1278
1279
1280Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1281                                          bool IsSimple,
1282                                          bool IsVolatile,
1283                                          unsigned NumOutputs,
1284                                          unsigned NumInputs,
1285                                          IdentifierInfo **Names,
1286                                          MultiExprArg constraints,
1287                                          MultiExprArg exprs,
1288                                          ExprArg asmString,
1289                                          MultiExprArg clobbers,
1290                                          SourceLocation RParenLoc,
1291                                          bool MSAsm) {
1292  unsigned NumClobbers = clobbers.size();
1293  StringLiteral **Constraints =
1294    reinterpret_cast<StringLiteral**>(constraints.get());
1295  Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1296  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1297  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1298
1299  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1300
1301  // The parser verifies that there is a string literal here.
1302  if (AsmString->isWide())
1303    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1304      << AsmString->getSourceRange());
1305
1306  for (unsigned i = 0; i != NumOutputs; i++) {
1307    StringLiteral *Literal = Constraints[i];
1308    if (Literal->isWide())
1309      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1310        << Literal->getSourceRange());
1311
1312    llvm::StringRef OutputName;
1313    if (Names[i])
1314      OutputName = Names[i]->getName();
1315
1316    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1317    if (!Context.Target.validateOutputConstraint(Info))
1318      return StmtError(Diag(Literal->getLocStart(),
1319                            diag::err_asm_invalid_output_constraint)
1320                       << Info.getConstraintStr());
1321
1322    // Check that the output exprs are valid lvalues.
1323    Expr *OutputExpr = Exprs[i];
1324    if (CheckAsmLValue(OutputExpr, *this)) {
1325      return StmtError(Diag(OutputExpr->getLocStart(),
1326                  diag::err_asm_invalid_lvalue_in_output)
1327        << OutputExpr->getSourceRange());
1328    }
1329
1330    OutputConstraintInfos.push_back(Info);
1331  }
1332
1333  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1334
1335  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1336    StringLiteral *Literal = Constraints[i];
1337    if (Literal->isWide())
1338      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1339        << Literal->getSourceRange());
1340
1341    llvm::StringRef InputName;
1342    if (Names[i])
1343      InputName = Names[i]->getName();
1344
1345    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1346    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1347                                                NumOutputs, Info)) {
1348      return StmtError(Diag(Literal->getLocStart(),
1349                            diag::err_asm_invalid_input_constraint)
1350                       << Info.getConstraintStr());
1351    }
1352
1353    Expr *InputExpr = Exprs[i];
1354
1355    // Only allow void types for memory constraints.
1356    if (Info.allowsMemory() && !Info.allowsRegister()) {
1357      if (CheckAsmLValue(InputExpr, *this))
1358        return StmtError(Diag(InputExpr->getLocStart(),
1359                              diag::err_asm_invalid_lvalue_in_input)
1360                         << Info.getConstraintStr()
1361                         << InputExpr->getSourceRange());
1362    }
1363
1364    if (Info.allowsRegister()) {
1365      if (InputExpr->getType()->isVoidType()) {
1366        return StmtError(Diag(InputExpr->getLocStart(),
1367                              diag::err_asm_invalid_type_in_input)
1368          << InputExpr->getType() << Info.getConstraintStr()
1369          << InputExpr->getSourceRange());
1370      }
1371    }
1372
1373    DefaultFunctionArrayLvalueConversion(Exprs[i]);
1374
1375    InputConstraintInfos.push_back(Info);
1376  }
1377
1378  // Check that the clobbers are valid.
1379  for (unsigned i = 0; i != NumClobbers; i++) {
1380    StringLiteral *Literal = Clobbers[i];
1381    if (Literal->isWide())
1382      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1383        << Literal->getSourceRange());
1384
1385    llvm::StringRef Clobber = Literal->getString();
1386
1387    if (!Context.Target.isValidGCCRegisterName(Clobber))
1388      return StmtError(Diag(Literal->getLocStart(),
1389                  diag::err_asm_unknown_register_name) << Clobber);
1390  }
1391
1392  constraints.release();
1393  exprs.release();
1394  asmString.release();
1395  clobbers.release();
1396  AsmStmt *NS =
1397    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1398                          NumOutputs, NumInputs, Names, Constraints, Exprs,
1399                          AsmString, NumClobbers, Clobbers, RParenLoc);
1400  // Validate the asm string, ensuring it makes sense given the operands we
1401  // have.
1402  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1403  unsigned DiagOffs;
1404  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1405    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1406           << AsmString->getSourceRange();
1407    DeleteStmt(NS);
1408    return StmtError();
1409  }
1410
1411  // Validate tied input operands for type mismatches.
1412  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1413    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1414
1415    // If this is a tied constraint, verify that the output and input have
1416    // either exactly the same type, or that they are int/ptr operands with the
1417    // same size (int/long, int*/long, are ok etc).
1418    if (!Info.hasTiedOperand()) continue;
1419
1420    unsigned TiedTo = Info.getTiedOperand();
1421    Expr *OutputExpr = Exprs[TiedTo];
1422    Expr *InputExpr = Exprs[i+NumOutputs];
1423    QualType InTy = InputExpr->getType();
1424    QualType OutTy = OutputExpr->getType();
1425    if (Context.hasSameType(InTy, OutTy))
1426      continue;  // All types can be tied to themselves.
1427
1428    // Decide if the input and output are in the same domain (integer/ptr or
1429    // floating point.
1430    enum AsmDomain {
1431      AD_Int, AD_FP, AD_Other
1432    } InputDomain, OutputDomain;
1433
1434    if (InTy->isIntegerType() || InTy->isPointerType())
1435      InputDomain = AD_Int;
1436    else if (InTy->isRealFloatingType())
1437      InputDomain = AD_FP;
1438    else
1439      InputDomain = AD_Other;
1440
1441    if (OutTy->isIntegerType() || OutTy->isPointerType())
1442      OutputDomain = AD_Int;
1443    else if (OutTy->isRealFloatingType())
1444      OutputDomain = AD_FP;
1445    else
1446      OutputDomain = AD_Other;
1447
1448    // They are ok if they are the same size and in the same domain.  This
1449    // allows tying things like:
1450    //   void* to int*
1451    //   void* to int            if they are the same size.
1452    //   double to long double   if they are the same size.
1453    //
1454    uint64_t OutSize = Context.getTypeSize(OutTy);
1455    uint64_t InSize = Context.getTypeSize(InTy);
1456    if (OutSize == InSize && InputDomain == OutputDomain &&
1457        InputDomain != AD_Other)
1458      continue;
1459
1460    // If the smaller input/output operand is not mentioned in the asm string,
1461    // then we can promote it and the asm string won't notice.  Check this
1462    // case now.
1463    bool SmallerValueMentioned = false;
1464    for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1465      AsmStmt::AsmStringPiece &Piece = Pieces[p];
1466      if (!Piece.isOperand()) continue;
1467
1468      // If this is a reference to the input and if the input was the smaller
1469      // one, then we have to reject this asm.
1470      if (Piece.getOperandNo() == i+NumOutputs) {
1471        if (InSize < OutSize) {
1472          SmallerValueMentioned = true;
1473          break;
1474        }
1475      }
1476
1477      // If this is a reference to the input and if the input was the smaller
1478      // one, then we have to reject this asm.
1479      if (Piece.getOperandNo() == TiedTo) {
1480        if (InSize > OutSize) {
1481          SmallerValueMentioned = true;
1482          break;
1483        }
1484      }
1485    }
1486
1487    // If the smaller value wasn't mentioned in the asm string, and if the
1488    // output was a register, just extend the shorter one to the size of the
1489    // larger one.
1490    if (!SmallerValueMentioned && InputDomain != AD_Other &&
1491        OutputConstraintInfos[TiedTo].allowsRegister())
1492      continue;
1493
1494    Diag(InputExpr->getLocStart(),
1495         diag::err_asm_tying_incompatible_types)
1496      << InTy << OutTy << OutputExpr->getSourceRange()
1497      << InputExpr->getSourceRange();
1498    DeleteStmt(NS);
1499    return StmtError();
1500  }
1501
1502  return Owned(NS);
1503}
1504
1505Action::OwningStmtResult
1506Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1507                           SourceLocation RParen, Decl *Parm,
1508                           StmtArg Body) {
1509  VarDecl *Var = cast_or_null<VarDecl>(Parm);
1510  if (Var && Var->isInvalidDecl())
1511    return StmtError();
1512
1513  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var,
1514                                             Body.takeAs<Stmt>()));
1515}
1516
1517Action::OwningStmtResult
1518Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1519  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1520                                           static_cast<Stmt*>(Body.release())));
1521}
1522
1523Action::OwningStmtResult
1524Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try,
1525                         MultiStmtArg CatchStmts, StmtArg Finally) {
1526  setFunctionHasBranchProtectedScope();
1527  unsigned NumCatchStmts = CatchStmts.size();
1528  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try.takeAs<Stmt>(),
1529                                     (Stmt **)CatchStmts.release(),
1530                                     NumCatchStmts,
1531                                     Finally.takeAs<Stmt>()));
1532}
1533
1534Sema::OwningStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1535                                                  ExprArg ThrowE) {
1536  Expr *Throw = static_cast<Expr *>(ThrowE.get());
1537  if (Throw) {
1538    QualType ThrowType = Throw->getType();
1539    // Make sure the expression type is an ObjC pointer or "void *".
1540    if (!ThrowType->isDependentType() &&
1541        !ThrowType->isObjCObjectPointerType()) {
1542      const PointerType *PT = ThrowType->getAs<PointerType>();
1543      if (!PT || !PT->getPointeeType()->isVoidType())
1544        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1545                         << Throw->getType() << Throw->getSourceRange());
1546    }
1547  }
1548
1549  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowE.takeAs<Expr>()));
1550}
1551
1552Action::OwningStmtResult
1553Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw,
1554                           Scope *CurScope) {
1555  if (!Throw.get()) {
1556    // @throw without an expression designates a rethrow (which much occur
1557    // in the context of an @catch clause).
1558    Scope *AtCatchParent = CurScope;
1559    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1560      AtCatchParent = AtCatchParent->getParent();
1561    if (!AtCatchParent)
1562      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1563  }
1564
1565  return BuildObjCAtThrowStmt(AtLoc, move(Throw));
1566}
1567
1568Action::OwningStmtResult
1569Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1570                                  StmtArg SynchBody) {
1571  setFunctionHasBranchProtectedScope();
1572
1573  // Make sure the expression type is an ObjC pointer or "void *".
1574  Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1575  if (!SyncExpr->getType()->isDependentType() &&
1576      !SyncExpr->getType()->isObjCObjectPointerType()) {
1577    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1578    if (!PT || !PT->getPointeeType()->isVoidType())
1579      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1580                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1581  }
1582
1583  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1584                                                    SynchExpr.takeAs<Stmt>(),
1585                                                    SynchBody.takeAs<Stmt>()));
1586}
1587
1588/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1589/// and creates a proper catch handler from them.
1590Action::OwningStmtResult
1591Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
1592                         StmtArg HandlerBlock) {
1593  // There's nothing to test that ActOnExceptionDecl didn't already test.
1594  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1595                                          cast_or_null<VarDecl>(ExDecl),
1596                                          HandlerBlock.takeAs<Stmt>()));
1597}
1598
1599namespace {
1600
1601class TypeWithHandler {
1602  QualType t;
1603  CXXCatchStmt *stmt;
1604public:
1605  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1606  : t(type), stmt(statement) {}
1607
1608  // An arbitrary order is fine as long as it places identical
1609  // types next to each other.
1610  bool operator<(const TypeWithHandler &y) const {
1611    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1612      return true;
1613    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1614      return false;
1615    else
1616      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1617  }
1618
1619  bool operator==(const TypeWithHandler& other) const {
1620    return t == other.t;
1621  }
1622
1623  QualType getQualType() const { return t; }
1624  CXXCatchStmt *getCatchStmt() const { return stmt; }
1625  SourceLocation getTypeSpecStartLoc() const {
1626    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1627  }
1628};
1629
1630}
1631
1632/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1633/// handlers and creates a try statement from them.
1634Action::OwningStmtResult
1635Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1636                       MultiStmtArg RawHandlers) {
1637  unsigned NumHandlers = RawHandlers.size();
1638  assert(NumHandlers > 0 &&
1639         "The parser shouldn't call this if there are no handlers.");
1640  Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1641
1642  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1643
1644  for (unsigned i = 0; i < NumHandlers; ++i) {
1645    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1646    if (!Handler->getExceptionDecl()) {
1647      if (i < NumHandlers - 1)
1648        return StmtError(Diag(Handler->getLocStart(),
1649                              diag::err_early_catch_all));
1650
1651      continue;
1652    }
1653
1654    const QualType CaughtType = Handler->getCaughtType();
1655    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1656    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1657  }
1658
1659  // Detect handlers for the same type as an earlier one.
1660  if (NumHandlers > 1) {
1661    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1662
1663    TypeWithHandler prev = TypesWithHandlers[0];
1664    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1665      TypeWithHandler curr = TypesWithHandlers[i];
1666
1667      if (curr == prev) {
1668        Diag(curr.getTypeSpecStartLoc(),
1669             diag::warn_exception_caught_by_earlier_handler)
1670          << curr.getCatchStmt()->getCaughtType().getAsString();
1671        Diag(prev.getTypeSpecStartLoc(),
1672             diag::note_previous_exception_handler)
1673          << prev.getCatchStmt()->getCaughtType().getAsString();
1674      }
1675
1676      prev = curr;
1677    }
1678  }
1679
1680  setFunctionHasBranchProtectedScope();
1681
1682  // FIXME: We should detect handlers that cannot catch anything because an
1683  // earlier handler catches a superclass. Need to find a method that is not
1684  // quadratic for this.
1685  // Neither of these are explicitly forbidden, but every compiler detects them
1686  // and warns.
1687
1688  RawHandlers.release();
1689  return Owned(CXXTryStmt::Create(Context, TryLoc,
1690                                  static_cast<Stmt*>(TryBlock.release()),
1691                                  Handlers, NumHandlers));
1692}
1693