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