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