SemaStmt.cpp revision 856d3798af7c2f7251e4a295f3da7a09ce4c62ab
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/Sema/Lookup.h"
19#include "clang/AST/APValue.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Lex/Preprocessor.h"
28#include "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallVector.h"
32using namespace clang;
33using namespace sema;
34
35StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
36  Expr *E = expr.get();
37  if (!E) // FIXME: FullExprArg has no error state?
38    return StmtError();
39
40  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41  // void expression for its side effects.  Conversion to void allows any
42  // operand, even incomplete types.
43
44  // Same thing in for stmt first clause (when expr) and third clause.
45  return Owned(static_cast<Stmt*>(E));
46}
47
48
49StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
50                               SourceLocation LeadingEmptyMacroLoc) {
51  return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacroLoc));
52}
53
54StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
55                               SourceLocation EndLoc) {
56  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
57
58  // If we have an invalid decl, just return an error.
59  if (DG.isNull()) return StmtError();
60
61  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
62}
63
64void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
66
67  // If we have an invalid decl, just return.
68  if (DG.isNull() || !DG.isSingleDecl()) return;
69  VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
70
71  // suppress any potential 'unused variable' warning.
72  var->setUsed();
73
74  // In ARC, we don't want to lifetime for the iteration
75  // variable of a fast enumeration loop.  Rather than actually
76  // trying to catch that during declaration processing, we
77  // remove the consequences here.
78  if (getLangOptions().ObjCAutoRefCount) {
79    SplitQualType split = var->getType().split();
80
81    // Inferred lifetime will show up as a local qualifier because
82    // explicit lifetime would have shown up as an AttributedType
83    // instead.
84    if (split.second.hasObjCLifetime()) {
85      // Change the qualification to 'const __unsafe_unretained'.
86      split.second.setObjCLifetime(Qualifiers::OCL_ExplicitNone);
87      split.second.addConst();
88      var->setType(Context.getQualifiedType(split.first, split.second));
89      var->setInit(0);
90    }
91  }
92}
93
94void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
95  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
96    return DiagnoseUnusedExprResult(Label->getSubStmt());
97
98  const Expr *E = dyn_cast_or_null<Expr>(S);
99  if (!E)
100    return;
101
102  SourceLocation Loc;
103  SourceRange R1, R2;
104  if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
105    return;
106
107  // Okay, we have an unused result.  Depending on what the base expression is,
108  // we might want to make a more specific diagnostic.  Check for one of these
109  // cases now.
110  unsigned DiagID = diag::warn_unused_expr;
111  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
112    E = Temps->getSubExpr();
113  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
114    E = TempExpr->getSubExpr();
115
116  E = E->IgnoreParenImpCasts();
117  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
118    if (E->getType()->isVoidType())
119      return;
120
121    // If the callee has attribute pure, const, or warn_unused_result, warn with
122    // a more specific message to make it clear what is happening.
123    if (const Decl *FD = CE->getCalleeDecl()) {
124      if (FD->getAttr<WarnUnusedResultAttr>()) {
125        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
126        return;
127      }
128      if (FD->getAttr<PureAttr>()) {
129        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
130        return;
131      }
132      if (FD->getAttr<ConstAttr>()) {
133        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
134        return;
135      }
136    }
137  } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
138    if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) {
139      Diag(Loc, diag::err_arc_unused_init_message) << R1;
140      return;
141    }
142    const ObjCMethodDecl *MD = ME->getMethodDecl();
143    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
144      Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
145      return;
146    }
147  } else if (isa<ObjCPropertyRefExpr>(E)) {
148    DiagID = diag::warn_unused_property_expr;
149  } else if (const CXXFunctionalCastExpr *FC
150                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
151    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
152        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
153      return;
154  }
155  // Diagnose "(void*) blah" as a typo for "(void) blah".
156  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
157    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
158    QualType T = TI->getType();
159
160    // We really do want to use the non-canonical type here.
161    if (T == Context.VoidPtrTy) {
162      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
163
164      Diag(Loc, diag::warn_unused_voidptr)
165        << FixItHint::CreateRemoval(TL.getStarLoc());
166      return;
167    }
168  }
169
170  DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
171}
172
173StmtResult
174Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
175                        MultiStmtArg elts, bool isStmtExpr) {
176  unsigned NumElts = elts.size();
177  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
178  // If we're in C89 mode, check that we don't have any decls after stmts.  If
179  // so, emit an extension diagnostic.
180  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
181    // Note that __extension__ can be around a decl.
182    unsigned i = 0;
183    // Skip over all declarations.
184    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
185      /*empty*/;
186
187    // We found the end of the list or a statement.  Scan for another declstmt.
188    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
189      /*empty*/;
190
191    if (i != NumElts) {
192      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
193      Diag(D->getLocation(), diag::ext_mixed_decls_code);
194    }
195  }
196  // Warn about unused expressions in statements.
197  for (unsigned i = 0; i != NumElts; ++i) {
198    // Ignore statements that are last in a statement expression.
199    if (isStmtExpr && i == NumElts - 1)
200      continue;
201
202    DiagnoseUnusedExprResult(Elts[i]);
203  }
204
205  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
206}
207
208StmtResult
209Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
210                    SourceLocation DotDotDotLoc, Expr *RHSVal,
211                    SourceLocation ColonLoc) {
212  assert((LHSVal != 0) && "missing expression in case statement");
213
214  // C99 6.8.4.2p3: The expression shall be an integer constant.
215  // However, GCC allows any evaluatable integer expression.
216  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
217      VerifyIntegerConstantExpression(LHSVal))
218    return StmtError();
219
220  // GCC extension: The expression shall be an integer constant.
221
222  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
223      VerifyIntegerConstantExpression(RHSVal)) {
224    RHSVal = 0;  // Recover by just forgetting about it.
225  }
226
227  if (getCurFunction()->SwitchStack.empty()) {
228    Diag(CaseLoc, diag::err_case_not_in_switch);
229    return StmtError();
230  }
231
232  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
233                                        ColonLoc);
234  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
235  return Owned(CS);
236}
237
238/// ActOnCaseStmtBody - This installs a statement as the body of a case.
239void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
240  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
241  CS->setSubStmt(SubStmt);
242}
243
244StmtResult
245Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
246                       Stmt *SubStmt, Scope *CurScope) {
247  if (getCurFunction()->SwitchStack.empty()) {
248    Diag(DefaultLoc, diag::err_default_not_in_switch);
249    return Owned(SubStmt);
250  }
251
252  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
253  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
254  return Owned(DS);
255}
256
257StmtResult
258Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
259                     SourceLocation ColonLoc, Stmt *SubStmt) {
260
261  // If the label was multiply defined, reject it now.
262  if (TheDecl->getStmt()) {
263    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
264    Diag(TheDecl->getLocation(), diag::note_previous_definition);
265    return Owned(SubStmt);
266  }
267
268  // Otherwise, things are good.  Fill in the declaration and return it.
269  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
270  TheDecl->setStmt(LS);
271  if (!TheDecl->isGnuLocal())
272    TheDecl->setLocation(IdentLoc);
273  return Owned(LS);
274}
275
276StmtResult
277Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
278                  Stmt *thenStmt, SourceLocation ElseLoc,
279                  Stmt *elseStmt) {
280  ExprResult CondResult(CondVal.release());
281
282  VarDecl *ConditionVar = 0;
283  if (CondVar) {
284    ConditionVar = cast<VarDecl>(CondVar);
285    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
286    if (CondResult.isInvalid())
287      return StmtError();
288  }
289  Expr *ConditionExpr = CondResult.takeAs<Expr>();
290  if (!ConditionExpr)
291    return StmtError();
292
293  DiagnoseUnusedExprResult(thenStmt);
294
295  // Warn if the if block has a null body without an else value.
296  // this helps prevent bugs due to typos, such as
297  // if (condition);
298  //   do_stuff();
299  //
300  if (!elseStmt) {
301    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
302      // But do not warn if the body is a macro that expands to nothing, e.g:
303      //
304      // #define CALL(x)
305      // if (condition)
306      //   CALL(0);
307      //
308      if (!stmt->hasLeadingEmptyMacro())
309        Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
310  }
311
312  DiagnoseUnusedExprResult(elseStmt);
313
314  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
315                                    thenStmt, ElseLoc, elseStmt));
316}
317
318/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
319/// the specified width and sign.  If an overflow occurs, detect it and emit
320/// the specified diagnostic.
321void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
322                                              unsigned NewWidth, bool NewSign,
323                                              SourceLocation Loc,
324                                              unsigned DiagID) {
325  // Perform a conversion to the promoted condition type if needed.
326  if (NewWidth > Val.getBitWidth()) {
327    // If this is an extension, just do it.
328    Val = Val.extend(NewWidth);
329    Val.setIsSigned(NewSign);
330
331    // If the input was signed and negative and the output is
332    // unsigned, don't bother to warn: this is implementation-defined
333    // behavior.
334    // FIXME: Introduce a second, default-ignored warning for this case?
335  } else if (NewWidth < Val.getBitWidth()) {
336    // If this is a truncation, check for overflow.
337    llvm::APSInt ConvVal(Val);
338    ConvVal = ConvVal.trunc(NewWidth);
339    ConvVal.setIsSigned(NewSign);
340    ConvVal = ConvVal.extend(Val.getBitWidth());
341    ConvVal.setIsSigned(Val.isSigned());
342    if (ConvVal != Val)
343      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
344
345    // Regardless of whether a diagnostic was emitted, really do the
346    // truncation.
347    Val = Val.trunc(NewWidth);
348    Val.setIsSigned(NewSign);
349  } else if (NewSign != Val.isSigned()) {
350    // Convert the sign to match the sign of the condition.  This can cause
351    // overflow as well: unsigned(INTMIN)
352    // We don't diagnose this overflow, because it is implementation-defined
353    // behavior.
354    // FIXME: Introduce a second, default-ignored warning for this case?
355    llvm::APSInt OldVal(Val);
356    Val.setIsSigned(NewSign);
357  }
358}
359
360namespace {
361  struct CaseCompareFunctor {
362    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
363                    const llvm::APSInt &RHS) {
364      return LHS.first < RHS;
365    }
366    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
367                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
368      return LHS.first < RHS.first;
369    }
370    bool operator()(const llvm::APSInt &LHS,
371                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
372      return LHS < RHS.first;
373    }
374  };
375}
376
377/// CmpCaseVals - Comparison predicate for sorting case values.
378///
379static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
380                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
381  if (lhs.first < rhs.first)
382    return true;
383
384  if (lhs.first == rhs.first &&
385      lhs.second->getCaseLoc().getRawEncoding()
386       < rhs.second->getCaseLoc().getRawEncoding())
387    return true;
388  return false;
389}
390
391/// CmpEnumVals - Comparison predicate for sorting enumeration values.
392///
393static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
394                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
395{
396  return lhs.first < rhs.first;
397}
398
399/// EqEnumVals - Comparison preficate for uniqing enumeration values.
400///
401static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
402                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
403{
404  return lhs.first == rhs.first;
405}
406
407/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
408/// potentially integral-promoted expression @p expr.
409static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
410  if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
411    const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
412    QualType TypeBeforePromotion = ExprBeforePromotion->getType();
413    if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
414      return TypeBeforePromotion;
415    }
416  }
417  return expr->getType();
418}
419
420StmtResult
421Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
422                             Decl *CondVar) {
423  ExprResult CondResult;
424
425  VarDecl *ConditionVar = 0;
426  if (CondVar) {
427    ConditionVar = cast<VarDecl>(CondVar);
428    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
429    if (CondResult.isInvalid())
430      return StmtError();
431
432    Cond = CondResult.release();
433  }
434
435  if (!Cond)
436    return StmtError();
437
438  CondResult
439    = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
440                          PDiag(diag::err_typecheck_statement_requires_integer),
441                                   PDiag(diag::err_switch_incomplete_class_type)
442                                     << Cond->getSourceRange(),
443                                   PDiag(diag::err_switch_explicit_conversion),
444                                         PDiag(diag::note_switch_conversion),
445                                   PDiag(diag::err_switch_multiple_conversions),
446                                         PDiag(diag::note_switch_conversion),
447                                         PDiag(0));
448  if (CondResult.isInvalid()) return StmtError();
449  Cond = CondResult.take();
450
451  if (!CondVar) {
452    CheckImplicitConversions(Cond, SwitchLoc);
453    CondResult = MaybeCreateExprWithCleanups(Cond);
454    if (CondResult.isInvalid())
455      return StmtError();
456    Cond = CondResult.take();
457  }
458
459  getCurFunction()->setHasBranchIntoScope();
460
461  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
462  getCurFunction()->SwitchStack.push_back(SS);
463  return Owned(SS);
464}
465
466static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
467  if (Val.getBitWidth() < BitWidth)
468    Val = Val.extend(BitWidth);
469  else if (Val.getBitWidth() > BitWidth)
470    Val = Val.trunc(BitWidth);
471  Val.setIsSigned(IsSigned);
472}
473
474StmtResult
475Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
476                            Stmt *BodyStmt) {
477  SwitchStmt *SS = cast<SwitchStmt>(Switch);
478  assert(SS == getCurFunction()->SwitchStack.back() &&
479         "switch stack missing push/pop!");
480
481  SS->setBody(BodyStmt, SwitchLoc);
482  getCurFunction()->SwitchStack.pop_back();
483
484  if (SS->getCond() == 0)
485    return StmtError();
486
487  Expr *CondExpr = SS->getCond();
488  Expr *CondExprBeforePromotion = CondExpr;
489  QualType CondTypeBeforePromotion =
490      GetTypeBeforeIntegralPromotion(CondExpr);
491
492  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
493  ExprResult CondResult = UsualUnaryConversions(CondExpr);
494  if (CondResult.isInvalid())
495    return StmtError();
496  CondExpr = CondResult.take();
497  QualType CondType = CondExpr->getType();
498  SS->setCond(CondExpr);
499
500  // C++ 6.4.2.p2:
501  // Integral promotions are performed (on the switch condition).
502  //
503  // A case value unrepresentable by the original switch condition
504  // type (before the promotion) doesn't make sense, even when it can
505  // be represented by the promoted type.  Therefore we need to find
506  // the pre-promotion type of the switch condition.
507  if (!CondExpr->isTypeDependent()) {
508    // We have already converted the expression to an integral or enumeration
509    // type, when we started the switch statement. If we don't have an
510    // appropriate type now, just return an error.
511    if (!CondType->isIntegralOrEnumerationType())
512      return StmtError();
513
514    if (CondExpr->isKnownToHaveBooleanValue()) {
515      // switch(bool_expr) {...} is often a programmer error, e.g.
516      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
517      // One can always use an if statement instead of switch(bool_expr).
518      Diag(SwitchLoc, diag::warn_bool_switch_condition)
519          << CondExpr->getSourceRange();
520    }
521  }
522
523  // Get the bitwidth of the switched-on value before promotions.  We must
524  // convert the integer case values to this width before comparison.
525  bool HasDependentValue
526    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
527  unsigned CondWidth
528    = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
529  bool CondIsSigned
530    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
531
532  // Accumulate all of the case values in a vector so that we can sort them
533  // and detect duplicates.  This vector contains the APInt for the case after
534  // it has been converted to the condition type.
535  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
536  CaseValsTy CaseVals;
537
538  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
539  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
540  CaseRangesTy CaseRanges;
541
542  DefaultStmt *TheDefaultStmt = 0;
543
544  bool CaseListIsErroneous = false;
545
546  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
547       SC = SC->getNextSwitchCase()) {
548
549    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
550      if (TheDefaultStmt) {
551        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
552        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
553
554        // FIXME: Remove the default statement from the switch block so that
555        // we'll return a valid AST.  This requires recursing down the AST and
556        // finding it, not something we are set up to do right now.  For now,
557        // just lop the entire switch stmt out of the AST.
558        CaseListIsErroneous = true;
559      }
560      TheDefaultStmt = DS;
561
562    } else {
563      CaseStmt *CS = cast<CaseStmt>(SC);
564
565      // We already verified that the expression has a i-c-e value (C99
566      // 6.8.4.2p3) - get that value now.
567      Expr *Lo = CS->getLHS();
568
569      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
570        HasDependentValue = true;
571        break;
572      }
573
574      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
575
576      // Convert the value to the same width/sign as the condition.
577      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
578                                         Lo->getLocStart(),
579                                         diag::warn_case_value_overflow);
580
581      // If the LHS is not the same type as the condition, insert an implicit
582      // cast.
583      Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
584      CS->setLHS(Lo);
585
586      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
587      if (CS->getRHS()) {
588        if (CS->getRHS()->isTypeDependent() ||
589            CS->getRHS()->isValueDependent()) {
590          HasDependentValue = true;
591          break;
592        }
593        CaseRanges.push_back(std::make_pair(LoVal, CS));
594      } else
595        CaseVals.push_back(std::make_pair(LoVal, CS));
596    }
597  }
598
599  if (!HasDependentValue) {
600    // If we don't have a default statement, check whether the
601    // condition is constant.
602    llvm::APSInt ConstantCondValue;
603    bool HasConstantCond = false;
604    bool ShouldCheckConstantCond = false;
605    if (!HasDependentValue && !TheDefaultStmt) {
606      Expr::EvalResult Result;
607      HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
608      if (HasConstantCond) {
609        assert(Result.Val.isInt() && "switch condition evaluated to non-int");
610        ConstantCondValue = Result.Val.getInt();
611        ShouldCheckConstantCond = true;
612
613        assert(ConstantCondValue.getBitWidth() == CondWidth &&
614               ConstantCondValue.isSigned() == CondIsSigned);
615      }
616    }
617
618    // Sort all the scalar case values so we can easily detect duplicates.
619    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
620
621    if (!CaseVals.empty()) {
622      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
623        if (ShouldCheckConstantCond &&
624            CaseVals[i].first == ConstantCondValue)
625          ShouldCheckConstantCond = false;
626
627        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
628          // If we have a duplicate, report it.
629          Diag(CaseVals[i].second->getLHS()->getLocStart(),
630               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
631          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
632               diag::note_duplicate_case_prev);
633          // FIXME: We really want to remove the bogus case stmt from the
634          // substmt, but we have no way to do this right now.
635          CaseListIsErroneous = true;
636        }
637      }
638    }
639
640    // Detect duplicate case ranges, which usually don't exist at all in
641    // the first place.
642    if (!CaseRanges.empty()) {
643      // Sort all the case ranges by their low value so we can easily detect
644      // overlaps between ranges.
645      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
646
647      // Scan the ranges, computing the high values and removing empty ranges.
648      std::vector<llvm::APSInt> HiVals;
649      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
650        llvm::APSInt &LoVal = CaseRanges[i].first;
651        CaseStmt *CR = CaseRanges[i].second;
652        Expr *Hi = CR->getRHS();
653        llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
654
655        // Convert the value to the same width/sign as the condition.
656        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
657                                           Hi->getLocStart(),
658                                           diag::warn_case_value_overflow);
659
660        // If the LHS is not the same type as the condition, insert an implicit
661        // cast.
662        Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
663        CR->setRHS(Hi);
664
665        // If the low value is bigger than the high value, the case is empty.
666        if (LoVal > HiVal) {
667          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
668            << SourceRange(CR->getLHS()->getLocStart(),
669                           Hi->getLocEnd());
670          CaseRanges.erase(CaseRanges.begin()+i);
671          --i, --e;
672          continue;
673        }
674
675        if (ShouldCheckConstantCond &&
676            LoVal <= ConstantCondValue &&
677            ConstantCondValue <= HiVal)
678          ShouldCheckConstantCond = false;
679
680        HiVals.push_back(HiVal);
681      }
682
683      // Rescan the ranges, looking for overlap with singleton values and other
684      // ranges.  Since the range list is sorted, we only need to compare case
685      // ranges with their neighbors.
686      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
687        llvm::APSInt &CRLo = CaseRanges[i].first;
688        llvm::APSInt &CRHi = HiVals[i];
689        CaseStmt *CR = CaseRanges[i].second;
690
691        // Check to see whether the case range overlaps with any
692        // singleton cases.
693        CaseStmt *OverlapStmt = 0;
694        llvm::APSInt OverlapVal(32);
695
696        // Find the smallest value >= the lower bound.  If I is in the
697        // case range, then we have overlap.
698        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
699                                                  CaseVals.end(), CRLo,
700                                                  CaseCompareFunctor());
701        if (I != CaseVals.end() && I->first < CRHi) {
702          OverlapVal  = I->first;   // Found overlap with scalar.
703          OverlapStmt = I->second;
704        }
705
706        // Find the smallest value bigger than the upper bound.
707        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
708        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
709          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
710          OverlapStmt = (I-1)->second;
711        }
712
713        // Check to see if this case stmt overlaps with the subsequent
714        // case range.
715        if (i && CRLo <= HiVals[i-1]) {
716          OverlapVal  = HiVals[i-1];       // Found overlap with range.
717          OverlapStmt = CaseRanges[i-1].second;
718        }
719
720        if (OverlapStmt) {
721          // If we have a duplicate, report it.
722          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
723            << OverlapVal.toString(10);
724          Diag(OverlapStmt->getLHS()->getLocStart(),
725               diag::note_duplicate_case_prev);
726          // FIXME: We really want to remove the bogus case stmt from the
727          // substmt, but we have no way to do this right now.
728          CaseListIsErroneous = true;
729        }
730      }
731    }
732
733    // Complain if we have a constant condition and we didn't find a match.
734    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
735      // TODO: it would be nice if we printed enums as enums, chars as
736      // chars, etc.
737      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
738        << ConstantCondValue.toString(10)
739        << CondExpr->getSourceRange();
740    }
741
742    // Check to see if switch is over an Enum and handles all of its
743    // values.  We only issue a warning if there is not 'default:', but
744    // we still do the analysis to preserve this information in the AST
745    // (which can be used by flow-based analyes).
746    //
747    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
748
749    // If switch has default case, then ignore it.
750    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
751      const EnumDecl *ED = ET->getDecl();
752      typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
753        EnumValsTy;
754      EnumValsTy EnumVals;
755
756      // Gather all enum values, set their type and sort them,
757      // allowing easier comparison with CaseVals.
758      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
759           EDI != ED->enumerator_end(); ++EDI) {
760        llvm::APSInt Val = EDI->getInitVal();
761        AdjustAPSInt(Val, CondWidth, CondIsSigned);
762        EnumVals.push_back(std::make_pair(Val, *EDI));
763      }
764      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
765      EnumValsTy::iterator EIend =
766        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
767
768      // See which case values aren't in enum.
769      // TODO: we might want to check whether case values are out of the
770      // enum even if we don't want to check whether all cases are handled.
771      if (!TheDefaultStmt) {
772        EnumValsTy::const_iterator EI = EnumVals.begin();
773        for (CaseValsTy::const_iterator CI = CaseVals.begin();
774             CI != CaseVals.end(); CI++) {
775          while (EI != EIend && EI->first < CI->first)
776            EI++;
777          if (EI == EIend || EI->first > CI->first)
778            Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
779              << ED->getDeclName();
780        }
781        // See which of case ranges aren't in enum
782        EI = EnumVals.begin();
783        for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
784             RI != CaseRanges.end() && EI != EIend; RI++) {
785          while (EI != EIend && EI->first < RI->first)
786            EI++;
787
788          if (EI == EIend || EI->first != RI->first) {
789            Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
790              << ED->getDeclName();
791          }
792
793          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
794          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
795          while (EI != EIend && EI->first < Hi)
796            EI++;
797          if (EI == EIend || EI->first != Hi)
798            Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
799              << ED->getDeclName();
800        }
801      }
802
803      // Check which enum vals aren't in switch
804      CaseValsTy::const_iterator CI = CaseVals.begin();
805      CaseRangesTy::const_iterator RI = CaseRanges.begin();
806      bool hasCasesNotInSwitch = false;
807
808      llvm::SmallVector<DeclarationName,8> UnhandledNames;
809
810      for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
811        // Drop unneeded case values
812        llvm::APSInt CIVal;
813        while (CI != CaseVals.end() && CI->first < EI->first)
814          CI++;
815
816        if (CI != CaseVals.end() && CI->first == EI->first)
817          continue;
818
819        // Drop unneeded case ranges
820        for (; RI != CaseRanges.end(); RI++) {
821          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
822          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
823          if (EI->first <= Hi)
824            break;
825        }
826
827        if (RI == CaseRanges.end() || EI->first < RI->first) {
828          hasCasesNotInSwitch = true;
829          if (!TheDefaultStmt)
830            UnhandledNames.push_back(EI->second->getDeclName());
831        }
832      }
833
834      // Produce a nice diagnostic if multiple values aren't handled.
835      switch (UnhandledNames.size()) {
836      case 0: break;
837      case 1:
838        Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
839          << UnhandledNames[0];
840        break;
841      case 2:
842        Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
843          << UnhandledNames[0] << UnhandledNames[1];
844        break;
845      case 3:
846        Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
847          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
848        break;
849      default:
850        Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
851          << (unsigned)UnhandledNames.size()
852          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
853        break;
854      }
855
856      if (!hasCasesNotInSwitch)
857        SS->setAllEnumCasesCovered();
858    }
859  }
860
861  // FIXME: If the case list was broken is some way, we don't have a good system
862  // to patch it up.  Instead, just return the whole substmt as broken.
863  if (CaseListIsErroneous)
864    return StmtError();
865
866  return Owned(SS);
867}
868
869StmtResult
870Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
871                     Decl *CondVar, Stmt *Body) {
872  ExprResult CondResult(Cond.release());
873
874  VarDecl *ConditionVar = 0;
875  if (CondVar) {
876    ConditionVar = cast<VarDecl>(CondVar);
877    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
878    if (CondResult.isInvalid())
879      return StmtError();
880  }
881  Expr *ConditionExpr = CondResult.take();
882  if (!ConditionExpr)
883    return StmtError();
884
885  DiagnoseUnusedExprResult(Body);
886
887  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
888                                       Body, WhileLoc));
889}
890
891StmtResult
892Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
893                  SourceLocation WhileLoc, SourceLocation CondLParen,
894                  Expr *Cond, SourceLocation CondRParen) {
895  assert(Cond && "ActOnDoStmt(): missing expression");
896
897  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
898  if (CondResult.isInvalid() || CondResult.isInvalid())
899    return StmtError();
900  Cond = CondResult.take();
901
902  CheckImplicitConversions(Cond, DoLoc);
903  CondResult = MaybeCreateExprWithCleanups(Cond);
904  if (CondResult.isInvalid())
905    return StmtError();
906  Cond = CondResult.take();
907
908  DiagnoseUnusedExprResult(Body);
909
910  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
911}
912
913StmtResult
914Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
915                   Stmt *First, FullExprArg second, Decl *secondVar,
916                   FullExprArg third,
917                   SourceLocation RParenLoc, Stmt *Body) {
918  if (!getLangOptions().CPlusPlus) {
919    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
920      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
921      // declare identifiers for objects having storage class 'auto' or
922      // 'register'.
923      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
924           DI!=DE; ++DI) {
925        VarDecl *VD = dyn_cast<VarDecl>(*DI);
926        if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
927          VD = 0;
928        if (VD == 0)
929          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
930        // FIXME: mark decl erroneous!
931      }
932    }
933  }
934
935  ExprResult SecondResult(second.release());
936  VarDecl *ConditionVar = 0;
937  if (secondVar) {
938    ConditionVar = cast<VarDecl>(secondVar);
939    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
940    if (SecondResult.isInvalid())
941      return StmtError();
942  }
943
944  Expr *Third  = third.release().takeAs<Expr>();
945
946  DiagnoseUnusedExprResult(First);
947  DiagnoseUnusedExprResult(Third);
948  DiagnoseUnusedExprResult(Body);
949
950  return Owned(new (Context) ForStmt(Context, First,
951                                     SecondResult.take(), ConditionVar,
952                                     Third, Body, ForLoc, LParenLoc,
953                                     RParenLoc));
954}
955
956/// In an Objective C collection iteration statement:
957///   for (x in y)
958/// x can be an arbitrary l-value expression.  Bind it up as a
959/// full-expression.
960StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
961  CheckImplicitConversions(E);
962  ExprResult Result = MaybeCreateExprWithCleanups(E);
963  if (Result.isInvalid()) return StmtError();
964  return Owned(static_cast<Stmt*>(Result.get()));
965}
966
967StmtResult
968Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
969                                 SourceLocation LParenLoc,
970                                 Stmt *First, Expr *Second,
971                                 SourceLocation RParenLoc, Stmt *Body) {
972  if (First) {
973    QualType FirstType;
974    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
975      if (!DS->isSingleDecl())
976        return StmtError(Diag((*DS->decl_begin())->getLocation(),
977                         diag::err_toomany_element_decls));
978
979      VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
980      FirstType = D->getType();
981      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
982      // declare identifiers for objects having storage class 'auto' or
983      // 'register'.
984      if (!D->hasLocalStorage())
985        return StmtError(Diag(D->getLocation(),
986                              diag::err_non_variable_decl_in_for));
987    } else {
988      Expr *FirstE = cast<Expr>(First);
989      if (!FirstE->isTypeDependent() && !FirstE->isLValue())
990        return StmtError(Diag(First->getLocStart(),
991                   diag::err_selector_element_not_lvalue)
992          << First->getSourceRange());
993
994      FirstType = static_cast<Expr*>(First)->getType();
995    }
996    if (!FirstType->isDependentType() &&
997        !FirstType->isObjCObjectPointerType() &&
998        !FirstType->isBlockPointerType())
999        Diag(ForLoc, diag::err_selector_element_type)
1000          << FirstType << First->getSourceRange();
1001  }
1002  if (Second && !Second->isTypeDependent()) {
1003    ExprResult Result = DefaultFunctionArrayLvalueConversion(Second);
1004    if (Result.isInvalid())
1005      return StmtError();
1006    Second = Result.take();
1007    QualType SecondType = Second->getType();
1008    if (!SecondType->isObjCObjectPointerType())
1009      Diag(ForLoc, diag::err_collection_expr_type)
1010        << SecondType << Second->getSourceRange();
1011    else if (const ObjCObjectPointerType *OPT =
1012             SecondType->getAsObjCInterfacePointerType()) {
1013      llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
1014      IdentifierInfo* selIdent =
1015        &Context.Idents.get("countByEnumeratingWithState");
1016      KeyIdents.push_back(selIdent);
1017      selIdent = &Context.Idents.get("objects");
1018      KeyIdents.push_back(selIdent);
1019      selIdent = &Context.Idents.get("count");
1020      KeyIdents.push_back(selIdent);
1021      Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
1022      if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
1023        if (!IDecl->isForwardDecl() &&
1024            !IDecl->lookupInstanceMethod(CSelector) &&
1025            !LookupMethodInQualifiedType(CSelector, OPT, true)) {
1026          // Must further look into private implementation methods.
1027          if (!LookupPrivateInstanceMethod(CSelector, IDecl))
1028            Diag(ForLoc, diag::warn_collection_expr_type)
1029              << SecondType << CSelector << Second->getSourceRange();
1030        }
1031      }
1032    }
1033  }
1034  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1035                                                   ForLoc, RParenLoc));
1036}
1037
1038namespace {
1039
1040enum BeginEndFunction {
1041  BEF_begin,
1042  BEF_end
1043};
1044
1045/// Build a variable declaration for a for-range statement.
1046static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1047                                     QualType Type, const char *Name) {
1048  DeclContext *DC = SemaRef.CurContext;
1049  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1050  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1051  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1052                                  TInfo, SC_Auto, SC_None);
1053  Decl->setImplicit();
1054  return Decl;
1055}
1056
1057/// Finish building a variable declaration for a for-range statement.
1058/// \return true if an error occurs.
1059static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1060                                  SourceLocation Loc, int diag) {
1061  // Deduce the type for the iterator variable now rather than leaving it to
1062  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1063  TypeSourceInfo *InitTSI = 0;
1064  if (Init->getType()->isVoidType() ||
1065      !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
1066    SemaRef.Diag(Loc, diag) << Init->getType();
1067  if (!InitTSI) {
1068    Decl->setInvalidDecl();
1069    return true;
1070  }
1071  Decl->setTypeSourceInfo(InitTSI);
1072  Decl->setType(InitTSI->getType());
1073
1074  // In ARC, infer lifetime.
1075  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1076  // we're doing the equivalent of fast iteration.
1077  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1078      SemaRef.inferObjCARCLifetime(Decl))
1079    Decl->setInvalidDecl();
1080
1081  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1082                               /*TypeMayContainAuto=*/false);
1083  SemaRef.FinalizeDeclaration(Decl);
1084  SemaRef.CurContext->addHiddenDecl(Decl);
1085  return false;
1086}
1087
1088/// Produce a note indicating which begin/end function was implicitly called
1089/// by a C++0x for-range statement. This is often not obvious from the code,
1090/// nor from the diagnostics produced when analysing the implicit expressions
1091/// required in a for-range statement.
1092void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1093                                  BeginEndFunction BEF) {
1094  CallExpr *CE = dyn_cast<CallExpr>(E);
1095  if (!CE)
1096    return;
1097  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1098  if (!D)
1099    return;
1100  SourceLocation Loc = D->getLocation();
1101
1102  std::string Description;
1103  bool IsTemplate = false;
1104  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1105    Description = SemaRef.getTemplateArgumentBindingsText(
1106      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1107    IsTemplate = true;
1108  }
1109
1110  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1111    << BEF << IsTemplate << Description << E->getType();
1112}
1113
1114/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1115/// given LookupResult is non-empty, it is assumed to describe a member which
1116/// will be invoked. Otherwise, the function will be found via argument
1117/// dependent lookup.
1118static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1119                                            SourceLocation Loc,
1120                                            VarDecl *Decl,
1121                                            BeginEndFunction BEF,
1122                                            const DeclarationNameInfo &NameInfo,
1123                                            LookupResult &MemberLookup,
1124                                            Expr *Range) {
1125  ExprResult CallExpr;
1126  if (!MemberLookup.empty()) {
1127    ExprResult MemberRef =
1128      SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1129                                       /*IsPtr=*/false, CXXScopeSpec(),
1130                                       /*Qualifier=*/0, MemberLookup,
1131                                       /*TemplateArgs=*/0);
1132    if (MemberRef.isInvalid())
1133      return ExprError();
1134    CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1135                                     Loc, 0);
1136    if (CallExpr.isInvalid())
1137      return ExprError();
1138  } else {
1139    UnresolvedSet<0> FoundNames;
1140    // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1141    // std is an associated namespace.
1142    UnresolvedLookupExpr *Fn =
1143      UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1144                                   NestedNameSpecifierLoc(), NameInfo,
1145                                   /*NeedsADL=*/true, /*Overloaded=*/false,
1146                                   FoundNames.begin(), FoundNames.end(),
1147                                   /*LookInStdNamespace=*/true);
1148    CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1149                                               0);
1150    if (CallExpr.isInvalid()) {
1151      SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1152        << Range->getType();
1153      return ExprError();
1154    }
1155  }
1156  if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1157                            diag::err_for_range_iter_deduction_failure)) {
1158    NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1159    return ExprError();
1160  }
1161  return CallExpr;
1162}
1163
1164}
1165
1166/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1167///
1168/// C++0x [stmt.ranged]:
1169///   A range-based for statement is equivalent to
1170///
1171///   {
1172///     auto && __range = range-init;
1173///     for ( auto __begin = begin-expr,
1174///           __end = end-expr;
1175///           __begin != __end;
1176///           ++__begin ) {
1177///       for-range-declaration = *__begin;
1178///       statement
1179///     }
1180///   }
1181///
1182/// The body of the loop is not available yet, since it cannot be analysed until
1183/// we have determined the type of the for-range-declaration.
1184StmtResult
1185Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1186                           Stmt *First, SourceLocation ColonLoc, Expr *Range,
1187                           SourceLocation RParenLoc) {
1188  if (!First || !Range)
1189    return StmtError();
1190
1191  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1192  assert(DS && "first part of for range not a decl stmt");
1193
1194  if (!DS->isSingleDecl()) {
1195    Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1196    return StmtError();
1197  }
1198  if (DS->getSingleDecl()->isInvalidDecl())
1199    return StmtError();
1200
1201  if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1202    return StmtError();
1203
1204  // Build  auto && __range = range-init
1205  SourceLocation RangeLoc = Range->getLocStart();
1206  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1207                                           Context.getAutoRRefDeductType(),
1208                                           "__range");
1209  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1210                            diag::err_for_range_deduction_failure))
1211    return StmtError();
1212
1213  // Claim the type doesn't contain auto: we've already done the checking.
1214  DeclGroupPtrTy RangeGroup =
1215    BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1216  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1217  if (RangeDecl.isInvalid())
1218    return StmtError();
1219
1220  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1221                              /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1222                              RParenLoc);
1223}
1224
1225/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1226StmtResult
1227Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1228                           Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1229                           Expr *Inc, Stmt *LoopVarDecl,
1230                           SourceLocation RParenLoc) {
1231  Scope *S = getCurScope();
1232
1233  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1234  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1235  QualType RangeVarType = RangeVar->getType();
1236
1237  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1238  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1239
1240  StmtResult BeginEndDecl = BeginEnd;
1241  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1242
1243  if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1244    SourceLocation RangeLoc = RangeVar->getLocation();
1245
1246    ExprResult RangeRef = BuildDeclRefExpr(RangeVar,
1247                                           RangeVarType.getNonReferenceType(),
1248                                           VK_LValue, ColonLoc);
1249    if (RangeRef.isInvalid())
1250      return StmtError();
1251
1252    QualType AutoType = Context.getAutoDeductType();
1253    Expr *Range = RangeVar->getInit();
1254    if (!Range)
1255      return StmtError();
1256    QualType RangeType = Range->getType();
1257
1258    if (RequireCompleteType(RangeLoc, RangeType,
1259                            PDiag(diag::err_for_range_incomplete_type)))
1260      return StmtError();
1261
1262    // Build auto __begin = begin-expr, __end = end-expr.
1263    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1264                                             "__begin");
1265    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1266                                           "__end");
1267
1268    // Build begin-expr and end-expr and attach to __begin and __end variables.
1269    ExprResult BeginExpr, EndExpr;
1270    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1271      // - if _RangeT is an array type, begin-expr and end-expr are __range and
1272      //   __range + __bound, respectively, where __bound is the array bound. If
1273      //   _RangeT is an array of unknown size or an array of incomplete type,
1274      //   the program is ill-formed;
1275
1276      // begin-expr is __range.
1277      BeginExpr = RangeRef;
1278      if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc,
1279                                diag::err_for_range_iter_deduction_failure)) {
1280        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1281        return StmtError();
1282      }
1283
1284      // Find the array bound.
1285      ExprResult BoundExpr;
1286      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1287        BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1288                                                 Context.getPointerDiffType(),
1289                                                 RangeLoc));
1290      else if (const VariableArrayType *VAT =
1291               dyn_cast<VariableArrayType>(UnqAT))
1292        BoundExpr = VAT->getSizeExpr();
1293      else {
1294        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1295        // UnqAT is not incomplete and Range is not type-dependent.
1296        assert(0 && "Unexpected array type in for-range");
1297        return StmtError();
1298      }
1299
1300      // end-expr is __range + __bound.
1301      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(),
1302                           BoundExpr.get());
1303      if (EndExpr.isInvalid())
1304        return StmtError();
1305      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1306                                diag::err_for_range_iter_deduction_failure)) {
1307        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1308        return StmtError();
1309      }
1310    } else {
1311      DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1312                                        ColonLoc);
1313      DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1314                                      ColonLoc);
1315
1316      LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1317      LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1318
1319      if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1320        // - if _RangeT is a class type, the unqualified-ids begin and end are
1321        //   looked up in the scope of class _RangeT as if by class member access
1322        //   lookup (3.4.5), and if either (or both) finds at least one
1323        //   declaration, begin-expr and end-expr are __range.begin() and
1324        //   __range.end(), respectively;
1325        LookupQualifiedName(BeginMemberLookup, D);
1326        LookupQualifiedName(EndMemberLookup, D);
1327
1328        if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1329          Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1330            << RangeType << BeginMemberLookup.empty();
1331          return StmtError();
1332        }
1333      } else {
1334        // - otherwise, begin-expr and end-expr are begin(__range) and
1335        //   end(__range), respectively, where begin and end are looked up with
1336        //   argument-dependent lookup (3.4.2). For the purposes of this name
1337        //   lookup, namespace std is an associated namespace.
1338      }
1339
1340      BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1341                                            BEF_begin, BeginNameInfo,
1342                                            BeginMemberLookup, RangeRef.get());
1343      if (BeginExpr.isInvalid())
1344        return StmtError();
1345
1346      EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1347                                          BEF_end, EndNameInfo,
1348                                          EndMemberLookup, RangeRef.get());
1349      if (EndExpr.isInvalid())
1350        return StmtError();
1351    }
1352
1353    // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1354    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1355    if (!Context.hasSameType(BeginType, EndType)) {
1356      Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1357        << BeginType << EndType;
1358      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1359      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1360    }
1361
1362    Decl *BeginEndDecls[] = { BeginVar, EndVar };
1363    // Claim the type doesn't contain auto: we've already done the checking.
1364    DeclGroupPtrTy BeginEndGroup =
1365      BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1366    BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1367
1368    ExprResult BeginRef = BuildDeclRefExpr(BeginVar,
1369                                           BeginType.getNonReferenceType(),
1370                                           VK_LValue, ColonLoc);
1371    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1372                                         VK_LValue, ColonLoc);
1373
1374    // Build and check __begin != __end expression.
1375    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1376                           BeginRef.get(), EndRef.get());
1377    NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1378    NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1379    if (NotEqExpr.isInvalid()) {
1380      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1381      if (!Context.hasSameType(BeginType, EndType))
1382        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1383      return StmtError();
1384    }
1385
1386    // Build and check ++__begin expression.
1387    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1388    IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1389    if (IncrExpr.isInvalid()) {
1390      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1391      return StmtError();
1392    }
1393
1394    // Build and check *__begin  expression.
1395    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1396    if (DerefExpr.isInvalid()) {
1397      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1398      return StmtError();
1399    }
1400
1401    // Attach  *__begin  as initializer for VD.
1402    if (!LoopVar->isInvalidDecl()) {
1403      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1404                           /*TypeMayContainAuto=*/true);
1405      if (LoopVar->isInvalidDecl())
1406        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1407    }
1408  }
1409
1410  return Owned(new (Context) CXXForRangeStmt(RangeDS,
1411                                     cast_or_null<DeclStmt>(BeginEndDecl.get()),
1412                                             NotEqExpr.take(), IncrExpr.take(),
1413                                             LoopVarDS, /*Body=*/0, ForLoc,
1414                                             ColonLoc, RParenLoc));
1415}
1416
1417/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1418/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1419/// body cannot be performed until after the type of the range variable is
1420/// determined.
1421StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1422  if (!S || !B)
1423    return StmtError();
1424
1425  cast<CXXForRangeStmt>(S)->setBody(B);
1426  return S;
1427}
1428
1429StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1430                               SourceLocation LabelLoc,
1431                               LabelDecl *TheDecl) {
1432  getCurFunction()->setHasBranchIntoScope();
1433  TheDecl->setUsed();
1434  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
1435}
1436
1437StmtResult
1438Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
1439                            Expr *E) {
1440  // Convert operand to void*
1441  if (!E->isTypeDependent()) {
1442    QualType ETy = E->getType();
1443    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1444    ExprResult ExprRes = Owned(E);
1445    AssignConvertType ConvTy =
1446      CheckSingleAssignmentConstraints(DestTy, ExprRes);
1447    if (ExprRes.isInvalid())
1448      return StmtError();
1449    E = ExprRes.take();
1450    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
1451      return StmtError();
1452  }
1453
1454  getCurFunction()->setHasIndirectGoto();
1455
1456  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1457}
1458
1459StmtResult
1460Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1461  Scope *S = CurScope->getContinueParent();
1462  if (!S) {
1463    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1464    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1465  }
1466
1467  return Owned(new (Context) ContinueStmt(ContinueLoc));
1468}
1469
1470StmtResult
1471Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1472  Scope *S = CurScope->getBreakParent();
1473  if (!S) {
1474    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1475    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1476  }
1477
1478  return Owned(new (Context) BreakStmt(BreakLoc));
1479}
1480
1481/// \brief Determine whether the given expression is a candidate for
1482/// copy elision in either a return statement or a throw expression.
1483///
1484/// \param ReturnType If we're determining the copy elision candidate for
1485/// a return statement, this is the return type of the function. If we're
1486/// determining the copy elision candidate for a throw expression, this will
1487/// be a NULL type.
1488///
1489/// \param E The expression being returned from the function or block, or
1490/// being thrown.
1491///
1492/// \param AllowFunctionParameter Whether we allow function parameters to
1493/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1494/// we re-use this logic to determine whether we should try to move as part of
1495/// a return or throw (which does allow function parameters).
1496///
1497/// \returns The NRVO candidate variable, if the return statement may use the
1498/// NRVO, or NULL if there is no such candidate.
1499const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1500                                             Expr *E,
1501                                             bool AllowFunctionParameter) {
1502  QualType ExprType = E->getType();
1503  // - in a return statement in a function with ...
1504  // ... a class return type ...
1505  if (!ReturnType.isNull()) {
1506    if (!ReturnType->isRecordType())
1507      return 0;
1508    // ... the same cv-unqualified type as the function return type ...
1509    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1510      return 0;
1511  }
1512
1513  // ... the expression is the name of a non-volatile automatic object
1514  // (other than a function or catch-clause parameter)) ...
1515  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
1516  if (!DR)
1517    return 0;
1518  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1519  if (!VD)
1520    return 0;
1521
1522  if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
1523      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1524      !VD->getType().isVolatileQualified() &&
1525      ((VD->getKind() == Decl::Var) ||
1526       (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
1527    return VD;
1528
1529  return 0;
1530}
1531
1532/// \brief Perform the initialization of a potentially-movable value, which
1533/// is the result of return value.
1534///
1535/// This routine implements C++0x [class.copy]p33, which attempts to treat
1536/// returned lvalues as rvalues in certain cases (to prefer move construction),
1537/// then falls back to treating them as lvalues if that failed.
1538ExprResult
1539Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1540                                      const VarDecl *NRVOCandidate,
1541                                      QualType ResultType,
1542                                      Expr *Value) {
1543  // C++0x [class.copy]p33:
1544  //   When the criteria for elision of a copy operation are met or would
1545  //   be met save for the fact that the source object is a function
1546  //   parameter, and the object to be copied is designated by an lvalue,
1547  //   overload resolution to select the constructor for the copy is first
1548  //   performed as if the object were designated by an rvalue.
1549  ExprResult Res = ExprError();
1550  if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) {
1551    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
1552                              Value->getType(), CK_LValueToRValue,
1553                              Value, VK_XValue);
1554
1555    Expr *InitExpr = &AsRvalue;
1556    InitializationKind Kind
1557      = InitializationKind::CreateCopy(Value->getLocStart(),
1558                                       Value->getLocStart());
1559    InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
1560
1561    //   [...] If overload resolution fails, or if the type of the first
1562    //   parameter of the selected constructor is not an rvalue reference
1563    //   to the object's type (possibly cv-qualified), overload resolution
1564    //   is performed again, considering the object as an lvalue.
1565    if (Seq) {
1566      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1567           StepEnd = Seq.step_end();
1568           Step != StepEnd; ++Step) {
1569        if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
1570          continue;
1571
1572        CXXConstructorDecl *Constructor
1573        = cast<CXXConstructorDecl>(Step->Function.Function);
1574
1575        const RValueReferenceType *RRefType
1576          = Constructor->getParamDecl(0)->getType()
1577                                                 ->getAs<RValueReferenceType>();
1578
1579        // If we don't meet the criteria, break out now.
1580        if (!RRefType ||
1581            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1582                            Context.getTypeDeclType(Constructor->getParent())))
1583          break;
1584
1585        // Promote "AsRvalue" to the heap, since we now need this
1586        // expression node to persist.
1587        Value = ImplicitCastExpr::Create(Context, Value->getType(),
1588                                         CK_LValueToRValue, Value, 0,
1589                                         VK_XValue);
1590
1591        // Complete type-checking the initialization of the return type
1592        // using the constructor we found.
1593        Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
1594      }
1595    }
1596  }
1597
1598  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
1599  // above, or overload resolution failed. Either way, we need to try
1600  // (again) now with the return value expression as written.
1601  if (Res.isInvalid())
1602    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
1603
1604  return Res;
1605}
1606
1607/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1608///
1609StmtResult
1610Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1611  // If this is the first return we've seen in the block, infer the type of
1612  // the block from it.
1613  BlockScopeInfo *CurBlock = getCurBlock();
1614  if (CurBlock->ReturnType.isNull()) {
1615    if (RetValExp) {
1616      // Don't call UsualUnaryConversions(), since we don't want to do
1617      // integer promotions here.
1618      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1619      if (Result.isInvalid())
1620        return StmtError();
1621      RetValExp = Result.take();
1622
1623      if (!RetValExp->isTypeDependent()) {
1624        CurBlock->ReturnType = RetValExp->getType();
1625        if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1626          // We have to remove a 'const' added to copied-in variable which was
1627          // part of the implementation spec. and not the actual qualifier for
1628          // the variable.
1629          if (CDRE->isConstQualAdded())
1630            CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1631        }
1632      } else
1633        CurBlock->ReturnType = Context.DependentTy;
1634    } else
1635      CurBlock->ReturnType = Context.VoidTy;
1636  }
1637  QualType FnRetType = CurBlock->ReturnType;
1638
1639  if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
1640    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1641      << getCurFunctionOrMethodDecl()->getDeclName();
1642    return StmtError();
1643  }
1644
1645  // Otherwise, verify that this result type matches the previous one.  We are
1646  // pickier with blocks than for normal functions because we don't have GCC
1647  // compatibility to worry about here.
1648  ReturnStmt *Result = 0;
1649  if (CurBlock->ReturnType->isVoidType()) {
1650    if (RetValExp && !RetValExp->isTypeDependent() &&
1651        (!getLangOptions().CPlusPlus || !RetValExp->getType()->isVoidType())) {
1652      Diag(ReturnLoc, diag::err_return_block_has_expr);
1653      RetValExp = 0;
1654    }
1655    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1656  } else if (!RetValExp) {
1657    if (!CurBlock->ReturnType->isDependentType())
1658      return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1659
1660    Result = new (Context) ReturnStmt(ReturnLoc, 0, 0);
1661  } else {
1662    const VarDecl *NRVOCandidate = 0;
1663
1664    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1665      // we have a non-void block with an expression, continue checking
1666
1667      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1668      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1669      // function return.
1670
1671      // In C++ the return statement is handled via a copy initialization.
1672      // the C version of which boils down to CheckSingleAssignmentConstraints.
1673      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1674      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1675                                                                     FnRetType,
1676                                                           NRVOCandidate != 0);
1677      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1678                                                       FnRetType, RetValExp);
1679      if (Res.isInvalid()) {
1680        // FIXME: Cleanup temporaries here, anyway?
1681        return StmtError();
1682      }
1683
1684      if (RetValExp) {
1685        CheckImplicitConversions(RetValExp, ReturnLoc);
1686        RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1687      }
1688
1689      RetValExp = Res.takeAs<Expr>();
1690      if (RetValExp)
1691        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1692    }
1693
1694    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1695  }
1696
1697  // If we need to check for the named return value optimization, save the
1698  // return statement in our scope for later processing.
1699  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1700      !CurContext->isDependentContext())
1701    FunctionScopes.back()->Returns.push_back(Result);
1702
1703  return Owned(Result);
1704}
1705
1706StmtResult
1707Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1708  // Check for unexpanded parameter packs.
1709  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
1710    return StmtError();
1711
1712  if (getCurBlock())
1713    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1714
1715  QualType FnRetType;
1716  QualType DeclaredRetType;
1717  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1718    FnRetType = FD->getResultType();
1719    DeclaredRetType = FnRetType;
1720    if (FD->hasAttr<NoReturnAttr>() ||
1721        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1722      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1723        << getCurFunctionOrMethodDecl()->getDeclName();
1724  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1725    DeclaredRetType = MD->getResultType();
1726    if (MD->hasRelatedResultType() && MD->getClassInterface()) {
1727      // In the implementation of a method with a related return type, the
1728      // type used to type-check the validity of return statements within the
1729      // method body is a pointer to the type of the class being implemented.
1730      FnRetType = Context.getObjCInterfaceType(MD->getClassInterface());
1731      FnRetType = Context.getObjCObjectPointerType(FnRetType);
1732    } else {
1733      FnRetType = DeclaredRetType;
1734    }
1735  } else // If we don't have a function/method context, bail.
1736    return StmtError();
1737
1738  ReturnStmt *Result = 0;
1739  if (FnRetType->isVoidType()) {
1740    if (RetValExp) {
1741      if (!RetValExp->isTypeDependent()) {
1742        // C99 6.8.6.4p1 (ext_ since GCC warns)
1743        unsigned D = diag::ext_return_has_expr;
1744        if (RetValExp->getType()->isVoidType())
1745          D = diag::ext_return_has_void_expr;
1746        else {
1747          ExprResult Result = Owned(RetValExp);
1748          Result = IgnoredValueConversions(Result.take());
1749          if (Result.isInvalid())
1750            return StmtError();
1751          RetValExp = Result.take();
1752          RetValExp = ImpCastExprToType(RetValExp,
1753                                        Context.VoidTy, CK_ToVoid).take();
1754        }
1755
1756        // return (some void expression); is legal in C++.
1757        if (D != diag::ext_return_has_void_expr ||
1758            !getLangOptions().CPlusPlus) {
1759          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1760          Diag(ReturnLoc, D)
1761            << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1762            << RetValExp->getSourceRange();
1763        }
1764      }
1765
1766      CheckImplicitConversions(RetValExp, ReturnLoc);
1767      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1768    }
1769
1770    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1771  } else if (!RetValExp && !FnRetType->isDependentType()) {
1772    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1773    // C99 6.8.6.4p1 (ext_ since GCC warns)
1774    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1775
1776    if (FunctionDecl *FD = getCurFunctionDecl())
1777      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1778    else
1779      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1780    Result = new (Context) ReturnStmt(ReturnLoc);
1781  } else {
1782    const VarDecl *NRVOCandidate = 0;
1783    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1784      // we have a non-void function with an expression, continue checking
1785
1786      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1787      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1788      // function return.
1789
1790      // In C++ the return statement is handled via a copy initialization,
1791      // the C version of which boils down to CheckSingleAssignmentConstraints.
1792      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1793      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1794                                                                     FnRetType,
1795                                                            NRVOCandidate != 0);
1796      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1797                                                       FnRetType, RetValExp);
1798      if (Res.isInvalid()) {
1799        // FIXME: Cleanup temporaries here, anyway?
1800        return StmtError();
1801      }
1802
1803      RetValExp = Res.takeAs<Expr>();
1804      if (RetValExp)
1805        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1806    }
1807
1808    if (RetValExp) {
1809      // If we type-checked an Objective-C method's return type based
1810      // on a related return type, we may need to adjust the return
1811      // type again. Do so now.
1812      if (DeclaredRetType != FnRetType) {
1813        ExprResult result = PerformImplicitConversion(RetValExp,
1814                                                      DeclaredRetType,
1815                                                      AA_Returning);
1816        if (result.isInvalid()) return StmtError();
1817        RetValExp = result.take();
1818      }
1819
1820      CheckImplicitConversions(RetValExp, ReturnLoc);
1821      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1822    }
1823    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1824  }
1825
1826  // If we need to check for the named return value optimization, save the
1827  // return statement in our scope for later processing.
1828  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1829      !CurContext->isDependentContext())
1830    FunctionScopes.back()->Returns.push_back(Result);
1831
1832  return Owned(Result);
1833}
1834
1835/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1836/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1837/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1838/// provide a strong guidance to not use it.
1839///
1840/// This method checks to see if the argument is an acceptable l-value and
1841/// returns false if it is a case we can handle.
1842static bool CheckAsmLValue(const Expr *E, Sema &S) {
1843  // Type dependent expressions will be checked during instantiation.
1844  if (E->isTypeDependent())
1845    return false;
1846
1847  if (E->isLValue())
1848    return false;  // Cool, this is an lvalue.
1849
1850  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1851  // are supposed to allow.
1852  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1853  if (E != E2 && E2->isLValue()) {
1854    if (!S.getLangOptions().HeinousExtensions)
1855      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1856        << E->getSourceRange();
1857    else
1858      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1859        << E->getSourceRange();
1860    // Accept, even if we emitted an error diagnostic.
1861    return false;
1862  }
1863
1864  // None of the above, just randomly invalid non-lvalue.
1865  return true;
1866}
1867
1868/// isOperandMentioned - Return true if the specified operand # is mentioned
1869/// anywhere in the decomposed asm string.
1870static bool isOperandMentioned(unsigned OpNo,
1871                         llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
1872  for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1873    const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1874    if (!Piece.isOperand()) continue;
1875
1876    // If this is a reference to the input and if the input was the smaller
1877    // one, then we have to reject this asm.
1878    if (Piece.getOperandNo() == OpNo)
1879      return true;
1880  }
1881
1882  return false;
1883}
1884
1885StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1886                              bool IsVolatile, unsigned NumOutputs,
1887                              unsigned NumInputs, IdentifierInfo **Names,
1888                              MultiExprArg constraints, MultiExprArg exprs,
1889                              Expr *asmString, MultiExprArg clobbers,
1890                              SourceLocation RParenLoc, bool MSAsm) {
1891  unsigned NumClobbers = clobbers.size();
1892  StringLiteral **Constraints =
1893    reinterpret_cast<StringLiteral**>(constraints.get());
1894  Expr **Exprs = exprs.get();
1895  StringLiteral *AsmString = cast<StringLiteral>(asmString);
1896  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1897
1898  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1899
1900  // The parser verifies that there is a string literal here.
1901  if (AsmString->isWide())
1902    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1903      << AsmString->getSourceRange());
1904
1905  for (unsigned i = 0; i != NumOutputs; i++) {
1906    StringLiteral *Literal = Constraints[i];
1907    if (Literal->isWide())
1908      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1909        << Literal->getSourceRange());
1910
1911    llvm::StringRef OutputName;
1912    if (Names[i])
1913      OutputName = Names[i]->getName();
1914
1915    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1916    if (!Context.Target.validateOutputConstraint(Info))
1917      return StmtError(Diag(Literal->getLocStart(),
1918                            diag::err_asm_invalid_output_constraint)
1919                       << Info.getConstraintStr());
1920
1921    // Check that the output exprs are valid lvalues.
1922    Expr *OutputExpr = Exprs[i];
1923    if (CheckAsmLValue(OutputExpr, *this)) {
1924      return StmtError(Diag(OutputExpr->getLocStart(),
1925                  diag::err_asm_invalid_lvalue_in_output)
1926        << OutputExpr->getSourceRange());
1927    }
1928
1929    OutputConstraintInfos.push_back(Info);
1930  }
1931
1932  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1933
1934  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1935    StringLiteral *Literal = Constraints[i];
1936    if (Literal->isWide())
1937      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1938        << Literal->getSourceRange());
1939
1940    llvm::StringRef InputName;
1941    if (Names[i])
1942      InputName = Names[i]->getName();
1943
1944    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1945    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1946                                                NumOutputs, Info)) {
1947      return StmtError(Diag(Literal->getLocStart(),
1948                            diag::err_asm_invalid_input_constraint)
1949                       << Info.getConstraintStr());
1950    }
1951
1952    Expr *InputExpr = Exprs[i];
1953
1954    // Only allow void types for memory constraints.
1955    if (Info.allowsMemory() && !Info.allowsRegister()) {
1956      if (CheckAsmLValue(InputExpr, *this))
1957        return StmtError(Diag(InputExpr->getLocStart(),
1958                              diag::err_asm_invalid_lvalue_in_input)
1959                         << Info.getConstraintStr()
1960                         << InputExpr->getSourceRange());
1961    }
1962
1963    if (Info.allowsRegister()) {
1964      if (InputExpr->getType()->isVoidType()) {
1965        return StmtError(Diag(InputExpr->getLocStart(),
1966                              diag::err_asm_invalid_type_in_input)
1967          << InputExpr->getType() << Info.getConstraintStr()
1968          << InputExpr->getSourceRange());
1969      }
1970    }
1971
1972    ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
1973    if (Result.isInvalid())
1974      return StmtError();
1975
1976    Exprs[i] = Result.take();
1977    InputConstraintInfos.push_back(Info);
1978  }
1979
1980  // Check that the clobbers are valid.
1981  for (unsigned i = 0; i != NumClobbers; i++) {
1982    StringLiteral *Literal = Clobbers[i];
1983    if (Literal->isWide())
1984      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1985        << Literal->getSourceRange());
1986
1987    llvm::StringRef Clobber = Literal->getString();
1988
1989    if (!Context.Target.isValidGCCRegisterName(Clobber))
1990      return StmtError(Diag(Literal->getLocStart(),
1991                  diag::err_asm_unknown_register_name) << Clobber);
1992  }
1993
1994  AsmStmt *NS =
1995    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1996                          NumOutputs, NumInputs, Names, Constraints, Exprs,
1997                          AsmString, NumClobbers, Clobbers, RParenLoc);
1998  // Validate the asm string, ensuring it makes sense given the operands we
1999  // have.
2000  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2001  unsigned DiagOffs;
2002  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
2003    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2004           << AsmString->getSourceRange();
2005    return StmtError();
2006  }
2007
2008  // Validate tied input operands for type mismatches.
2009  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2010    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2011
2012    // If this is a tied constraint, verify that the output and input have
2013    // either exactly the same type, or that they are int/ptr operands with the
2014    // same size (int/long, int*/long, are ok etc).
2015    if (!Info.hasTiedOperand()) continue;
2016
2017    unsigned TiedTo = Info.getTiedOperand();
2018    unsigned InputOpNo = i+NumOutputs;
2019    Expr *OutputExpr = Exprs[TiedTo];
2020    Expr *InputExpr = Exprs[InputOpNo];
2021    QualType InTy = InputExpr->getType();
2022    QualType OutTy = OutputExpr->getType();
2023    if (Context.hasSameType(InTy, OutTy))
2024      continue;  // All types can be tied to themselves.
2025
2026    // Decide if the input and output are in the same domain (integer/ptr or
2027    // floating point.
2028    enum AsmDomain {
2029      AD_Int, AD_FP, AD_Other
2030    } InputDomain, OutputDomain;
2031
2032    if (InTy->isIntegerType() || InTy->isPointerType())
2033      InputDomain = AD_Int;
2034    else if (InTy->isRealFloatingType())
2035      InputDomain = AD_FP;
2036    else
2037      InputDomain = AD_Other;
2038
2039    if (OutTy->isIntegerType() || OutTy->isPointerType())
2040      OutputDomain = AD_Int;
2041    else if (OutTy->isRealFloatingType())
2042      OutputDomain = AD_FP;
2043    else
2044      OutputDomain = AD_Other;
2045
2046    // They are ok if they are the same size and in the same domain.  This
2047    // allows tying things like:
2048    //   void* to int*
2049    //   void* to int            if they are the same size.
2050    //   double to long double   if they are the same size.
2051    //
2052    uint64_t OutSize = Context.getTypeSize(OutTy);
2053    uint64_t InSize = Context.getTypeSize(InTy);
2054    if (OutSize == InSize && InputDomain == OutputDomain &&
2055        InputDomain != AD_Other)
2056      continue;
2057
2058    // If the smaller input/output operand is not mentioned in the asm string,
2059    // then we can promote the smaller one to a larger input and the asm string
2060    // won't notice.
2061    bool SmallerValueMentioned = false;
2062
2063    // If this is a reference to the input and if the input was the smaller
2064    // one, then we have to reject this asm.
2065    if (isOperandMentioned(InputOpNo, Pieces)) {
2066      // This is a use in the asm string of the smaller operand.  Since we
2067      // codegen this by promoting to a wider value, the asm will get printed
2068      // "wrong".
2069      SmallerValueMentioned |= InSize < OutSize;
2070    }
2071    if (isOperandMentioned(TiedTo, Pieces)) {
2072      // If this is a reference to the output, and if the output is the larger
2073      // value, then it's ok because we'll promote the input to the larger type.
2074      SmallerValueMentioned |= OutSize < InSize;
2075    }
2076
2077    // If the smaller value wasn't mentioned in the asm string, and if the
2078    // output was a register, just extend the shorter one to the size of the
2079    // larger one.
2080    if (!SmallerValueMentioned && InputDomain != AD_Other &&
2081        OutputConstraintInfos[TiedTo].allowsRegister())
2082      continue;
2083
2084    // Either both of the operands were mentioned or the smaller one was
2085    // mentioned.  One more special case that we'll allow: if the tied input is
2086    // integer, unmentioned, and is a constant, then we'll allow truncating it
2087    // down to the size of the destination.
2088    if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2089        !isOperandMentioned(InputOpNo, Pieces) &&
2090        InputExpr->isEvaluatable(Context)) {
2091      CastKind castKind =
2092        (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2093      InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2094      Exprs[InputOpNo] = InputExpr;
2095      NS->setInputExpr(i, InputExpr);
2096      continue;
2097    }
2098
2099    Diag(InputExpr->getLocStart(),
2100         diag::err_asm_tying_incompatible_types)
2101      << InTy << OutTy << OutputExpr->getSourceRange()
2102      << InputExpr->getSourceRange();
2103    return StmtError();
2104  }
2105
2106  return Owned(NS);
2107}
2108
2109StmtResult
2110Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2111                           SourceLocation RParen, Decl *Parm,
2112                           Stmt *Body) {
2113  VarDecl *Var = cast_or_null<VarDecl>(Parm);
2114  if (Var && Var->isInvalidDecl())
2115    return StmtError();
2116
2117  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
2118}
2119
2120StmtResult
2121Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2122  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2123}
2124
2125StmtResult
2126Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2127                         MultiStmtArg CatchStmts, Stmt *Finally) {
2128  if (!getLangOptions().ObjCExceptions)
2129    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2130
2131  getCurFunction()->setHasBranchProtectedScope();
2132  unsigned NumCatchStmts = CatchStmts.size();
2133  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2134                                     CatchStmts.release(),
2135                                     NumCatchStmts,
2136                                     Finally));
2137}
2138
2139StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
2140                                                  Expr *Throw) {
2141  if (Throw) {
2142    ExprResult Result = DefaultLvalueConversion(Throw);
2143    if (Result.isInvalid())
2144      return StmtError();
2145
2146    Throw = Result.take();
2147    QualType ThrowType = Throw->getType();
2148    // Make sure the expression type is an ObjC pointer or "void *".
2149    if (!ThrowType->isDependentType() &&
2150        !ThrowType->isObjCObjectPointerType()) {
2151      const PointerType *PT = ThrowType->getAs<PointerType>();
2152      if (!PT || !PT->getPointeeType()->isVoidType())
2153        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2154                         << Throw->getType() << Throw->getSourceRange());
2155    }
2156  }
2157
2158  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2159}
2160
2161StmtResult
2162Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2163                           Scope *CurScope) {
2164  if (!getLangOptions().ObjCExceptions)
2165    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2166
2167  if (!Throw) {
2168    // @throw without an expression designates a rethrow (which much occur
2169    // in the context of an @catch clause).
2170    Scope *AtCatchParent = CurScope;
2171    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2172      AtCatchParent = AtCatchParent->getParent();
2173    if (!AtCatchParent)
2174      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2175  }
2176
2177  return BuildObjCAtThrowStmt(AtLoc, Throw);
2178}
2179
2180StmtResult
2181Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2182                                  Stmt *SyncBody) {
2183  getCurFunction()->setHasBranchProtectedScope();
2184
2185  ExprResult Result = DefaultLvalueConversion(SyncExpr);
2186  if (Result.isInvalid())
2187    return StmtError();
2188
2189  SyncExpr = Result.take();
2190  // Make sure the expression type is an ObjC pointer or "void *".
2191  if (!SyncExpr->getType()->isDependentType() &&
2192      !SyncExpr->getType()->isObjCObjectPointerType()) {
2193    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
2194    if (!PT || !PT->getPointeeType()->isVoidType())
2195      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
2196                       << SyncExpr->getType() << SyncExpr->getSourceRange());
2197  }
2198
2199  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2200}
2201
2202/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2203/// and creates a proper catch handler from them.
2204StmtResult
2205Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
2206                         Stmt *HandlerBlock) {
2207  // There's nothing to test that ActOnExceptionDecl didn't already test.
2208  return Owned(new (Context) CXXCatchStmt(CatchLoc,
2209                                          cast_or_null<VarDecl>(ExDecl),
2210                                          HandlerBlock));
2211}
2212
2213StmtResult
2214Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2215  getCurFunction()->setHasBranchProtectedScope();
2216  return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2217}
2218
2219namespace {
2220
2221class TypeWithHandler {
2222  QualType t;
2223  CXXCatchStmt *stmt;
2224public:
2225  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2226  : t(type), stmt(statement) {}
2227
2228  // An arbitrary order is fine as long as it places identical
2229  // types next to each other.
2230  bool operator<(const TypeWithHandler &y) const {
2231    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2232      return true;
2233    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2234      return false;
2235    else
2236      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2237  }
2238
2239  bool operator==(const TypeWithHandler& other) const {
2240    return t == other.t;
2241  }
2242
2243  CXXCatchStmt *getCatchStmt() const { return stmt; }
2244  SourceLocation getTypeSpecStartLoc() const {
2245    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2246  }
2247};
2248
2249}
2250
2251/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2252/// handlers and creates a try statement from them.
2253StmtResult
2254Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2255                       MultiStmtArg RawHandlers) {
2256  // Don't report an error if 'try' is used in system headers.
2257  if (!getLangOptions().CXXExceptions &&
2258      !getSourceManager().isInSystemHeader(TryLoc))
2259      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
2260
2261  unsigned NumHandlers = RawHandlers.size();
2262  assert(NumHandlers > 0 &&
2263         "The parser shouldn't call this if there are no handlers.");
2264  Stmt **Handlers = RawHandlers.get();
2265
2266  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
2267
2268  for (unsigned i = 0; i < NumHandlers; ++i) {
2269    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
2270    if (!Handler->getExceptionDecl()) {
2271      if (i < NumHandlers - 1)
2272        return StmtError(Diag(Handler->getLocStart(),
2273                              diag::err_early_catch_all));
2274
2275      continue;
2276    }
2277
2278    const QualType CaughtType = Handler->getCaughtType();
2279    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2280    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
2281  }
2282
2283  // Detect handlers for the same type as an earlier one.
2284  if (NumHandlers > 1) {
2285    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
2286
2287    TypeWithHandler prev = TypesWithHandlers[0];
2288    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2289      TypeWithHandler curr = TypesWithHandlers[i];
2290
2291      if (curr == prev) {
2292        Diag(curr.getTypeSpecStartLoc(),
2293             diag::warn_exception_caught_by_earlier_handler)
2294          << curr.getCatchStmt()->getCaughtType().getAsString();
2295        Diag(prev.getTypeSpecStartLoc(),
2296             diag::note_previous_exception_handler)
2297          << prev.getCatchStmt()->getCaughtType().getAsString();
2298      }
2299
2300      prev = curr;
2301    }
2302  }
2303
2304  getCurFunction()->setHasBranchProtectedScope();
2305
2306  // FIXME: We should detect handlers that cannot catch anything because an
2307  // earlier handler catches a superclass. Need to find a method that is not
2308  // quadratic for this.
2309  // Neither of these are explicitly forbidden, but every compiler detects them
2310  // and warns.
2311
2312  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
2313                                  Handlers, NumHandlers));
2314}
2315
2316StmtResult
2317Sema::ActOnSEHTryBlock(bool IsCXXTry,
2318                       SourceLocation TryLoc,
2319                       Stmt *TryBlock,
2320                       Stmt *Handler) {
2321  assert(TryBlock && Handler);
2322
2323  getCurFunction()->setHasBranchProtectedScope();
2324
2325  return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2326}
2327
2328StmtResult
2329Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2330                          Expr *FilterExpr,
2331                          Stmt *Block) {
2332  assert(FilterExpr && Block);
2333
2334  if(!FilterExpr->getType()->isIntegerType()) {
2335    return StmtError(Diag(FilterExpr->getExprLoc(),
2336                     diag::err_filter_expression_integral)
2337                     << FilterExpr->getType());
2338  }
2339
2340  return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2341}
2342
2343StmtResult
2344Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2345                           Stmt *Block) {
2346  assert(Block);
2347  return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2348}
2349
2350