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