SemaStmt.cpp revision d68876176a0d2c19e3864e7d38f6036c4f72f0a3
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 "clang/AST/APValue.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/StmtObjC.h"
20#include "clang/AST/StmtCXX.h"
21#include "clang/Basic/TargetInfo.h"
22using namespace clang;
23
24Sema::OwningStmtResult Sema::ActOnExprStmt(ExprArg expr) {
25  Expr *E = static_cast<Expr*>(expr.release());
26  assert(E && "ActOnExprStmt(): missing expression");
27
28  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
29  // void expression for its side effects.  Conversion to void allows any
30  // operand, even incomplete types.
31
32  // Same thing in for stmt first clause (when expr) and third clause.
33  return Owned(static_cast<Stmt*>(E));
34}
35
36
37Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
38  return Owned(new (Context) NullStmt(SemiLoc));
39}
40
41Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
42                                           SourceLocation StartLoc,
43                                           SourceLocation EndLoc) {
44  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
45
46  // If we have an invalid decl, just return an error.
47  if (DG.isNull()) return StmtError();
48
49  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
50}
51
52Action::OwningStmtResult
53Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
54                        MultiStmtArg elts, bool isStmtExpr) {
55  unsigned NumElts = elts.size();
56  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
57  // If we're in C89 mode, check that we don't have any decls after stmts.  If
58  // so, emit an extension diagnostic.
59  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
60    // Note that __extension__ can be around a decl.
61    unsigned i = 0;
62    // Skip over all declarations.
63    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
64      /*empty*/;
65
66    // We found the end of the list or a statement.  Scan for another declstmt.
67    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
68      /*empty*/;
69
70    if (i != NumElts) {
71      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
72      Diag(D->getLocation(), diag::ext_mixed_decls_code);
73    }
74  }
75  // Warn about unused expressions in statements.
76  for (unsigned i = 0; i != NumElts; ++i) {
77    Expr *E = dyn_cast<Expr>(Elts[i]);
78    if (!E) continue;
79
80    // Warn about expressions with unused results if they are non-void and if
81    // this not the last stmt in a stmt expr.
82    if (E->getType()->isVoidType() || (isStmtExpr && i == NumElts-1))
83      continue;
84
85    SourceLocation Loc;
86    SourceRange R1, R2;
87    if (!E->isUnusedResultAWarning(Loc, R1, R2))
88      continue;
89
90    Diag(Loc, diag::warn_unused_expr) << R1 << R2;
91  }
92
93  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
94}
95
96Action::OwningStmtResult
97Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
98                    SourceLocation DotDotDotLoc, ExprArg rhsval,
99                    SourceLocation ColonLoc) {
100  assert((lhsval.get() != 0) && "missing expression in case statement");
101
102  // C99 6.8.4.2p3: The expression shall be an integer constant.
103  // However, GCC allows any evaluatable integer expression.
104  Expr *LHSVal = static_cast<Expr*>(lhsval.get());
105  if (VerifyIntegerConstantExpression(LHSVal))
106    return StmtError();
107
108  // GCC extension: The expression shall be an integer constant.
109
110  Expr *RHSVal = static_cast<Expr*>(rhsval.get());
111  if (RHSVal && VerifyIntegerConstantExpression(RHSVal)) {
112    RHSVal = 0;  // Recover by just forgetting about it.
113    rhsval = 0;
114  }
115
116  if (getSwitchStack().empty()) {
117    Diag(CaseLoc, diag::err_case_not_in_switch);
118    return StmtError();
119  }
120
121  // Only now release the smart pointers.
122  lhsval.release();
123  rhsval.release();
124  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc);
125  getSwitchStack().back()->addSwitchCase(CS);
126  return Owned(CS);
127}
128
129/// ActOnCaseStmtBody - This installs a statement as the body of a case.
130void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
131  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
132  Stmt *SubStmt = static_cast<Stmt*>(subStmt.release());
133  CS->setSubStmt(SubStmt);
134}
135
136Action::OwningStmtResult
137Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
138                       StmtArg subStmt, Scope *CurScope) {
139  Stmt *SubStmt = static_cast<Stmt*>(subStmt.release());
140
141  if (getSwitchStack().empty()) {
142    Diag(DefaultLoc, diag::err_default_not_in_switch);
143    return Owned(SubStmt);
144  }
145
146  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, SubStmt);
147  getSwitchStack().back()->addSwitchCase(DS);
148  return Owned(DS);
149}
150
151Action::OwningStmtResult
152Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
153                     SourceLocation ColonLoc, StmtArg subStmt) {
154  Stmt *SubStmt = static_cast<Stmt*>(subStmt.release());
155  // Look up the record for this label identifier.
156  LabelStmt *&LabelDecl = getLabelMap()[II];
157
158  // If not forward referenced or defined already, just create a new LabelStmt.
159  if (LabelDecl == 0)
160    return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
161
162  assert(LabelDecl->getID() == II && "Label mismatch!");
163
164  // Otherwise, this label was either forward reference or multiply defined.  If
165  // multiply defined, reject it now.
166  if (LabelDecl->getSubStmt()) {
167    Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
168    Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
169    return Owned(SubStmt);
170  }
171
172  // Otherwise, this label was forward declared, and we just found its real
173  // definition.  Fill in the forward definition and return it.
174  LabelDecl->setIdentLoc(IdentLoc);
175  LabelDecl->setSubStmt(SubStmt);
176  return Owned(LabelDecl);
177}
178
179Action::OwningStmtResult
180Sema::ActOnIfStmt(SourceLocation IfLoc, ExprArg CondVal,
181                  StmtArg ThenVal, SourceLocation ElseLoc,
182                  StmtArg ElseVal) {
183  Expr *condExpr = (Expr *)CondVal.release();
184
185  assert(condExpr && "ActOnIfStmt(): missing expression");
186
187  DefaultFunctionArrayConversion(condExpr);
188  // Take ownership again until we're past the error checking.
189  CondVal = condExpr;
190  QualType condType = condExpr->getType();
191
192  if (getLangOptions().CPlusPlus) {
193    if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
194      return StmtError();
195  } else if (!condType->isScalarType()) // C99 6.8.4.1p1
196    return StmtError(Diag(IfLoc, diag::err_typecheck_statement_requires_scalar)
197      << condType << condExpr->getSourceRange());
198
199  Stmt *thenStmt = (Stmt *)ThenVal.release();
200
201  // Warn if the if block has a null body without an else value.
202  // this helps prevent bugs due to typos, such as
203  // if (condition);
204  //   do_stuff();
205  if (!ElseVal.get()) {
206    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
207      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
208  }
209
210  CondVal.release();
211  return Owned(new (Context) IfStmt(IfLoc, condExpr, thenStmt,
212                                    (Stmt*)ElseVal.release()));
213}
214
215Action::OwningStmtResult
216Sema::ActOnStartOfSwitchStmt(ExprArg cond) {
217  Expr *Cond = static_cast<Expr*>(cond.release());
218
219  if (getLangOptions().CPlusPlus) {
220    // C++ 6.4.2.p2:
221    // The condition shall be of integral type, enumeration type, or of a class
222    // type for which a single conversion function to integral or enumeration
223    // type exists (12.3). If the condition is of class type, the condition is
224    // converted by calling that conversion function, and the result of the
225    // conversion is used in place of the original condition for the remainder
226    // of this section. Integral promotions are performed.
227
228    QualType Ty = Cond->getType();
229
230    // FIXME: Handle class types.
231
232    // If the type is wrong a diagnostic will be emitted later at
233    // ActOnFinishSwitchStmt.
234    if (Ty->isIntegralType() || Ty->isEnumeralType()) {
235      // Integral promotions are performed.
236      // FIXME: Integral promotions for C++ are not complete.
237      UsualUnaryConversions(Cond);
238    }
239  } else {
240    // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
241    UsualUnaryConversions(Cond);
242  }
243
244  SwitchStmt *SS = new (Context) SwitchStmt(Cond);
245  getSwitchStack().push_back(SS);
246  return Owned(SS);
247}
248
249/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
250/// the specified width and sign.  If an overflow occurs, detect it and emit
251/// the specified diagnostic.
252void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
253                                              unsigned NewWidth, bool NewSign,
254                                              SourceLocation Loc,
255                                              unsigned DiagID) {
256  // Perform a conversion to the promoted condition type if needed.
257  if (NewWidth > Val.getBitWidth()) {
258    // If this is an extension, just do it.
259    llvm::APSInt OldVal(Val);
260    Val.extend(NewWidth);
261
262    // If the input was signed and negative and the output is unsigned,
263    // warn.
264    if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
265      Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
266
267    Val.setIsSigned(NewSign);
268  } else if (NewWidth < Val.getBitWidth()) {
269    // If this is a truncation, check for overflow.
270    llvm::APSInt ConvVal(Val);
271    ConvVal.trunc(NewWidth);
272    ConvVal.setIsSigned(NewSign);
273    ConvVal.extend(Val.getBitWidth());
274    ConvVal.setIsSigned(Val.isSigned());
275    if (ConvVal != Val)
276      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
277
278    // Regardless of whether a diagnostic was emitted, really do the
279    // truncation.
280    Val.trunc(NewWidth);
281    Val.setIsSigned(NewSign);
282  } else if (NewSign != Val.isSigned()) {
283    // Convert the sign to match the sign of the condition.  This can cause
284    // overflow as well: unsigned(INTMIN)
285    llvm::APSInt OldVal(Val);
286    Val.setIsSigned(NewSign);
287
288    if (Val.isNegative())  // Sign bit changes meaning.
289      Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
290  }
291}
292
293namespace {
294  struct CaseCompareFunctor {
295    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
296                    const llvm::APSInt &RHS) {
297      return LHS.first < RHS;
298    }
299    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
300                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
301      return LHS.first < RHS.first;
302    }
303    bool operator()(const llvm::APSInt &LHS,
304                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
305      return LHS < RHS.first;
306    }
307  };
308}
309
310/// CmpCaseVals - Comparison predicate for sorting case values.
311///
312static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
313                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
314  if (lhs.first < rhs.first)
315    return true;
316
317  if (lhs.first == rhs.first &&
318      lhs.second->getCaseLoc().getRawEncoding()
319       < rhs.second->getCaseLoc().getRawEncoding())
320    return true;
321  return false;
322}
323
324Action::OwningStmtResult
325Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
326                            StmtArg Body) {
327  Stmt *BodyStmt = (Stmt*)Body.release();
328
329  SwitchStmt *SS = getSwitchStack().back();
330  assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
331
332  SS->setBody(BodyStmt, SwitchLoc);
333  getSwitchStack().pop_back();
334
335  Expr *CondExpr = SS->getCond();
336  QualType CondType = CondExpr->getType();
337
338  if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
339    Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
340      << CondType << CondExpr->getSourceRange();
341    return StmtError();
342  }
343
344  // Get the bitwidth of the switched-on value before promotions.  We must
345  // convert the integer case values to this width before comparison.
346  unsigned CondWidth = static_cast<unsigned>(Context.getTypeSize(CondType));
347  bool CondIsSigned = CondType->isSignedIntegerType();
348
349  // Accumulate all of the case values in a vector so that we can sort them
350  // and detect duplicates.  This vector contains the APInt for the case after
351  // it has been converted to the condition type.
352  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
353  CaseValsTy CaseVals;
354
355  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
356  std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
357
358  DefaultStmt *TheDefaultStmt = 0;
359
360  bool CaseListIsErroneous = false;
361
362  for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
363       SC = SC->getNextSwitchCase()) {
364
365    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
366      if (TheDefaultStmt) {
367        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
368        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
369
370        // FIXME: Remove the default statement from the switch block so that
371        // we'll return a valid AST.  This requires recursing down the
372        // AST and finding it, not something we are set up to do right now.  For
373        // now, just lop the entire switch stmt out of the AST.
374        CaseListIsErroneous = true;
375      }
376      TheDefaultStmt = DS;
377
378    } else {
379      CaseStmt *CS = cast<CaseStmt>(SC);
380
381      // We already verified that the expression has a i-c-e value (C99
382      // 6.8.4.2p3) - get that value now.
383      Expr *Lo = CS->getLHS();
384      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
385
386      // Convert the value to the same width/sign as the condition.
387      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
388                                         CS->getLHS()->getLocStart(),
389                                         diag::warn_case_value_overflow);
390
391      // If the LHS is not the same type as the condition, insert an implicit
392      // cast.
393      ImpCastExprToType(Lo, CondType);
394      CS->setLHS(Lo);
395
396      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
397      if (CS->getRHS())
398        CaseRanges.push_back(std::make_pair(LoVal, CS));
399      else
400        CaseVals.push_back(std::make_pair(LoVal, CS));
401    }
402  }
403
404  // Sort all the scalar case values so we can easily detect duplicates.
405  std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
406
407  if (!CaseVals.empty()) {
408    for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
409      if (CaseVals[i].first == CaseVals[i+1].first) {
410        // If we have a duplicate, report it.
411        Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
412             diag::err_duplicate_case) << CaseVals[i].first.toString(10);
413        Diag(CaseVals[i].second->getLHS()->getLocStart(),
414             diag::note_duplicate_case_prev);
415        // FIXME: We really want to remove the bogus case stmt from the substmt,
416        // but we have no way to do this right now.
417        CaseListIsErroneous = true;
418      }
419    }
420  }
421
422  // Detect duplicate case ranges, which usually don't exist at all in the first
423  // place.
424  if (!CaseRanges.empty()) {
425    // Sort all the case ranges by their low value so we can easily detect
426    // overlaps between ranges.
427    std::stable_sort(CaseRanges.begin(), CaseRanges.end());
428
429    // Scan the ranges, computing the high values and removing empty ranges.
430    std::vector<llvm::APSInt> HiVals;
431    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
432      CaseStmt *CR = CaseRanges[i].second;
433      Expr *Hi = CR->getRHS();
434      llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
435
436      // Convert the value to the same width/sign as the condition.
437      ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
438                                         CR->getRHS()->getLocStart(),
439                                         diag::warn_case_value_overflow);
440
441      // If the LHS is not the same type as the condition, insert an implicit
442      // cast.
443      ImpCastExprToType(Hi, CondType);
444      CR->setRHS(Hi);
445
446      // If the low value is bigger than the high value, the case is empty.
447      if (CaseRanges[i].first > HiVal) {
448        Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
449          << SourceRange(CR->getLHS()->getLocStart(),
450                         CR->getRHS()->getLocEnd());
451        CaseRanges.erase(CaseRanges.begin()+i);
452        --i, --e;
453        continue;
454      }
455      HiVals.push_back(HiVal);
456    }
457
458    // Rescan the ranges, looking for overlap with singleton values and other
459    // ranges.  Since the range list is sorted, we only need to compare case
460    // ranges with their neighbors.
461    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
462      llvm::APSInt &CRLo = CaseRanges[i].first;
463      llvm::APSInt &CRHi = HiVals[i];
464      CaseStmt *CR = CaseRanges[i].second;
465
466      // Check to see whether the case range overlaps with any singleton cases.
467      CaseStmt *OverlapStmt = 0;
468      llvm::APSInt OverlapVal(32);
469
470      // Find the smallest value >= the lower bound.  If I is in the case range,
471      // then we have overlap.
472      CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
473                                                CaseVals.end(), CRLo,
474                                                CaseCompareFunctor());
475      if (I != CaseVals.end() && I->first < CRHi) {
476        OverlapVal  = I->first;   // Found overlap with scalar.
477        OverlapStmt = I->second;
478      }
479
480      // Find the smallest value bigger than the upper bound.
481      I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
482      if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
483        OverlapVal  = (I-1)->first;      // Found overlap with scalar.
484        OverlapStmt = (I-1)->second;
485      }
486
487      // Check to see if this case stmt overlaps with the subsequent case range.
488      if (i && CRLo <= HiVals[i-1]) {
489        OverlapVal  = HiVals[i-1];       // Found overlap with range.
490        OverlapStmt = CaseRanges[i-1].second;
491      }
492
493      if (OverlapStmt) {
494        // If we have a duplicate, report it.
495        Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
496          << OverlapVal.toString(10);
497        Diag(OverlapStmt->getLHS()->getLocStart(),
498             diag::note_duplicate_case_prev);
499        // FIXME: We really want to remove the bogus case stmt from the substmt,
500        // but we have no way to do this right now.
501        CaseListIsErroneous = true;
502      }
503    }
504  }
505
506  // FIXME: If the case list was broken is some way, we don't have a good system
507  // to patch it up.  Instead, just return the whole substmt as broken.
508  if (CaseListIsErroneous)
509    return StmtError();
510
511  Switch.release();
512  return Owned(SS);
513}
514
515Action::OwningStmtResult
516Sema::ActOnWhileStmt(SourceLocation WhileLoc, ExprArg Cond, StmtArg Body) {
517  Expr *condExpr = (Expr *)Cond.release();
518  assert(condExpr && "ActOnWhileStmt(): missing expression");
519
520  DefaultFunctionArrayConversion(condExpr);
521  Cond = condExpr;
522  QualType condType = condExpr->getType();
523
524  if (getLangOptions().CPlusPlus) {
525    if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
526      return StmtError();
527  } else if (!condType->isScalarType()) // C99 6.8.5p2
528    return StmtError(Diag(WhileLoc,
529      diag::err_typecheck_statement_requires_scalar)
530      << condType << condExpr->getSourceRange());
531
532  Cond.release();
533  return Owned(new (Context) WhileStmt(condExpr, (Stmt*)Body.release(),
534                                       WhileLoc));
535}
536
537Action::OwningStmtResult
538Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
539                  SourceLocation WhileLoc, ExprArg Cond) {
540  Expr *condExpr = (Expr *)Cond.release();
541  assert(condExpr && "ActOnDoStmt(): missing expression");
542
543  DefaultFunctionArrayConversion(condExpr);
544  Cond = condExpr;
545  QualType condType = condExpr->getType();
546
547  if (getLangOptions().CPlusPlus) {
548    if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
549      return StmtError();
550  } else if (!condType->isScalarType()) // C99 6.8.5p2
551    return StmtError(Diag(DoLoc, diag::err_typecheck_statement_requires_scalar)
552      << condType << condExpr->getSourceRange());
553
554  Cond.release();
555  return Owned(new (Context) DoStmt((Stmt*)Body.release(), condExpr, DoLoc));
556}
557
558Action::OwningStmtResult
559Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
560                   StmtArg first, ExprArg second, ExprArg third,
561                   SourceLocation RParenLoc, StmtArg body) {
562  Stmt *First  = static_cast<Stmt*>(first.get());
563  Expr *Second = static_cast<Expr*>(second.get());
564  Expr *Third  = static_cast<Expr*>(third.get());
565  Stmt *Body  = static_cast<Stmt*>(body.get());
566
567  if (!getLangOptions().CPlusPlus) {
568    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
569      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
570      // declare identifiers for objects having storage class 'auto' or
571      // 'register'.
572      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
573           DI!=DE; ++DI) {
574        VarDecl *VD = dyn_cast<VarDecl>(*DI);
575        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
576          VD = 0;
577        if (VD == 0)
578          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
579        // FIXME: mark decl erroneous!
580      }
581    }
582  }
583  if (Second) {
584    DefaultFunctionArrayConversion(Second);
585    QualType SecondType = Second->getType();
586
587    if (getLangOptions().CPlusPlus) {
588      if (CheckCXXBooleanCondition(Second)) // C++ 6.4p4
589        return StmtError();
590    } else if (!SecondType->isScalarType()) // C99 6.8.5p2
591      return StmtError(Diag(ForLoc,
592                            diag::err_typecheck_statement_requires_scalar)
593        << SecondType << Second->getSourceRange());
594  }
595  first.release();
596  second.release();
597  third.release();
598  body.release();
599  return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc));
600}
601
602Action::OwningStmtResult
603Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
604                                 SourceLocation LParenLoc,
605                                 StmtArg first, ExprArg second,
606                                 SourceLocation RParenLoc, StmtArg body) {
607  Stmt *First  = static_cast<Stmt*>(first.get());
608  Expr *Second = static_cast<Expr*>(second.get());
609  Stmt *Body  = static_cast<Stmt*>(body.get());
610  if (First) {
611    QualType FirstType;
612    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
613      if (!DS->isSingleDecl())
614        return StmtError(Diag((*DS->decl_begin())->getLocation(),
615                         diag::err_toomany_element_decls));
616
617      Decl *D = DS->getSingleDecl();
618      FirstType = cast<ValueDecl>(D)->getType();
619      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
620      // declare identifiers for objects having storage class 'auto' or
621      // 'register'.
622      VarDecl *VD = cast<VarDecl>(D);
623      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
624        return StmtError(Diag(VD->getLocation(),
625                              diag::err_non_variable_decl_in_for));
626    } else {
627      if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
628        return StmtError(Diag(First->getLocStart(),
629                   diag::err_selector_element_not_lvalue)
630          << First->getSourceRange());
631
632      FirstType = static_cast<Expr*>(First)->getType();
633    }
634    if (!Context.isObjCObjectPointerType(FirstType))
635        Diag(ForLoc, diag::err_selector_element_type)
636          << FirstType << First->getSourceRange();
637  }
638  if (Second) {
639    DefaultFunctionArrayConversion(Second);
640    QualType SecondType = Second->getType();
641    if (!Context.isObjCObjectPointerType(SecondType))
642      Diag(ForLoc, diag::err_collection_expr_type)
643        << SecondType << Second->getSourceRange();
644  }
645  first.release();
646  second.release();
647  body.release();
648  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
649                                                   ForLoc, RParenLoc));
650}
651
652Action::OwningStmtResult
653Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
654                    IdentifierInfo *LabelII) {
655  // If we are in a block, reject all gotos for now.
656  if (CurBlock)
657    return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
658
659  // Look up the record for this label identifier.
660  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
661
662  // If we haven't seen this label yet, create a forward reference.
663  if (LabelDecl == 0)
664    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
665
666  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
667}
668
669Action::OwningStmtResult
670Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
671                            ExprArg DestExp) {
672  // Convert operand to void*
673  Expr* E = DestExp.takeAs<Expr>();
674  QualType ETy = E->getType();
675  AssignConvertType ConvTy =
676        CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
677  if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
678                               E, "passing"))
679    return StmtError();
680  return Owned(new (Context) IndirectGotoStmt(GotoLoc, E));
681}
682
683Action::OwningStmtResult
684Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
685  Scope *S = CurScope->getContinueParent();
686  if (!S) {
687    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
688    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
689  }
690
691  return Owned(new (Context) ContinueStmt(ContinueLoc));
692}
693
694Action::OwningStmtResult
695Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
696  Scope *S = CurScope->getBreakParent();
697  if (!S) {
698    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
699    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
700  }
701
702  return Owned(new (Context) BreakStmt(BreakLoc));
703}
704
705/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
706///
707Action::OwningStmtResult
708Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
709
710  // If this is the first return we've seen in the block, infer the type of
711  // the block from it.
712  if (CurBlock->ReturnType == 0) {
713    if (RetValExp) {
714      // Don't call UsualUnaryConversions(), since we don't want to do
715      // integer promotions here.
716      DefaultFunctionArrayConversion(RetValExp);
717      CurBlock->ReturnType = RetValExp->getType().getTypePtr();
718    } else
719      CurBlock->ReturnType = Context.VoidTy.getTypePtr();
720  }
721  QualType FnRetType = QualType(CurBlock->ReturnType, 0);
722
723  // Otherwise, verify that this result type matches the previous one.  We are
724  // pickier with blocks than for normal functions because we don't have GCC
725  // compatibility to worry about here.
726  if (CurBlock->ReturnType->isVoidType()) {
727    if (RetValExp) {
728      Diag(ReturnLoc, diag::err_return_block_has_expr);
729      RetValExp->Destroy(Context);
730      RetValExp = 0;
731    }
732    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
733  }
734
735  if (!RetValExp)
736    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
737
738  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
739    // we have a non-void block with an expression, continue checking
740    QualType RetValType = RetValExp->getType();
741
742    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
743    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
744    // function return.
745
746    // In C++ the return statement is handled via a copy initialization.
747    // the C version of which boils down to CheckSingleAssignmentConstraints.
748    // FIXME: Leaks RetValExp.
749    if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
750      return StmtError();
751
752    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
753  }
754
755  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
756}
757
758/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
759/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
760static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
761                                 Expr *RetExpr) {
762  QualType ExprType = RetExpr->getType();
763  // - in a return statement in a function with ...
764  // ... a class return type ...
765  if (!RetType->isRecordType())
766    return false;
767  // ... the same cv-unqualified type as the function return type ...
768  if (Ctx.getCanonicalType(RetType).getUnqualifiedType() !=
769      Ctx.getCanonicalType(ExprType).getUnqualifiedType())
770    return false;
771  // ... the expression is the name of a non-volatile automatic object ...
772  // We ignore parentheses here.
773  // FIXME: Is this compliant?
774  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
775  if (!DR)
776    return false;
777  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
778  if (!VD)
779    return false;
780  return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
781    && !VD->getType().isVolatileQualified();
782}
783
784Action::OwningStmtResult
785Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
786  Expr *RetValExp = static_cast<Expr *>(rex.release());
787  if (CurBlock)
788    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
789
790  QualType FnRetType;
791  if (FunctionDecl *FD = getCurFunctionDecl())
792    FnRetType = FD->getResultType();
793  else if (ObjCMethodDecl *MD = getCurMethodDecl())
794    FnRetType = MD->getResultType();
795  else // If we don't have a function/method context, bail.
796    return StmtError();
797
798  if (FnRetType->isVoidType()) {
799    if (RetValExp) {// C99 6.8.6.4p1 (ext_ since GCC warns)
800      unsigned D = diag::ext_return_has_expr;
801      if (RetValExp->getType()->isVoidType())
802        D = diag::ext_return_has_void_expr;
803
804      // return (some void expression); is legal in C++.
805      if (D != diag::ext_return_has_void_expr ||
806          !getLangOptions().CPlusPlus) {
807        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
808        Diag(ReturnLoc, D)
809          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
810          << RetValExp->getSourceRange();
811      }
812    }
813    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
814  }
815
816  if (!RetValExp) {
817    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
818    // C99 6.8.6.4p1 (ext_ since GCC warns)
819    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
820
821    if (FunctionDecl *FD = getCurFunctionDecl())
822      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
823    else
824      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
825    return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
826  }
827
828  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
829    // we have a non-void function with an expression, continue checking
830
831    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
832    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
833    // function return.
834
835    // C++0x 12.8p15: When certain criteria are met, an implementation is
836    //   allowed to omit the copy construction of a class object, [...]
837    //   - in a return statement in a function with a class return type, when
838    //     the expression is the name of a non-volatile automatic object with
839    //     the same cv-unqualified type as the function return type, the copy
840    //     operation can be omitted [...]
841    // C++0x 12.8p16: When the criteria for elision of a copy operation are met
842    //   and the object to be copied is designated by an lvalue, overload
843    //   resolution to select the constructor for the copy is first performed
844    //   as if the object were designated by an rvalue.
845    // Note that we only compute Elidable if we're in C++0x, since we don't
846    // care otherwise.
847    bool Elidable = getLangOptions().CPlusPlus0x ?
848                      IsReturnCopyElidable(Context, FnRetType, RetValExp) :
849                      false;
850
851    // In C++ the return statement is handled via a copy initialization.
852    // the C version of which boils down to CheckSingleAssignmentConstraints.
853    // FIXME: Leaks RetValExp on error.
854    if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable))
855      return StmtError();
856
857    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
858  }
859
860  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
861}
862
863/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
864/// ignore "noop" casts in places where an lvalue is required by an inline asm.
865/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
866/// provide a strong guidance to not use it.
867///
868/// This method checks to see if the argument is an acceptable l-value and
869/// returns false if it is a case we can handle.
870static bool CheckAsmLValue(const Expr *E, Sema &S) {
871  if (E->isLvalue(S.Context) == Expr::LV_Valid)
872    return false;  // Cool, this is an lvalue.
873
874  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
875  // are supposed to allow.
876  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
877  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
878    if (!S.getLangOptions().HeinousExtensions)
879      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
880        << E->getSourceRange();
881    else
882      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
883        << E->getSourceRange();
884    // Accept, even if we emitted an error diagnostic.
885    return false;
886  }
887
888  // None of the above, just randomly invalid non-lvalue.
889  return true;
890}
891
892
893Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
894                                          bool IsSimple,
895                                          bool IsVolatile,
896                                          unsigned NumOutputs,
897                                          unsigned NumInputs,
898                                          std::string *Names,
899                                          MultiExprArg constraints,
900                                          MultiExprArg exprs,
901                                          ExprArg asmString,
902                                          MultiExprArg clobbers,
903                                          SourceLocation RParenLoc) {
904  unsigned NumClobbers = clobbers.size();
905  StringLiteral **Constraints =
906    reinterpret_cast<StringLiteral**>(constraints.get());
907  Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
908  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
909  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
910
911  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
912
913  // The parser verifies that there is a string literal here.
914  if (AsmString->isWide())
915    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
916      << AsmString->getSourceRange());
917
918  for (unsigned i = 0; i != NumOutputs; i++) {
919    StringLiteral *Literal = Constraints[i];
920    if (Literal->isWide())
921      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
922        << Literal->getSourceRange());
923
924    TargetInfo::ConstraintInfo Info(Literal->getStrData(),
925                                    Literal->getByteLength(),
926                                    Names[i]);
927    if (!Context.Target.validateOutputConstraint(Info))
928      return StmtError(Diag(Literal->getLocStart(),
929                            diag::err_asm_invalid_output_constraint)
930                       << Info.getConstraintStr());
931
932    // Check that the output exprs are valid lvalues.
933    // FIXME: Operands to asms should not be parsed as ParenExprs.
934    ParenExpr *OutputExpr = cast<ParenExpr>(Exprs[i]);
935    if (CheckAsmLValue(OutputExpr, *this)) {
936      return StmtError(Diag(OutputExpr->getSubExpr()->getLocStart(),
937                  diag::err_asm_invalid_lvalue_in_output)
938        << OutputExpr->getSubExpr()->getSourceRange());
939    }
940
941    OutputConstraintInfos.push_back(Info);
942  }
943
944  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
945    StringLiteral *Literal = Constraints[i];
946    if (Literal->isWide())
947      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
948        << Literal->getSourceRange());
949
950    TargetInfo::ConstraintInfo Info(Literal->getStrData(),
951                                    Literal->getByteLength(),
952                                    Names[i]);
953    if (!Context.Target.validateInputConstraint(&OutputConstraintInfos[0],
954                                                NumOutputs, Info)) {
955      return StmtError(Diag(Literal->getLocStart(),
956                            diag::err_asm_invalid_input_constraint)
957                       << Info.getConstraintStr());
958    }
959
960    ParenExpr *InputExpr = cast<ParenExpr>(Exprs[i]);
961
962    // Only allow void types for memory constraints.
963    if (Info.allowsMemory() && !Info.allowsRegister()) {
964      if (CheckAsmLValue(InputExpr, *this))
965        return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(),
966                              diag::err_asm_invalid_lvalue_in_input)
967                         << Info.getConstraintStr()
968                         << InputExpr->getSubExpr()->getSourceRange());
969    }
970
971    if (Info.allowsRegister()) {
972      if (InputExpr->getType()->isVoidType()) {
973        return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(),
974                              diag::err_asm_invalid_type_in_input)
975          << InputExpr->getType() << Info.getConstraintStr()
976          << InputExpr->getSubExpr()->getSourceRange());
977      }
978    }
979
980    DefaultFunctionArrayConversion(Exprs[i]);
981  }
982
983  // Check that the clobbers are valid.
984  for (unsigned i = 0; i != NumClobbers; i++) {
985    StringLiteral *Literal = Clobbers[i];
986    if (Literal->isWide())
987      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
988        << Literal->getSourceRange());
989
990    llvm::SmallString<16> Clobber(Literal->getStrData(),
991                                  Literal->getStrData() +
992                                  Literal->getByteLength());
993
994    if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
995      return StmtError(Diag(Literal->getLocStart(),
996                  diag::err_asm_unknown_register_name) << Clobber.c_str());
997  }
998
999  constraints.release();
1000  exprs.release();
1001  asmString.release();
1002  clobbers.release();
1003  AsmStmt *NS =
1004    new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1005                          Names, Constraints, Exprs, AsmString, NumClobbers,
1006                          Clobbers, RParenLoc);
1007  // Validate the asm string, ensuring it makes sense given the operands we
1008  // have.
1009  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1010  unsigned DiagOffs;
1011  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1012    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1013           << AsmString->getSourceRange();
1014    DeleteStmt(NS);
1015    return StmtError();
1016  }
1017
1018
1019  return Owned(NS);
1020}
1021
1022Action::OwningStmtResult
1023Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1024                           SourceLocation RParen, DeclPtrTy Parm,
1025                           StmtArg Body, StmtArg catchList) {
1026  Stmt *CatchList = static_cast<Stmt*>(catchList.release());
1027  ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
1028
1029  // PVD == 0 implies @catch(...).
1030  if (PVD) {
1031    // If we already know the decl is invalid, reject it.
1032    if (PVD->isInvalidDecl())
1033      return StmtError();
1034
1035    if (!Context.isObjCObjectPointerType(PVD->getType()))
1036      return StmtError(Diag(PVD->getLocation(),
1037                       diag::err_catch_param_not_objc_type));
1038    if (PVD->getType()->isObjCQualifiedIdType())
1039      return StmtError(Diag(PVD->getLocation(),
1040                       diag::err_illegal_qualifiers_on_catch_parm));
1041  }
1042
1043  ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
1044    PVD, static_cast<Stmt*>(Body.release()), CatchList);
1045  return Owned(CatchList ? CatchList : CS);
1046}
1047
1048Action::OwningStmtResult
1049Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1050  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1051                                           static_cast<Stmt*>(Body.release())));
1052}
1053
1054Action::OwningStmtResult
1055Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1056                         StmtArg Try, StmtArg Catch, StmtArg Finally) {
1057  CurFunctionNeedsScopeChecking = true;
1058  return Owned(new (Context) ObjCAtTryStmt(AtLoc,
1059                                        static_cast<Stmt*>(Try.release()),
1060                                        static_cast<Stmt*>(Catch.release()),
1061                                        static_cast<Stmt*>(Finally.release())));
1062}
1063
1064Action::OwningStmtResult
1065Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
1066  Expr *ThrowExpr = static_cast<Expr*>(expr.release());
1067  if (!ThrowExpr) {
1068    // @throw without an expression designates a rethrow (which much occur
1069    // in the context of an @catch clause).
1070    Scope *AtCatchParent = CurScope;
1071    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1072      AtCatchParent = AtCatchParent->getParent();
1073    if (!AtCatchParent)
1074      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1075  } else {
1076    QualType ThrowType = ThrowExpr->getType();
1077    // Make sure the expression type is an ObjC pointer or "void *".
1078    if (!Context.isObjCObjectPointerType(ThrowType)) {
1079      const PointerType *PT = ThrowType->getAsPointerType();
1080      if (!PT || !PT->getPointeeType()->isVoidType())
1081        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1082                        << ThrowExpr->getType() << ThrowExpr->getSourceRange());
1083    }
1084  }
1085  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
1086}
1087
1088Action::OwningStmtResult
1089Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1090                                  StmtArg SynchBody) {
1091  CurFunctionNeedsScopeChecking = true;
1092
1093  // Make sure the expression type is an ObjC pointer or "void *".
1094  Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1095  if (!Context.isObjCObjectPointerType(SyncExpr->getType())) {
1096    const PointerType *PT = SyncExpr->getType()->getAsPointerType();
1097    if (!PT || !PT->getPointeeType()->isVoidType())
1098      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1099                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1100  }
1101
1102  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1103                     static_cast<Stmt*>(SynchExpr.release()),
1104                     static_cast<Stmt*>(SynchBody.release())));
1105}
1106
1107/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1108/// and creates a proper catch handler from them.
1109Action::OwningStmtResult
1110Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1111                         StmtArg HandlerBlock) {
1112  // There's nothing to test that ActOnExceptionDecl didn't already test.
1113  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1114                                  cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1115                                  static_cast<Stmt*>(HandlerBlock.release())));
1116}
1117
1118/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1119/// handlers and creates a try statement from them.
1120Action::OwningStmtResult
1121Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1122                       MultiStmtArg RawHandlers) {
1123  unsigned NumHandlers = RawHandlers.size();
1124  assert(NumHandlers > 0 &&
1125         "The parser shouldn't call this if there are no handlers.");
1126  Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1127
1128  for(unsigned i = 0; i < NumHandlers - 1; ++i) {
1129    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1130    if (!Handler->getExceptionDecl())
1131      return StmtError(Diag(Handler->getLocStart(), diag::err_early_catch_all));
1132  }
1133  // FIXME: We should detect handlers for the same type as an earlier one.
1134  // This one is rather easy.
1135  // FIXME: We should detect handlers that cannot catch anything because an
1136  // earlier handler catches a superclass. Need to find a method that is not
1137  // quadratic for this.
1138  // Neither of these are explicitly forbidden, but every compiler detects them
1139  // and warns.
1140
1141  RawHandlers.release();
1142  return Owned(new (Context) CXXTryStmt(TryLoc,
1143                                        static_cast<Stmt*>(TryBlock.release()),
1144                                        Handlers, NumHandlers));
1145}
1146