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