SemaStmt.cpp revision bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6
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
371Action::OwningStmtResult
372Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
373                            StmtArg Body) {
374  Stmt *BodyStmt = Body.takeAs<Stmt>();
375
376  SwitchStmt *SS = getSwitchStack().back();
377  assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
378
379  SS->setBody(BodyStmt, SwitchLoc);
380  getSwitchStack().pop_back();
381
382  Expr *CondExpr = SS->getCond();
383  QualType CondType = CondExpr->getType();
384
385  if (!CondExpr->isTypeDependent() &&
386      !CondType->isIntegerType()) { // C99 6.8.4.2p1
387    Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
388      << CondType << CondExpr->getSourceRange();
389    return StmtError();
390  }
391
392  // Get the bitwidth of the switched-on value before promotions.  We must
393  // convert the integer case values to this width before comparison.
394  bool HasDependentValue
395    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
396  unsigned CondWidth
397    = HasDependentValue? 0
398                       : static_cast<unsigned>(Context.getTypeSize(CondType));
399  bool CondIsSigned = CondType->isSignedIntegerType();
400
401  // Accumulate all of the case values in a vector so that we can sort them
402  // and detect duplicates.  This vector contains the APInt for the case after
403  // it has been converted to the condition type.
404  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
405  CaseValsTy CaseVals;
406
407  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
408  std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
409
410  DefaultStmt *TheDefaultStmt = 0;
411
412  bool CaseListIsErroneous = false;
413
414  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
415       SC = SC->getNextSwitchCase()) {
416
417    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
418      if (TheDefaultStmt) {
419        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
420        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
421
422        // FIXME: Remove the default statement from the switch block so that
423        // we'll return a valid AST.  This requires recursing down the AST and
424        // finding it, not something we are set up to do right now.  For now,
425        // just lop the entire switch stmt out of the AST.
426        CaseListIsErroneous = true;
427      }
428      TheDefaultStmt = DS;
429
430    } else {
431      CaseStmt *CS = cast<CaseStmt>(SC);
432
433      // We already verified that the expression has a i-c-e value (C99
434      // 6.8.4.2p3) - get that value now.
435      Expr *Lo = CS->getLHS();
436
437      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
438        HasDependentValue = true;
439        break;
440      }
441
442      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
443
444      // Convert the value to the same width/sign as the condition.
445      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
446                                         CS->getLHS()->getLocStart(),
447                                         diag::warn_case_value_overflow);
448
449      // If the LHS is not the same type as the condition, insert an implicit
450      // cast.
451      ImpCastExprToType(Lo, CondType);
452      CS->setLHS(Lo);
453
454      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
455      if (CS->getRHS()) {
456        if (CS->getRHS()->isTypeDependent() ||
457            CS->getRHS()->isValueDependent()) {
458          HasDependentValue = true;
459          break;
460        }
461        CaseRanges.push_back(std::make_pair(LoVal, CS));
462      } else
463        CaseVals.push_back(std::make_pair(LoVal, CS));
464    }
465  }
466
467  if (!HasDependentValue) {
468    // Sort all the scalar case values so we can easily detect duplicates.
469    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
470
471    if (!CaseVals.empty()) {
472      for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
473        if (CaseVals[i].first == CaseVals[i+1].first) {
474          // If we have a duplicate, report it.
475          Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
476               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
477          Diag(CaseVals[i].second->getLHS()->getLocStart(),
478               diag::note_duplicate_case_prev);
479          // FIXME: We really want to remove the bogus case stmt from the
480          // substmt, but we have no way to do this right now.
481          CaseListIsErroneous = true;
482        }
483      }
484    }
485
486    // Detect duplicate case ranges, which usually don't exist at all in
487    // the first place.
488    if (!CaseRanges.empty()) {
489      // Sort all the case ranges by their low value so we can easily detect
490      // overlaps between ranges.
491      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
492
493      // Scan the ranges, computing the high values and removing empty ranges.
494      std::vector<llvm::APSInt> HiVals;
495      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
496        CaseStmt *CR = CaseRanges[i].second;
497        Expr *Hi = CR->getRHS();
498        llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
499
500        // Convert the value to the same width/sign as the condition.
501        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
502                                           CR->getRHS()->getLocStart(),
503                                           diag::warn_case_value_overflow);
504
505        // If the LHS is not the same type as the condition, insert an implicit
506        // cast.
507        ImpCastExprToType(Hi, CondType);
508        CR->setRHS(Hi);
509
510        // If the low value is bigger than the high value, the case is empty.
511        if (CaseRanges[i].first > HiVal) {
512          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
513            << SourceRange(CR->getLHS()->getLocStart(),
514                           CR->getRHS()->getLocEnd());
515          CaseRanges.erase(CaseRanges.begin()+i);
516          --i, --e;
517          continue;
518        }
519        HiVals.push_back(HiVal);
520      }
521
522      // Rescan the ranges, looking for overlap with singleton values and other
523      // ranges.  Since the range list is sorted, we only need to compare case
524      // ranges with their neighbors.
525      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
526        llvm::APSInt &CRLo = CaseRanges[i].first;
527        llvm::APSInt &CRHi = HiVals[i];
528        CaseStmt *CR = CaseRanges[i].second;
529
530        // Check to see whether the case range overlaps with any
531        // singleton cases.
532        CaseStmt *OverlapStmt = 0;
533        llvm::APSInt OverlapVal(32);
534
535        // Find the smallest value >= the lower bound.  If I is in the
536        // case range, then we have overlap.
537        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
538                                                  CaseVals.end(), CRLo,
539                                                  CaseCompareFunctor());
540        if (I != CaseVals.end() && I->first < CRHi) {
541          OverlapVal  = I->first;   // Found overlap with scalar.
542          OverlapStmt = I->second;
543        }
544
545        // Find the smallest value bigger than the upper bound.
546        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
547        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
548          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
549          OverlapStmt = (I-1)->second;
550        }
551
552        // Check to see if this case stmt overlaps with the subsequent
553        // case range.
554        if (i && CRLo <= HiVals[i-1]) {
555          OverlapVal  = HiVals[i-1];       // Found overlap with range.
556          OverlapStmt = CaseRanges[i-1].second;
557        }
558
559        if (OverlapStmt) {
560          // If we have a duplicate, report it.
561          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
562            << OverlapVal.toString(10);
563          Diag(OverlapStmt->getLHS()->getLocStart(),
564               diag::note_duplicate_case_prev);
565          // FIXME: We really want to remove the bogus case stmt from the
566          // substmt, but we have no way to do this right now.
567          CaseListIsErroneous = true;
568        }
569      }
570    }
571  }
572
573  // FIXME: If the case list was broken is some way, we don't have a good system
574  // to patch it up.  Instead, just return the whole substmt as broken.
575  if (CaseListIsErroneous)
576    return StmtError();
577
578  Switch.release();
579  return Owned(SS);
580}
581
582Action::OwningStmtResult
583Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, StmtArg Body) {
584  ExprArg CondArg(Cond.release());
585  Expr *condExpr = CondArg.takeAs<Expr>();
586  assert(condExpr && "ActOnWhileStmt(): missing expression");
587
588  if (CheckBooleanCondition(condExpr, WhileLoc)) {
589    CondArg = condExpr;
590    return StmtError();
591  }
592
593  Stmt *bodyStmt = Body.takeAs<Stmt>();
594  DiagnoseUnusedExprResult(bodyStmt);
595
596  CondArg.release();
597  return Owned(new (Context) WhileStmt(condExpr, bodyStmt, WhileLoc));
598}
599
600Action::OwningStmtResult
601Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
602                  SourceLocation WhileLoc, SourceLocation CondLParen,
603                  ExprArg Cond, SourceLocation CondRParen) {
604  Expr *condExpr = Cond.takeAs<Expr>();
605  assert(condExpr && "ActOnDoStmt(): missing expression");
606
607  if (CheckBooleanCondition(condExpr, DoLoc)) {
608    Cond = condExpr;
609    return StmtError();
610  }
611
612  Stmt *bodyStmt = Body.takeAs<Stmt>();
613  DiagnoseUnusedExprResult(bodyStmt);
614
615  Cond.release();
616  return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
617                                    WhileLoc, CondRParen));
618}
619
620Action::OwningStmtResult
621Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
622                   StmtArg first, ExprArg second, ExprArg third,
623                   SourceLocation RParenLoc, StmtArg body) {
624  Stmt *First  = static_cast<Stmt*>(first.get());
625  Expr *Second = second.takeAs<Expr>();
626  Expr *Third  = static_cast<Expr*>(third.get());
627  Stmt *Body  = static_cast<Stmt*>(body.get());
628
629  if (!getLangOptions().CPlusPlus) {
630    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
631      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
632      // declare identifiers for objects having storage class 'auto' or
633      // 'register'.
634      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
635           DI!=DE; ++DI) {
636        VarDecl *VD = dyn_cast<VarDecl>(*DI);
637        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
638          VD = 0;
639        if (VD == 0)
640          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
641        // FIXME: mark decl erroneous!
642      }
643    }
644  }
645  if (Second && CheckBooleanCondition(Second, ForLoc)) {
646    second = Second;
647    return StmtError();
648  }
649
650  DiagnoseUnusedExprResult(First);
651  DiagnoseUnusedExprResult(Third);
652  DiagnoseUnusedExprResult(Body);
653
654  first.release();
655  third.release();
656  body.release();
657  return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc,
658                                     LParenLoc, RParenLoc));
659}
660
661Action::OwningStmtResult
662Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
663                                 SourceLocation LParenLoc,
664                                 StmtArg first, ExprArg second,
665                                 SourceLocation RParenLoc, StmtArg body) {
666  Stmt *First  = static_cast<Stmt*>(first.get());
667  Expr *Second = static_cast<Expr*>(second.get());
668  Stmt *Body  = static_cast<Stmt*>(body.get());
669  if (First) {
670    QualType FirstType;
671    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
672      if (!DS->isSingleDecl())
673        return StmtError(Diag((*DS->decl_begin())->getLocation(),
674                         diag::err_toomany_element_decls));
675
676      Decl *D = DS->getSingleDecl();
677      FirstType = cast<ValueDecl>(D)->getType();
678      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
679      // declare identifiers for objects having storage class 'auto' or
680      // 'register'.
681      VarDecl *VD = cast<VarDecl>(D);
682      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
683        return StmtError(Diag(VD->getLocation(),
684                              diag::err_non_variable_decl_in_for));
685    } else {
686      if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
687        return StmtError(Diag(First->getLocStart(),
688                   diag::err_selector_element_not_lvalue)
689          << First->getSourceRange());
690
691      FirstType = static_cast<Expr*>(First)->getType();
692    }
693    if (!FirstType->isObjCObjectPointerType() &&
694        !FirstType->isBlockPointerType())
695        Diag(ForLoc, diag::err_selector_element_type)
696          << FirstType << First->getSourceRange();
697  }
698  if (Second) {
699    DefaultFunctionArrayConversion(Second);
700    QualType SecondType = Second->getType();
701    if (!SecondType->isObjCObjectPointerType())
702      Diag(ForLoc, diag::err_collection_expr_type)
703        << SecondType << Second->getSourceRange();
704  }
705  first.release();
706  second.release();
707  body.release();
708  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
709                                                   ForLoc, RParenLoc));
710}
711
712Action::OwningStmtResult
713Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
714                    IdentifierInfo *LabelII) {
715  // If we are in a block, reject all gotos for now.
716  if (CurBlock)
717    return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
718
719  // Look up the record for this label identifier.
720  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
721
722  // If we haven't seen this label yet, create a forward reference.
723  if (LabelDecl == 0)
724    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
725
726  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
727}
728
729Action::OwningStmtResult
730Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
731                            ExprArg DestExp) {
732  // Convert operand to void*
733  Expr* E = DestExp.takeAs<Expr>();
734  if (!E->isTypeDependent()) {
735    QualType ETy = E->getType();
736    AssignConvertType ConvTy =
737      CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
738    if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
739                                 E, "passing"))
740      return StmtError();
741  }
742  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
743}
744
745Action::OwningStmtResult
746Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
747  Scope *S = CurScope->getContinueParent();
748  if (!S) {
749    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
750    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
751  }
752
753  return Owned(new (Context) ContinueStmt(ContinueLoc));
754}
755
756Action::OwningStmtResult
757Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
758  Scope *S = CurScope->getBreakParent();
759  if (!S) {
760    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
761    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
762  }
763
764  return Owned(new (Context) BreakStmt(BreakLoc));
765}
766
767/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
768///
769Action::OwningStmtResult
770Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
771  // If this is the first return we've seen in the block, infer the type of
772  // the block from it.
773  if (CurBlock->ReturnType.isNull()) {
774    if (RetValExp) {
775      // Don't call UsualUnaryConversions(), since we don't want to do
776      // integer promotions here.
777      DefaultFunctionArrayConversion(RetValExp);
778      CurBlock->ReturnType = RetValExp->getType();
779      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
780        // We have to remove a 'const' added to copied-in variable which was
781        // part of the implementation spec. and not the actual qualifier for
782        // the variable.
783        if (CDRE->isConstQualAdded())
784           CurBlock->ReturnType.removeConst();
785      }
786    } else
787      CurBlock->ReturnType = Context.VoidTy;
788  }
789  QualType FnRetType = CurBlock->ReturnType;
790
791  if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
792    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
793      << getCurFunctionOrMethodDecl()->getDeclName();
794    return StmtError();
795  }
796
797  // Otherwise, verify that this result type matches the previous one.  We are
798  // pickier with blocks than for normal functions because we don't have GCC
799  // compatibility to worry about here.
800  if (CurBlock->ReturnType->isVoidType()) {
801    if (RetValExp) {
802      Diag(ReturnLoc, diag::err_return_block_has_expr);
803      RetValExp->Destroy(Context);
804      RetValExp = 0;
805    }
806    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
807  }
808
809  if (!RetValExp)
810    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
811
812  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
813    // we have a non-void block with an expression, continue checking
814    QualType RetValType = RetValExp->getType();
815
816    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
817    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
818    // function return.
819
820    // In C++ the return statement is handled via a copy initialization.
821    // the C version of which boils down to CheckSingleAssignmentConstraints.
822    // FIXME: Leaks RetValExp.
823    if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
824      return StmtError();
825
826    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
827  }
828
829  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
830}
831
832/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
833/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
834static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
835                                 Expr *RetExpr) {
836  QualType ExprType = RetExpr->getType();
837  // - in a return statement in a function with ...
838  // ... a class return type ...
839  if (!RetType->isRecordType())
840    return false;
841  // ... the same cv-unqualified type as the function return type ...
842  if (Ctx.getCanonicalType(RetType).getUnqualifiedType() !=
843      Ctx.getCanonicalType(ExprType).getUnqualifiedType())
844    return false;
845  // ... the expression is the name of a non-volatile automatic object ...
846  // We ignore parentheses here.
847  // FIXME: Is this compliant?
848  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
849  if (!DR)
850    return false;
851  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
852  if (!VD)
853    return false;
854  return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
855    && !VD->getType().isVolatileQualified();
856}
857
858Action::OwningStmtResult
859Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
860  Expr *RetValExp = rex.takeAs<Expr>();
861  if (CurBlock)
862    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
863
864  QualType FnRetType;
865  if (const FunctionDecl *FD = getCurFunctionDecl()) {
866    FnRetType = FD->getResultType();
867    if (FD->hasAttr<NoReturnAttr>())
868      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
869        << getCurFunctionOrMethodDecl()->getDeclName();
870  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
871    FnRetType = MD->getResultType();
872  else // If we don't have a function/method context, bail.
873    return StmtError();
874
875  if (FnRetType->isVoidType()) {
876    if (RetValExp && !RetValExp->isTypeDependent()) {
877      // C99 6.8.6.4p1 (ext_ since GCC warns)
878      unsigned D = diag::ext_return_has_expr;
879      if (RetValExp->getType()->isVoidType())
880        D = diag::ext_return_has_void_expr;
881
882      // return (some void expression); is legal in C++.
883      if (D != diag::ext_return_has_void_expr ||
884          !getLangOptions().CPlusPlus) {
885        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
886        Diag(ReturnLoc, D)
887          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
888          << RetValExp->getSourceRange();
889      }
890
891      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
892    }
893    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
894  }
895
896  if (!RetValExp && !FnRetType->isDependentType()) {
897    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
898    // C99 6.8.6.4p1 (ext_ since GCC warns)
899    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
900
901    if (FunctionDecl *FD = getCurFunctionDecl())
902      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
903    else
904      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
905    return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
906  }
907
908  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
909    // we have a non-void function with an expression, continue checking
910
911    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
912    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
913    // function return.
914
915    // C++0x 12.8p15: When certain criteria are met, an implementation is
916    //   allowed to omit the copy construction of a class object, [...]
917    //   - in a return statement in a function with a class return type, when
918    //     the expression is the name of a non-volatile automatic object with
919    //     the same cv-unqualified type as the function return type, the copy
920    //     operation can be omitted [...]
921    // C++0x 12.8p16: When the criteria for elision of a copy operation are met
922    //   and the object to be copied is designated by an lvalue, overload
923    //   resolution to select the constructor for the copy is first performed
924    //   as if the object were designated by an rvalue.
925    // Note that we only compute Elidable if we're in C++0x, since we don't
926    // care otherwise.
927    bool Elidable = getLangOptions().CPlusPlus0x ?
928                      IsReturnCopyElidable(Context, FnRetType, RetValExp) :
929                      false;
930
931    // In C++ the return statement is handled via a copy initialization.
932    // the C version of which boils down to CheckSingleAssignmentConstraints.
933    // FIXME: Leaks RetValExp on error.
934    if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable))
935      return StmtError();
936
937    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
938  }
939
940  if (RetValExp)
941    RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
942  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
943}
944
945/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
946/// ignore "noop" casts in places where an lvalue is required by an inline asm.
947/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
948/// provide a strong guidance to not use it.
949///
950/// This method checks to see if the argument is an acceptable l-value and
951/// returns false if it is a case we can handle.
952static bool CheckAsmLValue(const Expr *E, Sema &S) {
953  if (E->isLvalue(S.Context) == Expr::LV_Valid)
954    return false;  // Cool, this is an lvalue.
955
956  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
957  // are supposed to allow.
958  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
959  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
960    if (!S.getLangOptions().HeinousExtensions)
961      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
962        << E->getSourceRange();
963    else
964      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
965        << E->getSourceRange();
966    // Accept, even if we emitted an error diagnostic.
967    return false;
968  }
969
970  // None of the above, just randomly invalid non-lvalue.
971  return true;
972}
973
974
975Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
976                                          bool IsSimple,
977                                          bool IsVolatile,
978                                          unsigned NumOutputs,
979                                          unsigned NumInputs,
980                                          std::string *Names,
981                                          MultiExprArg constraints,
982                                          MultiExprArg exprs,
983                                          ExprArg asmString,
984                                          MultiExprArg clobbers,
985                                          SourceLocation RParenLoc) {
986  unsigned NumClobbers = clobbers.size();
987  StringLiteral **Constraints =
988    reinterpret_cast<StringLiteral**>(constraints.get());
989  Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
990  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
991  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
992
993  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
994
995  // The parser verifies that there is a string literal here.
996  if (AsmString->isWide())
997    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
998      << AsmString->getSourceRange());
999
1000  for (unsigned i = 0; i != NumOutputs; i++) {
1001    StringLiteral *Literal = Constraints[i];
1002    if (Literal->isWide())
1003      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1004        << Literal->getSourceRange());
1005
1006    TargetInfo::ConstraintInfo Info(Literal->getStrData(),
1007                                    Literal->getByteLength(),
1008                                    Names[i]);
1009    if (!Context.Target.validateOutputConstraint(Info))
1010      return StmtError(Diag(Literal->getLocStart(),
1011                            diag::err_asm_invalid_output_constraint)
1012                       << Info.getConstraintStr());
1013
1014    // Check that the output exprs are valid lvalues.
1015    Expr *OutputExpr = Exprs[i];
1016    if (CheckAsmLValue(OutputExpr, *this)) {
1017      return StmtError(Diag(OutputExpr->getLocStart(),
1018                  diag::err_asm_invalid_lvalue_in_output)
1019        << OutputExpr->getSourceRange());
1020    }
1021
1022    OutputConstraintInfos.push_back(Info);
1023  }
1024
1025  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1026
1027  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1028    StringLiteral *Literal = Constraints[i];
1029    if (Literal->isWide())
1030      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1031        << Literal->getSourceRange());
1032
1033    TargetInfo::ConstraintInfo Info(Literal->getStrData(),
1034                                    Literal->getByteLength(),
1035                                    Names[i]);
1036    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1037                                                NumOutputs, Info)) {
1038      return StmtError(Diag(Literal->getLocStart(),
1039                            diag::err_asm_invalid_input_constraint)
1040                       << Info.getConstraintStr());
1041    }
1042
1043    Expr *InputExpr = Exprs[i];
1044
1045    // Only allow void types for memory constraints.
1046    if (Info.allowsMemory() && !Info.allowsRegister()) {
1047      if (CheckAsmLValue(InputExpr, *this))
1048        return StmtError(Diag(InputExpr->getLocStart(),
1049                              diag::err_asm_invalid_lvalue_in_input)
1050                         << Info.getConstraintStr()
1051                         << InputExpr->getSourceRange());
1052    }
1053
1054    if (Info.allowsRegister()) {
1055      if (InputExpr->getType()->isVoidType()) {
1056        return StmtError(Diag(InputExpr->getLocStart(),
1057                              diag::err_asm_invalid_type_in_input)
1058          << InputExpr->getType() << Info.getConstraintStr()
1059          << InputExpr->getSourceRange());
1060      }
1061    }
1062
1063    DefaultFunctionArrayConversion(Exprs[i]);
1064
1065    InputConstraintInfos.push_back(Info);
1066  }
1067
1068  // Check that the clobbers are valid.
1069  for (unsigned i = 0; i != NumClobbers; i++) {
1070    StringLiteral *Literal = Clobbers[i];
1071    if (Literal->isWide())
1072      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1073        << Literal->getSourceRange());
1074
1075    std::string Clobber(Literal->getStrData(),
1076                        Literal->getStrData() +
1077                        Literal->getByteLength());
1078
1079    if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
1080      return StmtError(Diag(Literal->getLocStart(),
1081                  diag::err_asm_unknown_register_name) << Clobber);
1082  }
1083
1084  constraints.release();
1085  exprs.release();
1086  asmString.release();
1087  clobbers.release();
1088  AsmStmt *NS =
1089    new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1090                          Names, Constraints, Exprs, AsmString, NumClobbers,
1091                          Clobbers, RParenLoc);
1092  // Validate the asm string, ensuring it makes sense given the operands we
1093  // have.
1094  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1095  unsigned DiagOffs;
1096  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1097    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1098           << AsmString->getSourceRange();
1099    DeleteStmt(NS);
1100    return StmtError();
1101  }
1102
1103  // Validate tied input operands for type mismatches.
1104  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1105    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1106
1107    // If this is a tied constraint, verify that the output and input have
1108    // either exactly the same type, or that they are int/ptr operands with the
1109    // same size (int/long, int*/long, are ok etc).
1110    if (!Info.hasTiedOperand()) continue;
1111
1112    unsigned TiedTo = Info.getTiedOperand();
1113    Expr *OutputExpr = Exprs[TiedTo];
1114    Expr *InputExpr = Exprs[i+NumOutputs];
1115    QualType InTy = InputExpr->getType();
1116    QualType OutTy = OutputExpr->getType();
1117    if (Context.hasSameType(InTy, OutTy))
1118      continue;  // All types can be tied to themselves.
1119
1120    // Int/ptr operands have some special cases that we allow.
1121    if ((OutTy->isIntegerType() || OutTy->isPointerType()) &&
1122        (InTy->isIntegerType() || InTy->isPointerType())) {
1123
1124      // They are ok if they are the same size.  Tying void* to int is ok if
1125      // they are the same size, for example.  This also allows tying void* to
1126      // int*.
1127      uint64_t OutSize = Context.getTypeSize(OutTy);
1128      uint64_t InSize = Context.getTypeSize(InTy);
1129      if (OutSize == InSize)
1130        continue;
1131
1132      // If the smaller input/output operand is not mentioned in the asm string,
1133      // then we can promote it and the asm string won't notice.  Check this
1134      // case now.
1135      bool SmallerValueMentioned = false;
1136      for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1137        AsmStmt::AsmStringPiece &Piece = Pieces[p];
1138        if (!Piece.isOperand()) continue;
1139
1140        // If this is a reference to the input and if the input was the smaller
1141        // one, then we have to reject this asm.
1142        if (Piece.getOperandNo() == i+NumOutputs) {
1143          if (InSize < OutSize) {
1144            SmallerValueMentioned = true;
1145            break;
1146          }
1147        }
1148
1149        // If this is a reference to the input and if the input was the smaller
1150        // one, then we have to reject this asm.
1151        if (Piece.getOperandNo() == TiedTo) {
1152          if (InSize > OutSize) {
1153            SmallerValueMentioned = true;
1154            break;
1155          }
1156        }
1157      }
1158
1159      // If the smaller value wasn't mentioned in the asm string, and if the
1160      // output was a register, just extend the shorter one to the size of the
1161      // larger one.
1162      if (!SmallerValueMentioned &&
1163          OutputConstraintInfos[TiedTo].allowsRegister())
1164        continue;
1165    }
1166
1167    Diag(InputExpr->getLocStart(),
1168         diag::err_asm_tying_incompatible_types)
1169      << InTy << OutTy << OutputExpr->getSourceRange()
1170      << InputExpr->getSourceRange();
1171    DeleteStmt(NS);
1172    return StmtError();
1173  }
1174
1175  return Owned(NS);
1176}
1177
1178Action::OwningStmtResult
1179Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1180                           SourceLocation RParen, DeclPtrTy Parm,
1181                           StmtArg Body, StmtArg catchList) {
1182  Stmt *CatchList = catchList.takeAs<Stmt>();
1183  ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
1184
1185  // PVD == 0 implies @catch(...).
1186  if (PVD) {
1187    // If we already know the decl is invalid, reject it.
1188    if (PVD->isInvalidDecl())
1189      return StmtError();
1190
1191    if (!PVD->getType()->isObjCObjectPointerType())
1192      return StmtError(Diag(PVD->getLocation(),
1193                       diag::err_catch_param_not_objc_type));
1194    if (PVD->getType()->isObjCQualifiedIdType())
1195      return StmtError(Diag(PVD->getLocation(),
1196                       diag::err_illegal_qualifiers_on_catch_parm));
1197  }
1198
1199  ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
1200    PVD, Body.takeAs<Stmt>(), CatchList);
1201  return Owned(CatchList ? CatchList : CS);
1202}
1203
1204Action::OwningStmtResult
1205Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1206  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1207                                           static_cast<Stmt*>(Body.release())));
1208}
1209
1210Action::OwningStmtResult
1211Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1212                         StmtArg Try, StmtArg Catch, StmtArg Finally) {
1213  CurFunctionNeedsScopeChecking = true;
1214  return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(),
1215                                           Catch.takeAs<Stmt>(),
1216                                           Finally.takeAs<Stmt>()));
1217}
1218
1219Action::OwningStmtResult
1220Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
1221  Expr *ThrowExpr = expr.takeAs<Expr>();
1222  if (!ThrowExpr) {
1223    // @throw without an expression designates a rethrow (which much occur
1224    // in the context of an @catch clause).
1225    Scope *AtCatchParent = CurScope;
1226    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1227      AtCatchParent = AtCatchParent->getParent();
1228    if (!AtCatchParent)
1229      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1230  } else {
1231    QualType ThrowType = ThrowExpr->getType();
1232    // Make sure the expression type is an ObjC pointer or "void *".
1233    if (!ThrowType->isObjCObjectPointerType()) {
1234      const PointerType *PT = ThrowType->getAs<PointerType>();
1235      if (!PT || !PT->getPointeeType()->isVoidType())
1236        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1237                        << ThrowExpr->getType() << ThrowExpr->getSourceRange());
1238    }
1239  }
1240  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
1241}
1242
1243Action::OwningStmtResult
1244Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1245                                  StmtArg SynchBody) {
1246  CurFunctionNeedsScopeChecking = true;
1247
1248  // Make sure the expression type is an ObjC pointer or "void *".
1249  Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1250  if (!SyncExpr->getType()->isObjCObjectPointerType()) {
1251    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1252    if (!PT || !PT->getPointeeType()->isVoidType())
1253      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1254                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1255  }
1256
1257  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1258                                                    SynchExpr.takeAs<Stmt>(),
1259                                                    SynchBody.takeAs<Stmt>()));
1260}
1261
1262/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1263/// and creates a proper catch handler from them.
1264Action::OwningStmtResult
1265Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1266                         StmtArg HandlerBlock) {
1267  // There's nothing to test that ActOnExceptionDecl didn't already test.
1268  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1269                                  cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1270                                          HandlerBlock.takeAs<Stmt>()));
1271}
1272
1273class TypeWithHandler {
1274  QualType t;
1275  CXXCatchStmt *stmt;
1276public:
1277  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1278  : t(type), stmt(statement) {}
1279
1280  // An arbitrary order is fine as long as it places identical
1281  // types next to each other.
1282  bool operator<(const TypeWithHandler &y) const {
1283    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1284      return true;
1285    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1286      return false;
1287    else
1288      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1289  }
1290
1291  bool operator==(const TypeWithHandler& other) const {
1292    return t == other.t;
1293  }
1294
1295  QualType getQualType() const { return t; }
1296  CXXCatchStmt *getCatchStmt() const { return stmt; }
1297  SourceLocation getTypeSpecStartLoc() const {
1298    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1299  }
1300};
1301
1302/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1303/// handlers and creates a try statement from them.
1304Action::OwningStmtResult
1305Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1306                       MultiStmtArg RawHandlers) {
1307  unsigned NumHandlers = RawHandlers.size();
1308  assert(NumHandlers > 0 &&
1309         "The parser shouldn't call this if there are no handlers.");
1310  Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1311
1312  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1313
1314  for (unsigned i = 0; i < NumHandlers; ++i) {
1315    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1316    if (!Handler->getExceptionDecl()) {
1317      if (i < NumHandlers - 1)
1318        return StmtError(Diag(Handler->getLocStart(),
1319                              diag::err_early_catch_all));
1320
1321      continue;
1322    }
1323
1324    const QualType CaughtType = Handler->getCaughtType();
1325    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1326    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1327  }
1328
1329  // Detect handlers for the same type as an earlier one.
1330  if (NumHandlers > 1) {
1331    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1332
1333    TypeWithHandler prev = TypesWithHandlers[0];
1334    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1335      TypeWithHandler curr = TypesWithHandlers[i];
1336
1337      if (curr == prev) {
1338        Diag(curr.getTypeSpecStartLoc(),
1339             diag::warn_exception_caught_by_earlier_handler)
1340          << curr.getCatchStmt()->getCaughtType().getAsString();
1341        Diag(prev.getTypeSpecStartLoc(),
1342             diag::note_previous_exception_handler)
1343          << prev.getCatchStmt()->getCaughtType().getAsString();
1344      }
1345
1346      prev = curr;
1347    }
1348  }
1349
1350  // FIXME: We should detect handlers that cannot catch anything because an
1351  // earlier handler catches a superclass. Need to find a method that is not
1352  // quadratic for this.
1353  // Neither of these are explicitly forbidden, but every compiler detects them
1354  // and warns.
1355
1356  CurFunctionNeedsScopeChecking = true;
1357  RawHandlers.release();
1358  return Owned(new (Context) CXXTryStmt(TryLoc,
1359                                        static_cast<Stmt*>(TryBlock.release()),
1360                                        Handlers, NumHandlers));
1361}
1362