SemaStmt.cpp revision 61478065fbcafcf5295bb0fb796c9a92f2d861e0
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            !LookupMethodInQualifiedType(CSelector, OPT, true)) {
996          // Must further look into private implementation methods.
997          if (!LookupPrivateInstanceMethod(CSelector, IDecl))
998            Diag(ForLoc, diag::warn_collection_expr_type)
999              << SecondType << CSelector << Second->getSourceRange();
1000        }
1001      }
1002    }
1003  }
1004  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1005                                                   ForLoc, RParenLoc));
1006}
1007
1008StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1009                               SourceLocation LabelLoc,
1010                               LabelDecl *TheDecl) {
1011  getCurFunction()->setHasBranchIntoScope();
1012  TheDecl->setUsed();
1013  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
1014}
1015
1016StmtResult
1017Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
1018                            Expr *E) {
1019  // Convert operand to void*
1020  if (!E->isTypeDependent()) {
1021    QualType ETy = E->getType();
1022    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1023    AssignConvertType ConvTy =
1024      CheckSingleAssignmentConstraints(DestTy, E);
1025    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
1026      return StmtError();
1027  }
1028
1029  getCurFunction()->setHasIndirectGoto();
1030
1031  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1032}
1033
1034StmtResult
1035Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1036  Scope *S = CurScope->getContinueParent();
1037  if (!S) {
1038    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1039    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1040  }
1041
1042  return Owned(new (Context) ContinueStmt(ContinueLoc));
1043}
1044
1045StmtResult
1046Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1047  Scope *S = CurScope->getBreakParent();
1048  if (!S) {
1049    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1050    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1051  }
1052
1053  return Owned(new (Context) BreakStmt(BreakLoc));
1054}
1055
1056/// \brief Determine whether the given expression is a candidate for
1057/// copy elision in either a return statement or a throw expression.
1058///
1059/// \param ReturnType If we're determining the copy elision candidate for
1060/// a return statement, this is the return type of the function. If we're
1061/// determining the copy elision candidate for a throw expression, this will
1062/// be a NULL type.
1063///
1064/// \param E The expression being returned from the function or block, or
1065/// being thrown.
1066///
1067/// \param AllowFunctionParameter
1068///
1069/// \returns The NRVO candidate variable, if the return statement may use the
1070/// NRVO, or NULL if there is no such candidate.
1071const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1072                                             Expr *E,
1073                                             bool AllowFunctionParameter) {
1074  QualType ExprType = E->getType();
1075  // - in a return statement in a function with ...
1076  // ... a class return type ...
1077  if (!ReturnType.isNull()) {
1078    if (!ReturnType->isRecordType())
1079      return 0;
1080    // ... the same cv-unqualified type as the function return type ...
1081    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1082      return 0;
1083  }
1084
1085  // ... the expression is the name of a non-volatile automatic object
1086  // (other than a function or catch-clause parameter)) ...
1087  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
1088  if (!DR)
1089    return 0;
1090  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1091  if (!VD)
1092    return 0;
1093
1094  if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
1095      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1096      !VD->getType().isVolatileQualified() &&
1097      ((VD->getKind() == Decl::Var) ||
1098       (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
1099    return VD;
1100
1101  return 0;
1102}
1103
1104/// \brief Perform the initialization of a potentially-movable value, which
1105/// is the result of return value.
1106///
1107/// This routine implements C++0x [class.copy]p33, which attempts to treat
1108/// returned lvalues as rvalues in certain cases (to prefer move construction),
1109/// then falls back to treating them as lvalues if that failed.
1110ExprResult
1111Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1112                                      const VarDecl *NRVOCandidate,
1113                                      QualType ResultType,
1114                                      Expr *Value) {
1115  // C++0x [class.copy]p33:
1116  //   When the criteria for elision of a copy operation are met or would
1117  //   be met save for the fact that the source object is a function
1118  //   parameter, and the object to be copied is designated by an lvalue,
1119  //   overload resolution to select the constructor for the copy is first
1120  //   performed as if the object were designated by an rvalue.
1121  ExprResult Res = ExprError();
1122  if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) {
1123    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
1124                              Value->getType(), CK_LValueToRValue,
1125                              Value, VK_XValue);
1126
1127    Expr *InitExpr = &AsRvalue;
1128    InitializationKind Kind
1129      = InitializationKind::CreateCopy(Value->getLocStart(),
1130                                       Value->getLocStart());
1131    InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
1132
1133    //   [...] If overload resolution fails, or if the type of the first
1134    //   parameter of the selected constructor is not an rvalue reference
1135    //   to the object's type (possibly cv-qualified), overload resolution
1136    //   is performed again, considering the object as an lvalue.
1137    if (Seq.getKind() != InitializationSequence::FailedSequence) {
1138      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1139           StepEnd = Seq.step_end();
1140           Step != StepEnd; ++Step) {
1141        if (Step->Kind
1142            != InitializationSequence::SK_ConstructorInitialization)
1143          continue;
1144
1145        CXXConstructorDecl *Constructor
1146        = cast<CXXConstructorDecl>(Step->Function.Function);
1147
1148        const RValueReferenceType *RRefType
1149          = Constructor->getParamDecl(0)->getType()
1150                                                 ->getAs<RValueReferenceType>();
1151
1152        // If we don't meet the criteria, break out now.
1153        if (!RRefType ||
1154            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1155                            Context.getTypeDeclType(Constructor->getParent())))
1156          break;
1157
1158        // Promote "AsRvalue" to the heap, since we now need this
1159        // expression node to persist.
1160        Value = ImplicitCastExpr::Create(Context, Value->getType(),
1161                                         CK_LValueToRValue, Value, 0,
1162                                         VK_XValue);
1163
1164        // Complete type-checking the initialization of the return type
1165        // using the constructor we found.
1166        Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
1167      }
1168    }
1169  }
1170
1171  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
1172  // above, or overload resolution failed. Either way, we need to try
1173  // (again) now with the return value expression as written.
1174  if (Res.isInvalid())
1175    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
1176
1177  return Res;
1178}
1179
1180/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1181///
1182StmtResult
1183Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1184  // If this is the first return we've seen in the block, infer the type of
1185  // the block from it.
1186  BlockScopeInfo *CurBlock = getCurBlock();
1187  if (CurBlock->ReturnType.isNull()) {
1188    if (RetValExp) {
1189      // Don't call UsualUnaryConversions(), since we don't want to do
1190      // integer promotions here.
1191      DefaultFunctionArrayLvalueConversion(RetValExp);
1192      CurBlock->ReturnType = RetValExp->getType();
1193      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1194        // We have to remove a 'const' added to copied-in variable which was
1195        // part of the implementation spec. and not the actual qualifier for
1196        // the variable.
1197        if (CDRE->isConstQualAdded())
1198          CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1199      }
1200    } else
1201      CurBlock->ReturnType = Context.VoidTy;
1202  }
1203  QualType FnRetType = CurBlock->ReturnType;
1204
1205  if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
1206    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1207      << getCurFunctionOrMethodDecl()->getDeclName();
1208    return StmtError();
1209  }
1210
1211  // Otherwise, verify that this result type matches the previous one.  We are
1212  // pickier with blocks than for normal functions because we don't have GCC
1213  // compatibility to worry about here.
1214  ReturnStmt *Result = 0;
1215  if (CurBlock->ReturnType->isVoidType()) {
1216    if (RetValExp) {
1217      Diag(ReturnLoc, diag::err_return_block_has_expr);
1218      RetValExp = 0;
1219    }
1220    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1221  } else if (!RetValExp) {
1222    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1223  } else {
1224    const VarDecl *NRVOCandidate = 0;
1225
1226    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1227      // we have a non-void block with an expression, continue checking
1228
1229      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1230      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1231      // function return.
1232
1233      // In C++ the return statement is handled via a copy initialization.
1234      // the C version of which boils down to CheckSingleAssignmentConstraints.
1235      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1236      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1237                                                                     FnRetType,
1238                                                           NRVOCandidate != 0);
1239      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1240                                                       FnRetType, RetValExp);
1241      if (Res.isInvalid()) {
1242        // FIXME: Cleanup temporaries here, anyway?
1243        return StmtError();
1244      }
1245
1246      if (RetValExp) {
1247        CheckImplicitConversions(RetValExp, ReturnLoc);
1248        RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1249      }
1250
1251      RetValExp = Res.takeAs<Expr>();
1252      if (RetValExp)
1253        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1254    }
1255
1256    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1257  }
1258
1259  // If we need to check for the named return value optimization, save the
1260  // return statement in our scope for later processing.
1261  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1262      !CurContext->isDependentContext())
1263    FunctionScopes.back()->Returns.push_back(Result);
1264
1265  return Owned(Result);
1266}
1267
1268StmtResult
1269Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1270  if (getCurBlock())
1271    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1272
1273  QualType FnRetType;
1274  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1275    FnRetType = FD->getResultType();
1276    if (FD->hasAttr<NoReturnAttr>() ||
1277        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1278      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1279        << getCurFunctionOrMethodDecl()->getDeclName();
1280  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1281    FnRetType = MD->getResultType();
1282  else // If we don't have a function/method context, bail.
1283    return StmtError();
1284
1285  ReturnStmt *Result = 0;
1286  if (FnRetType->isVoidType()) {
1287    if (RetValExp && !RetValExp->isTypeDependent()) {
1288      // C99 6.8.6.4p1 (ext_ since GCC warns)
1289      unsigned D = diag::ext_return_has_expr;
1290      if (RetValExp->getType()->isVoidType())
1291        D = diag::ext_return_has_void_expr;
1292      else {
1293        IgnoredValueConversions(RetValExp);
1294        ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid);
1295      }
1296
1297      // return (some void expression); is legal in C++.
1298      if (D != diag::ext_return_has_void_expr ||
1299          !getLangOptions().CPlusPlus) {
1300        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1301        Diag(ReturnLoc, D)
1302          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1303          << RetValExp->getSourceRange();
1304      }
1305
1306      CheckImplicitConversions(RetValExp, ReturnLoc);
1307      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1308    }
1309
1310    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1311  } else if (!RetValExp && !FnRetType->isDependentType()) {
1312    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1313    // C99 6.8.6.4p1 (ext_ since GCC warns)
1314    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1315
1316    if (FunctionDecl *FD = getCurFunctionDecl())
1317      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1318    else
1319      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1320    Result = new (Context) ReturnStmt(ReturnLoc);
1321  } else {
1322    const VarDecl *NRVOCandidate = 0;
1323    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1324      // we have a non-void function with an expression, continue checking
1325
1326      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1327      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1328      // function return.
1329
1330      // In C++ the return statement is handled via a copy initialization.
1331      // the C version of which boils down to CheckSingleAssignmentConstraints.
1332      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1333      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1334                                                                     FnRetType,
1335                                                                     NRVOCandidate != 0);
1336      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1337                                                       FnRetType, RetValExp);
1338      if (Res.isInvalid()) {
1339        // FIXME: Cleanup temporaries here, anyway?
1340        return StmtError();
1341      }
1342
1343      RetValExp = Res.takeAs<Expr>();
1344      if (RetValExp)
1345        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1346    }
1347
1348    if (RetValExp) {
1349      CheckImplicitConversions(RetValExp, ReturnLoc);
1350      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1351    }
1352    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1353  }
1354
1355  // If we need to check for the named return value optimization, save the
1356  // return statement in our scope for later processing.
1357  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1358      !CurContext->isDependentContext())
1359    FunctionScopes.back()->Returns.push_back(Result);
1360
1361  return Owned(Result);
1362}
1363
1364/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1365/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1366/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1367/// provide a strong guidance to not use it.
1368///
1369/// This method checks to see if the argument is an acceptable l-value and
1370/// returns false if it is a case we can handle.
1371static bool CheckAsmLValue(const Expr *E, Sema &S) {
1372  // Type dependent expressions will be checked during instantiation.
1373  if (E->isTypeDependent())
1374    return false;
1375
1376  if (E->isLValue())
1377    return false;  // Cool, this is an lvalue.
1378
1379  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1380  // are supposed to allow.
1381  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1382  if (E != E2 && E2->isLValue()) {
1383    if (!S.getLangOptions().HeinousExtensions)
1384      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1385        << E->getSourceRange();
1386    else
1387      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1388        << E->getSourceRange();
1389    // Accept, even if we emitted an error diagnostic.
1390    return false;
1391  }
1392
1393  // None of the above, just randomly invalid non-lvalue.
1394  return true;
1395}
1396
1397/// isOperandMentioned - Return true if the specified operand # is mentioned
1398/// anywhere in the decomposed asm string.
1399static bool isOperandMentioned(unsigned OpNo,
1400                         llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
1401  for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1402    const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1403    if (!Piece.isOperand()) continue;
1404
1405    // If this is a reference to the input and if the input was the smaller
1406    // one, then we have to reject this asm.
1407    if (Piece.getOperandNo() == OpNo)
1408      return true;
1409  }
1410
1411  return false;
1412}
1413
1414StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1415                              bool IsVolatile, unsigned NumOutputs,
1416                              unsigned NumInputs, IdentifierInfo **Names,
1417                              MultiExprArg constraints, MultiExprArg exprs,
1418                              Expr *asmString, MultiExprArg clobbers,
1419                              SourceLocation RParenLoc, bool MSAsm) {
1420  unsigned NumClobbers = clobbers.size();
1421  StringLiteral **Constraints =
1422    reinterpret_cast<StringLiteral**>(constraints.get());
1423  Expr **Exprs = exprs.get();
1424  StringLiteral *AsmString = cast<StringLiteral>(asmString);
1425  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1426
1427  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1428
1429  // The parser verifies that there is a string literal here.
1430  if (AsmString->isWide())
1431    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1432      << AsmString->getSourceRange());
1433
1434  for (unsigned i = 0; i != NumOutputs; i++) {
1435    StringLiteral *Literal = Constraints[i];
1436    if (Literal->isWide())
1437      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1438        << Literal->getSourceRange());
1439
1440    llvm::StringRef OutputName;
1441    if (Names[i])
1442      OutputName = Names[i]->getName();
1443
1444    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1445    if (!Context.Target.validateOutputConstraint(Info))
1446      return StmtError(Diag(Literal->getLocStart(),
1447                            diag::err_asm_invalid_output_constraint)
1448                       << Info.getConstraintStr());
1449
1450    // Check that the output exprs are valid lvalues.
1451    Expr *OutputExpr = Exprs[i];
1452    if (CheckAsmLValue(OutputExpr, *this)) {
1453      return StmtError(Diag(OutputExpr->getLocStart(),
1454                  diag::err_asm_invalid_lvalue_in_output)
1455        << OutputExpr->getSourceRange());
1456    }
1457
1458    OutputConstraintInfos.push_back(Info);
1459  }
1460
1461  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1462
1463  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1464    StringLiteral *Literal = Constraints[i];
1465    if (Literal->isWide())
1466      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1467        << Literal->getSourceRange());
1468
1469    llvm::StringRef InputName;
1470    if (Names[i])
1471      InputName = Names[i]->getName();
1472
1473    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1474    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1475                                                NumOutputs, Info)) {
1476      return StmtError(Diag(Literal->getLocStart(),
1477                            diag::err_asm_invalid_input_constraint)
1478                       << Info.getConstraintStr());
1479    }
1480
1481    Expr *InputExpr = Exprs[i];
1482
1483    // Only allow void types for memory constraints.
1484    if (Info.allowsMemory() && !Info.allowsRegister()) {
1485      if (CheckAsmLValue(InputExpr, *this))
1486        return StmtError(Diag(InputExpr->getLocStart(),
1487                              diag::err_asm_invalid_lvalue_in_input)
1488                         << Info.getConstraintStr()
1489                         << InputExpr->getSourceRange());
1490    }
1491
1492    if (Info.allowsRegister()) {
1493      if (InputExpr->getType()->isVoidType()) {
1494        return StmtError(Diag(InputExpr->getLocStart(),
1495                              diag::err_asm_invalid_type_in_input)
1496          << InputExpr->getType() << Info.getConstraintStr()
1497          << InputExpr->getSourceRange());
1498      }
1499    }
1500
1501    DefaultFunctionArrayLvalueConversion(Exprs[i]);
1502
1503    InputConstraintInfos.push_back(Info);
1504  }
1505
1506  // Check that the clobbers are valid.
1507  for (unsigned i = 0; i != NumClobbers; i++) {
1508    StringLiteral *Literal = Clobbers[i];
1509    if (Literal->isWide())
1510      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1511        << Literal->getSourceRange());
1512
1513    llvm::StringRef Clobber = Literal->getString();
1514
1515    if (!Context.Target.isValidGCCRegisterName(Clobber))
1516      return StmtError(Diag(Literal->getLocStart(),
1517                  diag::err_asm_unknown_register_name) << Clobber);
1518  }
1519
1520  AsmStmt *NS =
1521    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1522                          NumOutputs, NumInputs, Names, Constraints, Exprs,
1523                          AsmString, NumClobbers, Clobbers, RParenLoc);
1524  // Validate the asm string, ensuring it makes sense given the operands we
1525  // have.
1526  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1527  unsigned DiagOffs;
1528  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1529    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1530           << AsmString->getSourceRange();
1531    return StmtError();
1532  }
1533
1534  // Validate tied input operands for type mismatches.
1535  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1536    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1537
1538    // If this is a tied constraint, verify that the output and input have
1539    // either exactly the same type, or that they are int/ptr operands with the
1540    // same size (int/long, int*/long, are ok etc).
1541    if (!Info.hasTiedOperand()) continue;
1542
1543    unsigned TiedTo = Info.getTiedOperand();
1544    unsigned InputOpNo = i+NumOutputs;
1545    Expr *OutputExpr = Exprs[TiedTo];
1546    Expr *InputExpr = Exprs[InputOpNo];
1547    QualType InTy = InputExpr->getType();
1548    QualType OutTy = OutputExpr->getType();
1549    if (Context.hasSameType(InTy, OutTy))
1550      continue;  // All types can be tied to themselves.
1551
1552    // Decide if the input and output are in the same domain (integer/ptr or
1553    // floating point.
1554    enum AsmDomain {
1555      AD_Int, AD_FP, AD_Other
1556    } InputDomain, OutputDomain;
1557
1558    if (InTy->isIntegerType() || InTy->isPointerType())
1559      InputDomain = AD_Int;
1560    else if (InTy->isRealFloatingType())
1561      InputDomain = AD_FP;
1562    else
1563      InputDomain = AD_Other;
1564
1565    if (OutTy->isIntegerType() || OutTy->isPointerType())
1566      OutputDomain = AD_Int;
1567    else if (OutTy->isRealFloatingType())
1568      OutputDomain = AD_FP;
1569    else
1570      OutputDomain = AD_Other;
1571
1572    // They are ok if they are the same size and in the same domain.  This
1573    // allows tying things like:
1574    //   void* to int*
1575    //   void* to int            if they are the same size.
1576    //   double to long double   if they are the same size.
1577    //
1578    uint64_t OutSize = Context.getTypeSize(OutTy);
1579    uint64_t InSize = Context.getTypeSize(InTy);
1580    if (OutSize == InSize && InputDomain == OutputDomain &&
1581        InputDomain != AD_Other)
1582      continue;
1583
1584    // If the smaller input/output operand is not mentioned in the asm string,
1585    // then we can promote the smaller one to a larger input and the asm string
1586    // won't notice.
1587    bool SmallerValueMentioned = false;
1588
1589    // If this is a reference to the input and if the input was the smaller
1590    // one, then we have to reject this asm.
1591    if (isOperandMentioned(InputOpNo, Pieces)) {
1592      // This is a use in the asm string of the smaller operand.  Since we
1593      // codegen this by promoting to a wider value, the asm will get printed
1594      // "wrong".
1595      SmallerValueMentioned |= InSize < OutSize;
1596    }
1597    if (isOperandMentioned(TiedTo, Pieces)) {
1598      // If this is a reference to the output, and if the output is the larger
1599      // value, then it's ok because we'll promote the input to the larger type.
1600      SmallerValueMentioned |= OutSize < InSize;
1601    }
1602
1603    // If the smaller value wasn't mentioned in the asm string, and if the
1604    // output was a register, just extend the shorter one to the size of the
1605    // larger one.
1606    if (!SmallerValueMentioned && InputDomain != AD_Other &&
1607        OutputConstraintInfos[TiedTo].allowsRegister())
1608      continue;
1609
1610    // Either both of the operands were mentioned or the smaller one was
1611    // mentioned.  One more special case that we'll allow: if the tied input is
1612    // integer, unmentioned, and is a constant, then we'll allow truncating it
1613    // down to the size of the destination.
1614    if (InputDomain == AD_Int && OutputDomain == AD_Int &&
1615        !isOperandMentioned(InputOpNo, Pieces) &&
1616        InputExpr->isEvaluatable(Context)) {
1617      ImpCastExprToType(InputExpr, OutTy, CK_IntegralCast);
1618      Exprs[InputOpNo] = InputExpr;
1619      NS->setInputExpr(i, InputExpr);
1620      continue;
1621    }
1622
1623    Diag(InputExpr->getLocStart(),
1624         diag::err_asm_tying_incompatible_types)
1625      << InTy << OutTy << OutputExpr->getSourceRange()
1626      << InputExpr->getSourceRange();
1627    return StmtError();
1628  }
1629
1630  return Owned(NS);
1631}
1632
1633StmtResult
1634Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1635                           SourceLocation RParen, Decl *Parm,
1636                           Stmt *Body) {
1637  VarDecl *Var = cast_or_null<VarDecl>(Parm);
1638  if (Var && Var->isInvalidDecl())
1639    return StmtError();
1640
1641  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
1642}
1643
1644StmtResult
1645Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1646  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
1647}
1648
1649StmtResult
1650Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1651                         MultiStmtArg CatchStmts, Stmt *Finally) {
1652  if (!getLangOptions().ObjCExceptions)
1653    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
1654
1655  getCurFunction()->setHasBranchProtectedScope();
1656  unsigned NumCatchStmts = CatchStmts.size();
1657  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1658                                     CatchStmts.release(),
1659                                     NumCatchStmts,
1660                                     Finally));
1661}
1662
1663StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1664                                                  Expr *Throw) {
1665  if (Throw) {
1666    DefaultLvalueConversion(Throw);
1667
1668    QualType ThrowType = Throw->getType();
1669    // Make sure the expression type is an ObjC pointer or "void *".
1670    if (!ThrowType->isDependentType() &&
1671        !ThrowType->isObjCObjectPointerType()) {
1672      const PointerType *PT = ThrowType->getAs<PointerType>();
1673      if (!PT || !PT->getPointeeType()->isVoidType())
1674        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1675                         << Throw->getType() << Throw->getSourceRange());
1676    }
1677  }
1678
1679  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
1680}
1681
1682StmtResult
1683Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
1684                           Scope *CurScope) {
1685  if (!getLangOptions().ObjCExceptions)
1686    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
1687
1688  if (!Throw) {
1689    // @throw without an expression designates a rethrow (which much occur
1690    // in the context of an @catch clause).
1691    Scope *AtCatchParent = CurScope;
1692    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1693      AtCatchParent = AtCatchParent->getParent();
1694    if (!AtCatchParent)
1695      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1696  }
1697
1698  return BuildObjCAtThrowStmt(AtLoc, Throw);
1699}
1700
1701StmtResult
1702Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1703                                  Stmt *SyncBody) {
1704  getCurFunction()->setHasBranchProtectedScope();
1705
1706  DefaultLvalueConversion(SyncExpr);
1707
1708  // Make sure the expression type is an ObjC pointer or "void *".
1709  if (!SyncExpr->getType()->isDependentType() &&
1710      !SyncExpr->getType()->isObjCObjectPointerType()) {
1711    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1712    if (!PT || !PT->getPointeeType()->isVoidType())
1713      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1714                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1715  }
1716
1717  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
1718}
1719
1720/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1721/// and creates a proper catch handler from them.
1722StmtResult
1723Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
1724                         Stmt *HandlerBlock) {
1725  // There's nothing to test that ActOnExceptionDecl didn't already test.
1726  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1727                                          cast_or_null<VarDecl>(ExDecl),
1728                                          HandlerBlock));
1729}
1730
1731namespace {
1732
1733class TypeWithHandler {
1734  QualType t;
1735  CXXCatchStmt *stmt;
1736public:
1737  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1738  : t(type), stmt(statement) {}
1739
1740  // An arbitrary order is fine as long as it places identical
1741  // types next to each other.
1742  bool operator<(const TypeWithHandler &y) const {
1743    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1744      return true;
1745    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1746      return false;
1747    else
1748      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1749  }
1750
1751  bool operator==(const TypeWithHandler& other) const {
1752    return t == other.t;
1753  }
1754
1755  CXXCatchStmt *getCatchStmt() const { return stmt; }
1756  SourceLocation getTypeSpecStartLoc() const {
1757    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1758  }
1759};
1760
1761}
1762
1763/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1764/// handlers and creates a try statement from them.
1765StmtResult
1766Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
1767                       MultiStmtArg RawHandlers) {
1768  // Don't report an error if 'try' is used in system headers.
1769  if (!getLangOptions().CXXExceptions &&
1770      !getSourceManager().isInSystemHeader(TryLoc))
1771      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
1772
1773  unsigned NumHandlers = RawHandlers.size();
1774  assert(NumHandlers > 0 &&
1775         "The parser shouldn't call this if there are no handlers.");
1776  Stmt **Handlers = RawHandlers.get();
1777
1778  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1779
1780  for (unsigned i = 0; i < NumHandlers; ++i) {
1781    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1782    if (!Handler->getExceptionDecl()) {
1783      if (i < NumHandlers - 1)
1784        return StmtError(Diag(Handler->getLocStart(),
1785                              diag::err_early_catch_all));
1786
1787      continue;
1788    }
1789
1790    const QualType CaughtType = Handler->getCaughtType();
1791    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1792    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1793  }
1794
1795  // Detect handlers for the same type as an earlier one.
1796  if (NumHandlers > 1) {
1797    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1798
1799    TypeWithHandler prev = TypesWithHandlers[0];
1800    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1801      TypeWithHandler curr = TypesWithHandlers[i];
1802
1803      if (curr == prev) {
1804        Diag(curr.getTypeSpecStartLoc(),
1805             diag::warn_exception_caught_by_earlier_handler)
1806          << curr.getCatchStmt()->getCaughtType().getAsString();
1807        Diag(prev.getTypeSpecStartLoc(),
1808             diag::note_previous_exception_handler)
1809          << prev.getCatchStmt()->getCaughtType().getAsString();
1810      }
1811
1812      prev = curr;
1813    }
1814  }
1815
1816  getCurFunction()->setHasBranchProtectedScope();
1817
1818  // FIXME: We should detect handlers that cannot catch anything because an
1819  // earlier handler catches a superclass. Need to find a method that is not
1820  // quadratic for this.
1821  // Neither of these are explicitly forbidden, but every compiler detects them
1822  // and warns.
1823
1824  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
1825                                  Handlers, NumHandlers));
1826}
1827