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