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