SemaStmt.cpp revision 7e1fb9abfc8d67fe4e7203ef6830a893df704d7b
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/EvaluatedExprVisitor.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Triple.h"
37#include "llvm/MC/MCAsmInfo.h"
38#include "llvm/MC/MCContext.h"
39#include "llvm/MC/MCInst.h"
40#include "llvm/MC/MCInstPrinter.h"
41#include "llvm/MC/MCInstrInfo.h"
42#include "llvm/MC/MCObjectFileInfo.h"
43#include "llvm/MC/MCRegisterInfo.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSubtargetInfo.h"
46#include "llvm/MC/MCTargetAsmParser.h"
47#include "llvm/MC/MCParser/MCAsmLexer.h"
48#include "llvm/MC/MCParser/MCAsmParser.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TargetRegistry.h"
51#include "llvm/Support/TargetSelect.h"
52using namespace clang;
53using namespace sema;
54
55StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
56  Expr *E = expr.get();
57  if (!E) // FIXME: FullExprArg has no error state?
58    return StmtError();
59
60  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
61  // void expression for its side effects.  Conversion to void allows any
62  // operand, even incomplete types.
63
64  // Same thing in for stmt first clause (when expr) and third clause.
65  return Owned(static_cast<Stmt*>(E));
66}
67
68
69StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
70                               bool HasLeadingEmptyMacro) {
71  return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
72}
73
74StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
75                               SourceLocation EndLoc) {
76  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
77
78  // If we have an invalid decl, just return an error.
79  if (DG.isNull()) return StmtError();
80
81  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
82}
83
84void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
85  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
86
87  // If we have an invalid decl, just return.
88  if (DG.isNull() || !DG.isSingleDecl()) return;
89  VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
90
91  // suppress any potential 'unused variable' warning.
92  var->setUsed();
93
94  // foreach variables are never actually initialized in the way that
95  // the parser came up with.
96  var->setInit(0);
97
98  // In ARC, we don't need to retain the iteration variable of a fast
99  // enumeration loop.  Rather than actually trying to catch that
100  // during declaration processing, we remove the consequences here.
101  if (getLangOpts().ObjCAutoRefCount) {
102    QualType type = var->getType();
103
104    // Only do this if we inferred the lifetime.  Inferred lifetime
105    // will show up as a local qualifier because explicit lifetime
106    // should have shown up as an AttributedType instead.
107    if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
108      // Add 'const' and mark the variable as pseudo-strong.
109      var->setType(type.withConst());
110      var->setARCPseudoStrong(true);
111    }
112  }
113}
114
115/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
116///
117/// Adding a cast to void (or other expression wrappers) will prevent the
118/// warning from firing.
119static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
120  SourceLocation Loc;
121  bool IsNotEqual, CanAssign;
122
123  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
124    if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
125      return false;
126
127    Loc = Op->getOperatorLoc();
128    IsNotEqual = Op->getOpcode() == BO_NE;
129    CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
130  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
131    if (Op->getOperator() != OO_EqualEqual &&
132        Op->getOperator() != OO_ExclaimEqual)
133      return false;
134
135    Loc = Op->getOperatorLoc();
136    IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
137    CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
138  } else {
139    // Not a typo-prone comparison.
140    return false;
141  }
142
143  // Suppress warnings when the operator, suspicious as it may be, comes from
144  // a macro expansion.
145  if (Loc.isMacroID())
146    return false;
147
148  S.Diag(Loc, diag::warn_unused_comparison)
149    << (unsigned)IsNotEqual << E->getSourceRange();
150
151  // If the LHS is a plausible entity to assign to, provide a fixit hint to
152  // correct common typos.
153  if (CanAssign) {
154    if (IsNotEqual)
155      S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
156        << FixItHint::CreateReplacement(Loc, "|=");
157    else
158      S.Diag(Loc, diag::note_equality_comparison_to_assign)
159        << FixItHint::CreateReplacement(Loc, "=");
160  }
161
162  return true;
163}
164
165void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
166  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
167    return DiagnoseUnusedExprResult(Label->getSubStmt());
168
169  const Expr *E = dyn_cast_or_null<Expr>(S);
170  if (!E)
171    return;
172
173  const Expr *WarnExpr;
174  SourceLocation Loc;
175  SourceRange R1, R2;
176  if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
177      !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
178    return;
179
180  // Okay, we have an unused result.  Depending on what the base expression is,
181  // we might want to make a more specific diagnostic.  Check for one of these
182  // cases now.
183  unsigned DiagID = diag::warn_unused_expr;
184  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
185    E = Temps->getSubExpr();
186  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
187    E = TempExpr->getSubExpr();
188
189  if (DiagnoseUnusedComparison(*this, E))
190    return;
191
192  E = WarnExpr;
193  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
194    if (E->getType()->isVoidType())
195      return;
196
197    // If the callee has attribute pure, const, or warn_unused_result, warn with
198    // a more specific message to make it clear what is happening.
199    if (const Decl *FD = CE->getCalleeDecl()) {
200      if (FD->getAttr<WarnUnusedResultAttr>()) {
201        Diag(Loc, diag::warn_unused_result) << R1 << R2;
202        return;
203      }
204      if (FD->getAttr<PureAttr>()) {
205        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
206        return;
207      }
208      if (FD->getAttr<ConstAttr>()) {
209        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
210        return;
211      }
212    }
213  } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
214    if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
215      Diag(Loc, diag::err_arc_unused_init_message) << R1;
216      return;
217    }
218    const ObjCMethodDecl *MD = ME->getMethodDecl();
219    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
220      Diag(Loc, diag::warn_unused_result) << R1 << R2;
221      return;
222    }
223  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
224    const Expr *Source = POE->getSyntacticForm();
225    if (isa<ObjCSubscriptRefExpr>(Source))
226      DiagID = diag::warn_unused_container_subscript_expr;
227    else
228      DiagID = diag::warn_unused_property_expr;
229  } else if (const CXXFunctionalCastExpr *FC
230                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
231    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
232        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
233      return;
234  }
235  // Diagnose "(void*) blah" as a typo for "(void) blah".
236  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
237    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
238    QualType T = TI->getType();
239
240    // We really do want to use the non-canonical type here.
241    if (T == Context.VoidPtrTy) {
242      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
243
244      Diag(Loc, diag::warn_unused_voidptr)
245        << FixItHint::CreateRemoval(TL.getStarLoc());
246      return;
247    }
248  }
249
250  if (E->isGLValue() && E->getType().isVolatileQualified()) {
251    Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
252    return;
253  }
254
255  DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
256}
257
258void Sema::ActOnStartOfCompoundStmt() {
259  PushCompoundScope();
260}
261
262void Sema::ActOnFinishOfCompoundStmt() {
263  PopCompoundScope();
264}
265
266sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
267  return getCurFunction()->CompoundScopes.back();
268}
269
270StmtResult
271Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
272                        MultiStmtArg elts, bool isStmtExpr) {
273  unsigned NumElts = elts.size();
274  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
275  // If we're in C89 mode, check that we don't have any decls after stmts.  If
276  // so, emit an extension diagnostic.
277  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
278    // Note that __extension__ can be around a decl.
279    unsigned i = 0;
280    // Skip over all declarations.
281    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
282      /*empty*/;
283
284    // We found the end of the list or a statement.  Scan for another declstmt.
285    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
286      /*empty*/;
287
288    if (i != NumElts) {
289      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
290      Diag(D->getLocation(), diag::ext_mixed_decls_code);
291    }
292  }
293  // Warn about unused expressions in statements.
294  for (unsigned i = 0; i != NumElts; ++i) {
295    // Ignore statements that are last in a statement expression.
296    if (isStmtExpr && i == NumElts - 1)
297      continue;
298
299    DiagnoseUnusedExprResult(Elts[i]);
300  }
301
302  // Check for suspicious empty body (null statement) in `for' and `while'
303  // statements.  Don't do anything for template instantiations, this just adds
304  // noise.
305  if (NumElts != 0 && !CurrentInstantiationScope &&
306      getCurCompoundScope().HasEmptyLoopBodies) {
307    for (unsigned i = 0; i != NumElts - 1; ++i)
308      DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
309  }
310
311  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
312}
313
314StmtResult
315Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
316                    SourceLocation DotDotDotLoc, Expr *RHSVal,
317                    SourceLocation ColonLoc) {
318  assert((LHSVal != 0) && "missing expression in case statement");
319
320  if (getCurFunction()->SwitchStack.empty()) {
321    Diag(CaseLoc, diag::err_case_not_in_switch);
322    return StmtError();
323  }
324
325  if (!getLangOpts().CPlusPlus0x) {
326    // C99 6.8.4.2p3: The expression shall be an integer constant.
327    // However, GCC allows any evaluatable integer expression.
328    if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
329      LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
330      if (!LHSVal)
331        return StmtError();
332    }
333
334    // GCC extension: The expression shall be an integer constant.
335
336    if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
337      RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
338      // Recover from an error by just forgetting about it.
339    }
340  }
341
342  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
343                                        ColonLoc);
344  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
345  return Owned(CS);
346}
347
348/// ActOnCaseStmtBody - This installs a statement as the body of a case.
349void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
350  DiagnoseUnusedExprResult(SubStmt);
351
352  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
353  CS->setSubStmt(SubStmt);
354}
355
356StmtResult
357Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
358                       Stmt *SubStmt, Scope *CurScope) {
359  DiagnoseUnusedExprResult(SubStmt);
360
361  if (getCurFunction()->SwitchStack.empty()) {
362    Diag(DefaultLoc, diag::err_default_not_in_switch);
363    return Owned(SubStmt);
364  }
365
366  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
367  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
368  return Owned(DS);
369}
370
371StmtResult
372Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
373                     SourceLocation ColonLoc, Stmt *SubStmt) {
374  // If the label was multiply defined, reject it now.
375  if (TheDecl->getStmt()) {
376    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
377    Diag(TheDecl->getLocation(), diag::note_previous_definition);
378    return Owned(SubStmt);
379  }
380
381  // Otherwise, things are good.  Fill in the declaration and return it.
382  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
383  TheDecl->setStmt(LS);
384  if (!TheDecl->isGnuLocal())
385    TheDecl->setLocation(IdentLoc);
386  return Owned(LS);
387}
388
389StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
390                                     ArrayRef<const Attr*> Attrs,
391                                     Stmt *SubStmt) {
392  // Fill in the declaration and return it.
393  AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
394  return Owned(LS);
395}
396
397StmtResult
398Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
399                  Stmt *thenStmt, SourceLocation ElseLoc,
400                  Stmt *elseStmt) {
401  ExprResult CondResult(CondVal.release());
402
403  VarDecl *ConditionVar = 0;
404  if (CondVar) {
405    ConditionVar = cast<VarDecl>(CondVar);
406    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
407    if (CondResult.isInvalid())
408      return StmtError();
409  }
410  Expr *ConditionExpr = CondResult.takeAs<Expr>();
411  if (!ConditionExpr)
412    return StmtError();
413
414  DiagnoseUnusedExprResult(thenStmt);
415
416  if (!elseStmt) {
417    DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
418                          diag::warn_empty_if_body);
419  }
420
421  DiagnoseUnusedExprResult(elseStmt);
422
423  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
424                                    thenStmt, ElseLoc, elseStmt));
425}
426
427/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
428/// the specified width and sign.  If an overflow occurs, detect it and emit
429/// the specified diagnostic.
430void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
431                                              unsigned NewWidth, bool NewSign,
432                                              SourceLocation Loc,
433                                              unsigned DiagID) {
434  // Perform a conversion to the promoted condition type if needed.
435  if (NewWidth > Val.getBitWidth()) {
436    // If this is an extension, just do it.
437    Val = Val.extend(NewWidth);
438    Val.setIsSigned(NewSign);
439
440    // If the input was signed and negative and the output is
441    // unsigned, don't bother to warn: this is implementation-defined
442    // behavior.
443    // FIXME: Introduce a second, default-ignored warning for this case?
444  } else if (NewWidth < Val.getBitWidth()) {
445    // If this is a truncation, check for overflow.
446    llvm::APSInt ConvVal(Val);
447    ConvVal = ConvVal.trunc(NewWidth);
448    ConvVal.setIsSigned(NewSign);
449    ConvVal = ConvVal.extend(Val.getBitWidth());
450    ConvVal.setIsSigned(Val.isSigned());
451    if (ConvVal != Val)
452      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
453
454    // Regardless of whether a diagnostic was emitted, really do the
455    // truncation.
456    Val = Val.trunc(NewWidth);
457    Val.setIsSigned(NewSign);
458  } else if (NewSign != Val.isSigned()) {
459    // Convert the sign to match the sign of the condition.  This can cause
460    // overflow as well: unsigned(INTMIN)
461    // We don't diagnose this overflow, because it is implementation-defined
462    // behavior.
463    // FIXME: Introduce a second, default-ignored warning for this case?
464    llvm::APSInt OldVal(Val);
465    Val.setIsSigned(NewSign);
466  }
467}
468
469namespace {
470  struct CaseCompareFunctor {
471    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
472                    const llvm::APSInt &RHS) {
473      return LHS.first < RHS;
474    }
475    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
476                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
477      return LHS.first < RHS.first;
478    }
479    bool operator()(const llvm::APSInt &LHS,
480                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
481      return LHS < RHS.first;
482    }
483  };
484}
485
486/// CmpCaseVals - Comparison predicate for sorting case values.
487///
488static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
489                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
490  if (lhs.first < rhs.first)
491    return true;
492
493  if (lhs.first == rhs.first &&
494      lhs.second->getCaseLoc().getRawEncoding()
495       < rhs.second->getCaseLoc().getRawEncoding())
496    return true;
497  return false;
498}
499
500/// CmpEnumVals - Comparison predicate for sorting enumeration values.
501///
502static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
503                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
504{
505  return lhs.first < rhs.first;
506}
507
508/// EqEnumVals - Comparison preficate for uniqing enumeration values.
509///
510static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
511                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
512{
513  return lhs.first == rhs.first;
514}
515
516/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
517/// potentially integral-promoted expression @p expr.
518static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
519  if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
520    expr = cleanups->getSubExpr();
521  while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
522    if (impcast->getCastKind() != CK_IntegralCast) break;
523    expr = impcast->getSubExpr();
524  }
525  return expr->getType();
526}
527
528StmtResult
529Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
530                             Decl *CondVar) {
531  ExprResult CondResult;
532
533  VarDecl *ConditionVar = 0;
534  if (CondVar) {
535    ConditionVar = cast<VarDecl>(CondVar);
536    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
537    if (CondResult.isInvalid())
538      return StmtError();
539
540    Cond = CondResult.release();
541  }
542
543  if (!Cond)
544    return StmtError();
545
546  class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
547    Expr *Cond;
548
549  public:
550    SwitchConvertDiagnoser(Expr *Cond)
551      : ICEConvertDiagnoser(false, true), Cond(Cond) { }
552
553    virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
554                                             QualType T) {
555      return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
556    }
557
558    virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
559                                                 QualType T) {
560      return S.Diag(Loc, diag::err_switch_incomplete_class_type)
561               << T << Cond->getSourceRange();
562    }
563
564    virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
565                                                   QualType T,
566                                                   QualType ConvTy) {
567      return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
568    }
569
570    virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
571                                               QualType ConvTy) {
572      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
573        << ConvTy->isEnumeralType() << ConvTy;
574    }
575
576    virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
577                                                QualType T) {
578      return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
579    }
580
581    virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
582                                            QualType ConvTy) {
583      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
584      << ConvTy->isEnumeralType() << ConvTy;
585    }
586
587    virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
588                                                 QualType T,
589                                                 QualType ConvTy) {
590      return DiagnosticBuilder::getEmpty();
591    }
592  } SwitchDiagnoser(Cond);
593
594  CondResult
595    = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
596                                         /*AllowScopedEnumerations*/ true);
597  if (CondResult.isInvalid()) return StmtError();
598  Cond = CondResult.take();
599
600  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
601  CondResult = UsualUnaryConversions(Cond);
602  if (CondResult.isInvalid()) return StmtError();
603  Cond = CondResult.take();
604
605  if (!CondVar) {
606    CheckImplicitConversions(Cond, SwitchLoc);
607    CondResult = MaybeCreateExprWithCleanups(Cond);
608    if (CondResult.isInvalid())
609      return StmtError();
610    Cond = CondResult.take();
611  }
612
613  getCurFunction()->setHasBranchIntoScope();
614
615  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
616  getCurFunction()->SwitchStack.push_back(SS);
617  return Owned(SS);
618}
619
620static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
621  if (Val.getBitWidth() < BitWidth)
622    Val = Val.extend(BitWidth);
623  else if (Val.getBitWidth() > BitWidth)
624    Val = Val.trunc(BitWidth);
625  Val.setIsSigned(IsSigned);
626}
627
628StmtResult
629Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
630                            Stmt *BodyStmt) {
631  SwitchStmt *SS = cast<SwitchStmt>(Switch);
632  assert(SS == getCurFunction()->SwitchStack.back() &&
633         "switch stack missing push/pop!");
634
635  SS->setBody(BodyStmt, SwitchLoc);
636  getCurFunction()->SwitchStack.pop_back();
637
638  Expr *CondExpr = SS->getCond();
639  if (!CondExpr) return StmtError();
640
641  QualType CondType = CondExpr->getType();
642
643  Expr *CondExprBeforePromotion = CondExpr;
644  QualType CondTypeBeforePromotion =
645      GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
646
647  // C++ 6.4.2.p2:
648  // Integral promotions are performed (on the switch condition).
649  //
650  // A case value unrepresentable by the original switch condition
651  // type (before the promotion) doesn't make sense, even when it can
652  // be represented by the promoted type.  Therefore we need to find
653  // the pre-promotion type of the switch condition.
654  if (!CondExpr->isTypeDependent()) {
655    // We have already converted the expression to an integral or enumeration
656    // type, when we started the switch statement. If we don't have an
657    // appropriate type now, just return an error.
658    if (!CondType->isIntegralOrEnumerationType())
659      return StmtError();
660
661    if (CondExpr->isKnownToHaveBooleanValue()) {
662      // switch(bool_expr) {...} is often a programmer error, e.g.
663      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
664      // One can always use an if statement instead of switch(bool_expr).
665      Diag(SwitchLoc, diag::warn_bool_switch_condition)
666          << CondExpr->getSourceRange();
667    }
668  }
669
670  // Get the bitwidth of the switched-on value before promotions.  We must
671  // convert the integer case values to this width before comparison.
672  bool HasDependentValue
673    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
674  unsigned CondWidth
675    = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
676  bool CondIsSigned
677    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
678
679  // Accumulate all of the case values in a vector so that we can sort them
680  // and detect duplicates.  This vector contains the APInt for the case after
681  // it has been converted to the condition type.
682  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
683  CaseValsTy CaseVals;
684
685  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
686  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
687  CaseRangesTy CaseRanges;
688
689  DefaultStmt *TheDefaultStmt = 0;
690
691  bool CaseListIsErroneous = false;
692
693  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
694       SC = SC->getNextSwitchCase()) {
695
696    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
697      if (TheDefaultStmt) {
698        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
699        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
700
701        // FIXME: Remove the default statement from the switch block so that
702        // we'll return a valid AST.  This requires recursing down the AST and
703        // finding it, not something we are set up to do right now.  For now,
704        // just lop the entire switch stmt out of the AST.
705        CaseListIsErroneous = true;
706      }
707      TheDefaultStmt = DS;
708
709    } else {
710      CaseStmt *CS = cast<CaseStmt>(SC);
711
712      Expr *Lo = CS->getLHS();
713
714      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
715        HasDependentValue = true;
716        break;
717      }
718
719      llvm::APSInt LoVal;
720
721      if (getLangOpts().CPlusPlus0x) {
722        // C++11 [stmt.switch]p2: the constant-expression shall be a converted
723        // constant expression of the promoted type of the switch condition.
724        ExprResult ConvLo =
725          CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
726        if (ConvLo.isInvalid()) {
727          CaseListIsErroneous = true;
728          continue;
729        }
730        Lo = ConvLo.take();
731      } else {
732        // We already verified that the expression has a i-c-e value (C99
733        // 6.8.4.2p3) - get that value now.
734        LoVal = Lo->EvaluateKnownConstInt(Context);
735
736        // If the LHS is not the same type as the condition, insert an implicit
737        // cast.
738        Lo = DefaultLvalueConversion(Lo).take();
739        Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
740      }
741
742      // Convert the value to the same width/sign as the condition had prior to
743      // integral promotions.
744      //
745      // FIXME: This causes us to reject valid code:
746      //   switch ((char)c) { case 256: case 0: return 0; }
747      // Here we claim there is a duplicated condition value, but there is not.
748      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
749                                         Lo->getLocStart(),
750                                         diag::warn_case_value_overflow);
751
752      CS->setLHS(Lo);
753
754      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
755      if (CS->getRHS()) {
756        if (CS->getRHS()->isTypeDependent() ||
757            CS->getRHS()->isValueDependent()) {
758          HasDependentValue = true;
759          break;
760        }
761        CaseRanges.push_back(std::make_pair(LoVal, CS));
762      } else
763        CaseVals.push_back(std::make_pair(LoVal, CS));
764    }
765  }
766
767  if (!HasDependentValue) {
768    // If we don't have a default statement, check whether the
769    // condition is constant.
770    llvm::APSInt ConstantCondValue;
771    bool HasConstantCond = false;
772    if (!HasDependentValue && !TheDefaultStmt) {
773      HasConstantCond
774        = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
775                                                 Expr::SE_AllowSideEffects);
776      assert(!HasConstantCond ||
777             (ConstantCondValue.getBitWidth() == CondWidth &&
778              ConstantCondValue.isSigned() == CondIsSigned));
779    }
780    bool ShouldCheckConstantCond = HasConstantCond;
781
782    // Sort all the scalar case values so we can easily detect duplicates.
783    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
784
785    if (!CaseVals.empty()) {
786      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
787        if (ShouldCheckConstantCond &&
788            CaseVals[i].first == ConstantCondValue)
789          ShouldCheckConstantCond = false;
790
791        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
792          // If we have a duplicate, report it.
793          // First, determine if either case value has a name
794          StringRef PrevString, CurrString;
795          Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
796          Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
797          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
798            PrevString = DeclRef->getDecl()->getName();
799          }
800          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
801            CurrString = DeclRef->getDecl()->getName();
802          }
803          llvm::SmallString<16> CaseValStr;
804          CaseVals[i-1].first.toString(CaseValStr);
805
806          if (PrevString == CurrString)
807            Diag(CaseVals[i].second->getLHS()->getLocStart(),
808                 diag::err_duplicate_case) <<
809                 (PrevString.empty() ? CaseValStr.str() : PrevString);
810          else
811            Diag(CaseVals[i].second->getLHS()->getLocStart(),
812                 diag::err_duplicate_case_differing_expr) <<
813                 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
814                 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
815                 CaseValStr;
816
817          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
818               diag::note_duplicate_case_prev);
819          // FIXME: We really want to remove the bogus case stmt from the
820          // substmt, but we have no way to do this right now.
821          CaseListIsErroneous = true;
822        }
823      }
824    }
825
826    // Detect duplicate case ranges, which usually don't exist at all in
827    // the first place.
828    if (!CaseRanges.empty()) {
829      // Sort all the case ranges by their low value so we can easily detect
830      // overlaps between ranges.
831      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
832
833      // Scan the ranges, computing the high values and removing empty ranges.
834      std::vector<llvm::APSInt> HiVals;
835      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
836        llvm::APSInt &LoVal = CaseRanges[i].first;
837        CaseStmt *CR = CaseRanges[i].second;
838        Expr *Hi = CR->getRHS();
839        llvm::APSInt HiVal;
840
841        if (getLangOpts().CPlusPlus0x) {
842          // C++11 [stmt.switch]p2: the constant-expression shall be a converted
843          // constant expression of the promoted type of the switch condition.
844          ExprResult ConvHi =
845            CheckConvertedConstantExpression(Hi, CondType, HiVal,
846                                             CCEK_CaseValue);
847          if (ConvHi.isInvalid()) {
848            CaseListIsErroneous = true;
849            continue;
850          }
851          Hi = ConvHi.take();
852        } else {
853          HiVal = Hi->EvaluateKnownConstInt(Context);
854
855          // If the RHS is not the same type as the condition, insert an
856          // implicit cast.
857          Hi = DefaultLvalueConversion(Hi).take();
858          Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
859        }
860
861        // Convert the value to the same width/sign as the condition.
862        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
863                                           Hi->getLocStart(),
864                                           diag::warn_case_value_overflow);
865
866        CR->setRHS(Hi);
867
868        // If the low value is bigger than the high value, the case is empty.
869        if (LoVal > HiVal) {
870          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
871            << SourceRange(CR->getLHS()->getLocStart(),
872                           Hi->getLocEnd());
873          CaseRanges.erase(CaseRanges.begin()+i);
874          --i, --e;
875          continue;
876        }
877
878        if (ShouldCheckConstantCond &&
879            LoVal <= ConstantCondValue &&
880            ConstantCondValue <= HiVal)
881          ShouldCheckConstantCond = false;
882
883        HiVals.push_back(HiVal);
884      }
885
886      // Rescan the ranges, looking for overlap with singleton values and other
887      // ranges.  Since the range list is sorted, we only need to compare case
888      // ranges with their neighbors.
889      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
890        llvm::APSInt &CRLo = CaseRanges[i].first;
891        llvm::APSInt &CRHi = HiVals[i];
892        CaseStmt *CR = CaseRanges[i].second;
893
894        // Check to see whether the case range overlaps with any
895        // singleton cases.
896        CaseStmt *OverlapStmt = 0;
897        llvm::APSInt OverlapVal(32);
898
899        // Find the smallest value >= the lower bound.  If I is in the
900        // case range, then we have overlap.
901        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
902                                                  CaseVals.end(), CRLo,
903                                                  CaseCompareFunctor());
904        if (I != CaseVals.end() && I->first < CRHi) {
905          OverlapVal  = I->first;   // Found overlap with scalar.
906          OverlapStmt = I->second;
907        }
908
909        // Find the smallest value bigger than the upper bound.
910        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
911        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
912          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
913          OverlapStmt = (I-1)->second;
914        }
915
916        // Check to see if this case stmt overlaps with the subsequent
917        // case range.
918        if (i && CRLo <= HiVals[i-1]) {
919          OverlapVal  = HiVals[i-1];       // Found overlap with range.
920          OverlapStmt = CaseRanges[i-1].second;
921        }
922
923        if (OverlapStmt) {
924          // If we have a duplicate, report it.
925          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
926            << OverlapVal.toString(10);
927          Diag(OverlapStmt->getLHS()->getLocStart(),
928               diag::note_duplicate_case_prev);
929          // FIXME: We really want to remove the bogus case stmt from the
930          // substmt, but we have no way to do this right now.
931          CaseListIsErroneous = true;
932        }
933      }
934    }
935
936    // Complain if we have a constant condition and we didn't find a match.
937    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
938      // TODO: it would be nice if we printed enums as enums, chars as
939      // chars, etc.
940      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
941        << ConstantCondValue.toString(10)
942        << CondExpr->getSourceRange();
943    }
944
945    // Check to see if switch is over an Enum and handles all of its
946    // values.  We only issue a warning if there is not 'default:', but
947    // we still do the analysis to preserve this information in the AST
948    // (which can be used by flow-based analyes).
949    //
950    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
951
952    // If switch has default case, then ignore it.
953    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
954      const EnumDecl *ED = ET->getDecl();
955      typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
956        EnumValsTy;
957      EnumValsTy EnumVals;
958
959      // Gather all enum values, set their type and sort them,
960      // allowing easier comparison with CaseVals.
961      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
962           EDI != ED->enumerator_end(); ++EDI) {
963        llvm::APSInt Val = EDI->getInitVal();
964        AdjustAPSInt(Val, CondWidth, CondIsSigned);
965        EnumVals.push_back(std::make_pair(Val, *EDI));
966      }
967      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
968      EnumValsTy::iterator EIend =
969        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
970
971      // See which case values aren't in enum.
972      EnumValsTy::const_iterator EI = EnumVals.begin();
973      for (CaseValsTy::const_iterator CI = CaseVals.begin();
974           CI != CaseVals.end(); CI++) {
975        while (EI != EIend && EI->first < CI->first)
976          EI++;
977        if (EI == EIend || EI->first > CI->first)
978          Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
979            << CondTypeBeforePromotion;
980      }
981      // See which of case ranges aren't in enum
982      EI = EnumVals.begin();
983      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
984           RI != CaseRanges.end() && EI != EIend; RI++) {
985        while (EI != EIend && EI->first < RI->first)
986          EI++;
987
988        if (EI == EIend || EI->first != RI->first) {
989          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
990            << CondTypeBeforePromotion;
991        }
992
993        llvm::APSInt Hi =
994          RI->second->getRHS()->EvaluateKnownConstInt(Context);
995        AdjustAPSInt(Hi, CondWidth, CondIsSigned);
996        while (EI != EIend && EI->first < Hi)
997          EI++;
998        if (EI == EIend || EI->first != Hi)
999          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
1000            << CondTypeBeforePromotion;
1001      }
1002
1003      // Check which enum vals aren't in switch
1004      CaseValsTy::const_iterator CI = CaseVals.begin();
1005      CaseRangesTy::const_iterator RI = CaseRanges.begin();
1006      bool hasCasesNotInSwitch = false;
1007
1008      SmallVector<DeclarationName,8> UnhandledNames;
1009
1010      for (EI = EnumVals.begin(); EI != EIend; EI++){
1011        // Drop unneeded case values
1012        llvm::APSInt CIVal;
1013        while (CI != CaseVals.end() && CI->first < EI->first)
1014          CI++;
1015
1016        if (CI != CaseVals.end() && CI->first == EI->first)
1017          continue;
1018
1019        // Drop unneeded case ranges
1020        for (; RI != CaseRanges.end(); RI++) {
1021          llvm::APSInt Hi =
1022            RI->second->getRHS()->EvaluateKnownConstInt(Context);
1023          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1024          if (EI->first <= Hi)
1025            break;
1026        }
1027
1028        if (RI == CaseRanges.end() || EI->first < RI->first) {
1029          hasCasesNotInSwitch = true;
1030          UnhandledNames.push_back(EI->second->getDeclName());
1031        }
1032      }
1033
1034      if (TheDefaultStmt && UnhandledNames.empty())
1035        Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1036
1037      // Produce a nice diagnostic if multiple values aren't handled.
1038      switch (UnhandledNames.size()) {
1039      case 0: break;
1040      case 1:
1041        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1042          ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1043          << UnhandledNames[0];
1044        break;
1045      case 2:
1046        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1047          ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1048          << UnhandledNames[0] << UnhandledNames[1];
1049        break;
1050      case 3:
1051        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1052          ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1053          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1054        break;
1055      default:
1056        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1057          ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1058          << (unsigned)UnhandledNames.size()
1059          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1060        break;
1061      }
1062
1063      if (!hasCasesNotInSwitch)
1064        SS->setAllEnumCasesCovered();
1065    }
1066  }
1067
1068  DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1069                        diag::warn_empty_switch_body);
1070
1071  // FIXME: If the case list was broken is some way, we don't have a good system
1072  // to patch it up.  Instead, just return the whole substmt as broken.
1073  if (CaseListIsErroneous)
1074    return StmtError();
1075
1076  return Owned(SS);
1077}
1078
1079void
1080Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1081                             Expr *SrcExpr) {
1082  unsigned DIAG = diag::warn_not_in_enum_assignement;
1083  if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1084      == DiagnosticsEngine::Ignored)
1085    return;
1086
1087  if (const EnumType *ET = DstType->getAs<EnumType>())
1088    if (!Context.hasSameType(SrcType, DstType) &&
1089        SrcType->isIntegerType()) {
1090      if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1091          SrcExpr->isIntegerConstantExpr(Context)) {
1092        // Get the bitwidth of the enum value before promotions.
1093        unsigned DstWith = Context.getIntWidth(DstType);
1094        bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1095
1096        llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1097        const EnumDecl *ED = ET->getDecl();
1098        typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1099        EnumValsTy;
1100        EnumValsTy EnumVals;
1101
1102        // Gather all enum values, set their type and sort them,
1103        // allowing easier comparison with rhs constant.
1104        for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1105             EDI != ED->enumerator_end(); ++EDI) {
1106          llvm::APSInt Val = EDI->getInitVal();
1107          AdjustAPSInt(Val, DstWith, DstIsSigned);
1108          EnumVals.push_back(std::make_pair(Val, *EDI));
1109        }
1110        if (EnumVals.empty())
1111          return;
1112        std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1113        EnumValsTy::iterator EIend =
1114        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1115
1116        // See which case values aren't in enum.
1117        EnumValsTy::const_iterator EI = EnumVals.begin();
1118        while (EI != EIend && EI->first < RhsVal)
1119          EI++;
1120        if (EI == EIend || EI->first != RhsVal) {
1121          Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1122          << DstType;
1123        }
1124      }
1125    }
1126}
1127
1128StmtResult
1129Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1130                     Decl *CondVar, Stmt *Body) {
1131  ExprResult CondResult(Cond.release());
1132
1133  VarDecl *ConditionVar = 0;
1134  if (CondVar) {
1135    ConditionVar = cast<VarDecl>(CondVar);
1136    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1137    if (CondResult.isInvalid())
1138      return StmtError();
1139  }
1140  Expr *ConditionExpr = CondResult.take();
1141  if (!ConditionExpr)
1142    return StmtError();
1143
1144  DiagnoseUnusedExprResult(Body);
1145
1146  if (isa<NullStmt>(Body))
1147    getCurCompoundScope().setHasEmptyLoopBodies();
1148
1149  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
1150                                       Body, WhileLoc));
1151}
1152
1153StmtResult
1154Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1155                  SourceLocation WhileLoc, SourceLocation CondLParen,
1156                  Expr *Cond, SourceLocation CondRParen) {
1157  assert(Cond && "ActOnDoStmt(): missing expression");
1158
1159  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1160  if (CondResult.isInvalid() || CondResult.isInvalid())
1161    return StmtError();
1162  Cond = CondResult.take();
1163
1164  CheckImplicitConversions(Cond, DoLoc);
1165  CondResult = MaybeCreateExprWithCleanups(Cond);
1166  if (CondResult.isInvalid())
1167    return StmtError();
1168  Cond = CondResult.take();
1169
1170  DiagnoseUnusedExprResult(Body);
1171
1172  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
1173}
1174
1175namespace {
1176  // This visitor will traverse a conditional statement and store all
1177  // the evaluated decls into a vector.  Simple is set to true if none
1178  // of the excluded constructs are used.
1179  class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1180    llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1181    llvm::SmallVector<SourceRange, 10> &Ranges;
1182    bool Simple;
1183public:
1184  typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1185
1186  DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1187                llvm::SmallVector<SourceRange, 10> &Ranges) :
1188      Inherited(S.Context),
1189      Decls(Decls),
1190      Ranges(Ranges),
1191      Simple(true) {}
1192
1193  bool isSimple() { return Simple; }
1194
1195  // Replaces the method in EvaluatedExprVisitor.
1196  void VisitMemberExpr(MemberExpr* E) {
1197    Simple = false;
1198  }
1199
1200  // Any Stmt not whitelisted will cause the condition to be marked complex.
1201  void VisitStmt(Stmt *S) {
1202    Simple = false;
1203  }
1204
1205  void VisitBinaryOperator(BinaryOperator *E) {
1206    Visit(E->getLHS());
1207    Visit(E->getRHS());
1208  }
1209
1210  void VisitCastExpr(CastExpr *E) {
1211    Visit(E->getSubExpr());
1212  }
1213
1214  void VisitUnaryOperator(UnaryOperator *E) {
1215    // Skip checking conditionals with derefernces.
1216    if (E->getOpcode() == UO_Deref)
1217      Simple = false;
1218    else
1219      Visit(E->getSubExpr());
1220  }
1221
1222  void VisitConditionalOperator(ConditionalOperator *E) {
1223    Visit(E->getCond());
1224    Visit(E->getTrueExpr());
1225    Visit(E->getFalseExpr());
1226  }
1227
1228  void VisitParenExpr(ParenExpr *E) {
1229    Visit(E->getSubExpr());
1230  }
1231
1232  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1233    Visit(E->getOpaqueValue()->getSourceExpr());
1234    Visit(E->getFalseExpr());
1235  }
1236
1237  void VisitIntegerLiteral(IntegerLiteral *E) { }
1238  void VisitFloatingLiteral(FloatingLiteral *E) { }
1239  void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1240  void VisitCharacterLiteral(CharacterLiteral *E) { }
1241  void VisitGNUNullExpr(GNUNullExpr *E) { }
1242  void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1243
1244  void VisitDeclRefExpr(DeclRefExpr *E) {
1245    VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1246    if (!VD) return;
1247
1248    Ranges.push_back(E->getSourceRange());
1249
1250    Decls.insert(VD);
1251  }
1252
1253  }; // end class DeclExtractor
1254
1255  // DeclMatcher checks to see if the decls are used in a non-evauluated
1256  // context.
1257  class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1258    llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1259    bool FoundDecl;
1260
1261public:
1262  typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1263
1264  DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1265      Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1266    if (!Statement) return;
1267
1268    Visit(Statement);
1269  }
1270
1271  void VisitReturnStmt(ReturnStmt *S) {
1272    FoundDecl = true;
1273  }
1274
1275  void VisitBreakStmt(BreakStmt *S) {
1276    FoundDecl = true;
1277  }
1278
1279  void VisitGotoStmt(GotoStmt *S) {
1280    FoundDecl = true;
1281  }
1282
1283  void VisitCastExpr(CastExpr *E) {
1284    if (E->getCastKind() == CK_LValueToRValue)
1285      CheckLValueToRValueCast(E->getSubExpr());
1286    else
1287      Visit(E->getSubExpr());
1288  }
1289
1290  void CheckLValueToRValueCast(Expr *E) {
1291    E = E->IgnoreParenImpCasts();
1292
1293    if (isa<DeclRefExpr>(E)) {
1294      return;
1295    }
1296
1297    if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1298      Visit(CO->getCond());
1299      CheckLValueToRValueCast(CO->getTrueExpr());
1300      CheckLValueToRValueCast(CO->getFalseExpr());
1301      return;
1302    }
1303
1304    if (BinaryConditionalOperator *BCO =
1305            dyn_cast<BinaryConditionalOperator>(E)) {
1306      CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1307      CheckLValueToRValueCast(BCO->getFalseExpr());
1308      return;
1309    }
1310
1311    Visit(E);
1312  }
1313
1314  void VisitDeclRefExpr(DeclRefExpr *E) {
1315    if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1316      if (Decls.count(VD))
1317        FoundDecl = true;
1318  }
1319
1320  bool FoundDeclInUse() { return FoundDecl; }
1321
1322  };  // end class DeclMatcher
1323
1324  void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1325                                        Expr *Third, Stmt *Body) {
1326    // Condition is empty
1327    if (!Second) return;
1328
1329    if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1330                                   Second->getLocStart())
1331        == DiagnosticsEngine::Ignored)
1332      return;
1333
1334    PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1335    llvm::SmallPtrSet<VarDecl*, 8> Decls;
1336    llvm::SmallVector<SourceRange, 10> Ranges;
1337    DeclExtractor DE(S, Decls, Ranges);
1338    DE.Visit(Second);
1339
1340    // Don't analyze complex conditionals.
1341    if (!DE.isSimple()) return;
1342
1343    // No decls found.
1344    if (Decls.size() == 0) return;
1345
1346    // Don't warn on volatile, static, or global variables.
1347    for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1348                                                  E = Decls.end();
1349         I != E; ++I)
1350      if ((*I)->getType().isVolatileQualified() ||
1351          (*I)->hasGlobalStorage()) return;
1352
1353    if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1354        DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1355        DeclMatcher(S, Decls, Body).FoundDeclInUse())
1356      return;
1357
1358    // Load decl names into diagnostic.
1359    if (Decls.size() > 4)
1360      PDiag << 0;
1361    else {
1362      PDiag << Decls.size();
1363      for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1364                                                    E = Decls.end();
1365           I != E; ++I)
1366        PDiag << (*I)->getDeclName();
1367    }
1368
1369    // Load SourceRanges into diagnostic if there is room.
1370    // Otherwise, load the SourceRange of the conditional expression.
1371    if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1372      for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1373                                                        E = Ranges.end();
1374           I != E; ++I)
1375        PDiag << *I;
1376    else
1377      PDiag << Second->getSourceRange();
1378
1379    S.Diag(Ranges.begin()->getBegin(), PDiag);
1380  }
1381
1382} // end namespace
1383
1384StmtResult
1385Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1386                   Stmt *First, FullExprArg second, Decl *secondVar,
1387                   FullExprArg third,
1388                   SourceLocation RParenLoc, Stmt *Body) {
1389  if (!getLangOpts().CPlusPlus) {
1390    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1391      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1392      // declare identifiers for objects having storage class 'auto' or
1393      // 'register'.
1394      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1395           DI!=DE; ++DI) {
1396        VarDecl *VD = dyn_cast<VarDecl>(*DI);
1397        if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1398          VD = 0;
1399        if (VD == 0)
1400          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1401        // FIXME: mark decl erroneous!
1402      }
1403    }
1404  }
1405
1406  CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1407
1408  ExprResult SecondResult(second.release());
1409  VarDecl *ConditionVar = 0;
1410  if (secondVar) {
1411    ConditionVar = cast<VarDecl>(secondVar);
1412    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1413    if (SecondResult.isInvalid())
1414      return StmtError();
1415  }
1416
1417  Expr *Third  = third.release().takeAs<Expr>();
1418
1419  DiagnoseUnusedExprResult(First);
1420  DiagnoseUnusedExprResult(Third);
1421  DiagnoseUnusedExprResult(Body);
1422
1423  if (isa<NullStmt>(Body))
1424    getCurCompoundScope().setHasEmptyLoopBodies();
1425
1426  return Owned(new (Context) ForStmt(Context, First,
1427                                     SecondResult.take(), ConditionVar,
1428                                     Third, Body, ForLoc, LParenLoc,
1429                                     RParenLoc));
1430}
1431
1432/// In an Objective C collection iteration statement:
1433///   for (x in y)
1434/// x can be an arbitrary l-value expression.  Bind it up as a
1435/// full-expression.
1436StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1437  // Reduce placeholder expressions here.  Note that this rejects the
1438  // use of pseudo-object l-values in this position.
1439  ExprResult result = CheckPlaceholderExpr(E);
1440  if (result.isInvalid()) return StmtError();
1441  E = result.take();
1442
1443  CheckImplicitConversions(E);
1444
1445  result = MaybeCreateExprWithCleanups(E);
1446  if (result.isInvalid()) return StmtError();
1447
1448  return Owned(static_cast<Stmt*>(result.take()));
1449}
1450
1451ExprResult
1452Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1453  if (!collection)
1454    return ExprError();
1455
1456  // Bail out early if we've got a type-dependent expression.
1457  if (collection->isTypeDependent()) return Owned(collection);
1458
1459  // Perform normal l-value conversion.
1460  ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1461  if (result.isInvalid())
1462    return ExprError();
1463  collection = result.take();
1464
1465  // The operand needs to have object-pointer type.
1466  // TODO: should we do a contextual conversion?
1467  const ObjCObjectPointerType *pointerType =
1468    collection->getType()->getAs<ObjCObjectPointerType>();
1469  if (!pointerType)
1470    return Diag(forLoc, diag::err_collection_expr_type)
1471             << collection->getType() << collection->getSourceRange();
1472
1473  // Check that the operand provides
1474  //   - countByEnumeratingWithState:objects:count:
1475  const ObjCObjectType *objectType = pointerType->getObjectType();
1476  ObjCInterfaceDecl *iface = objectType->getInterface();
1477
1478  // If we have a forward-declared type, we can't do this check.
1479  // Under ARC, it is an error not to have a forward-declared class.
1480  if (iface &&
1481      RequireCompleteType(forLoc, QualType(objectType, 0),
1482                          getLangOpts().ObjCAutoRefCount
1483                            ? diag::err_arc_collection_forward
1484                            : 0,
1485                          collection)) {
1486    // Otherwise, if we have any useful type information, check that
1487    // the type declares the appropriate method.
1488  } else if (iface || !objectType->qual_empty()) {
1489    IdentifierInfo *selectorIdents[] = {
1490      &Context.Idents.get("countByEnumeratingWithState"),
1491      &Context.Idents.get("objects"),
1492      &Context.Idents.get("count")
1493    };
1494    Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1495
1496    ObjCMethodDecl *method = 0;
1497
1498    // If there's an interface, look in both the public and private APIs.
1499    if (iface) {
1500      method = iface->lookupInstanceMethod(selector);
1501      if (!method) method = iface->lookupPrivateMethod(selector);
1502    }
1503
1504    // Also check protocol qualifiers.
1505    if (!method)
1506      method = LookupMethodInQualifiedType(selector, pointerType,
1507                                           /*instance*/ true);
1508
1509    // If we didn't find it anywhere, give up.
1510    if (!method) {
1511      Diag(forLoc, diag::warn_collection_expr_type)
1512        << collection->getType() << selector << collection->getSourceRange();
1513    }
1514
1515    // TODO: check for an incompatible signature?
1516  }
1517
1518  // Wrap up any cleanups in the expression.
1519  return Owned(MaybeCreateExprWithCleanups(collection));
1520}
1521
1522StmtResult
1523Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1524                                 Stmt *First, Expr *collection,
1525                                 SourceLocation RParenLoc) {
1526
1527  ExprResult CollectionExprResult =
1528    CheckObjCForCollectionOperand(ForLoc, collection);
1529
1530  if (First) {
1531    QualType FirstType;
1532    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1533      if (!DS->isSingleDecl())
1534        return StmtError(Diag((*DS->decl_begin())->getLocation(),
1535                         diag::err_toomany_element_decls));
1536
1537      VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1538      FirstType = D->getType();
1539      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1540      // declare identifiers for objects having storage class 'auto' or
1541      // 'register'.
1542      if (!D->hasLocalStorage())
1543        return StmtError(Diag(D->getLocation(),
1544                              diag::err_non_variable_decl_in_for));
1545    } else {
1546      Expr *FirstE = cast<Expr>(First);
1547      if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1548        return StmtError(Diag(First->getLocStart(),
1549                   diag::err_selector_element_not_lvalue)
1550          << First->getSourceRange());
1551
1552      FirstType = static_cast<Expr*>(First)->getType();
1553    }
1554    if (!FirstType->isDependentType() &&
1555        !FirstType->isObjCObjectPointerType() &&
1556        !FirstType->isBlockPointerType())
1557        return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1558                           << FirstType << First->getSourceRange());
1559  }
1560
1561  if (CollectionExprResult.isInvalid())
1562    return StmtError();
1563
1564  return Owned(new (Context) ObjCForCollectionStmt(First,
1565                                                   CollectionExprResult.take(), 0,
1566                                                   ForLoc, RParenLoc));
1567}
1568
1569namespace {
1570
1571enum BeginEndFunction {
1572  BEF_begin,
1573  BEF_end
1574};
1575
1576/// Build a variable declaration for a for-range statement.
1577static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1578                                     QualType Type, const char *Name) {
1579  DeclContext *DC = SemaRef.CurContext;
1580  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1581  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1582  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1583                                  TInfo, SC_Auto, SC_None);
1584  Decl->setImplicit();
1585  return Decl;
1586}
1587
1588/// Finish building a variable declaration for a for-range statement.
1589/// \return true if an error occurs.
1590static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1591                                  SourceLocation Loc, int diag) {
1592  // Deduce the type for the iterator variable now rather than leaving it to
1593  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1594  TypeSourceInfo *InitTSI = 0;
1595  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1596      SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1597          Sema::DAR_Failed)
1598    SemaRef.Diag(Loc, diag) << Init->getType();
1599  if (!InitTSI) {
1600    Decl->setInvalidDecl();
1601    return true;
1602  }
1603  Decl->setTypeSourceInfo(InitTSI);
1604  Decl->setType(InitTSI->getType());
1605
1606  // In ARC, infer lifetime.
1607  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1608  // we're doing the equivalent of fast iteration.
1609  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1610      SemaRef.inferObjCARCLifetime(Decl))
1611    Decl->setInvalidDecl();
1612
1613  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1614                               /*TypeMayContainAuto=*/false);
1615  SemaRef.FinalizeDeclaration(Decl);
1616  SemaRef.CurContext->addHiddenDecl(Decl);
1617  return false;
1618}
1619
1620/// Produce a note indicating which begin/end function was implicitly called
1621/// by a C++0x for-range statement. This is often not obvious from the code,
1622/// nor from the diagnostics produced when analysing the implicit expressions
1623/// required in a for-range statement.
1624void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1625                                  BeginEndFunction BEF) {
1626  CallExpr *CE = dyn_cast<CallExpr>(E);
1627  if (!CE)
1628    return;
1629  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1630  if (!D)
1631    return;
1632  SourceLocation Loc = D->getLocation();
1633
1634  std::string Description;
1635  bool IsTemplate = false;
1636  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1637    Description = SemaRef.getTemplateArgumentBindingsText(
1638      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1639    IsTemplate = true;
1640  }
1641
1642  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1643    << BEF << IsTemplate << Description << E->getType();
1644}
1645
1646/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1647/// given LookupResult is non-empty, it is assumed to describe a member which
1648/// will be invoked. Otherwise, the function will be found via argument
1649/// dependent lookup.
1650static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1651                                            SourceLocation Loc,
1652                                            VarDecl *Decl,
1653                                            BeginEndFunction BEF,
1654                                            const DeclarationNameInfo &NameInfo,
1655                                            LookupResult &MemberLookup,
1656                                            Expr *Range) {
1657  ExprResult CallExpr;
1658  if (!MemberLookup.empty()) {
1659    ExprResult MemberRef =
1660      SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1661                                       /*IsPtr=*/false, CXXScopeSpec(),
1662                                       /*TemplateKWLoc=*/SourceLocation(),
1663                                       /*FirstQualifierInScope=*/0,
1664                                       MemberLookup,
1665                                       /*TemplateArgs=*/0);
1666    if (MemberRef.isInvalid())
1667      return ExprError();
1668    CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1669                                     Loc, 0);
1670    if (CallExpr.isInvalid())
1671      return ExprError();
1672  } else {
1673    UnresolvedSet<0> FoundNames;
1674    // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1675    // std is an associated namespace.
1676    UnresolvedLookupExpr *Fn =
1677      UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1678                                   NestedNameSpecifierLoc(), NameInfo,
1679                                   /*NeedsADL=*/true, /*Overloaded=*/false,
1680                                   FoundNames.begin(), FoundNames.end(),
1681                                   /*LookInStdNamespace=*/true);
1682    CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1683                                               0, /*AllowTypoCorrection=*/false);
1684    if (CallExpr.isInvalid()) {
1685      SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1686        << Range->getType();
1687      return ExprError();
1688    }
1689  }
1690  if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1691                            diag::err_for_range_iter_deduction_failure)) {
1692    NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1693    return ExprError();
1694  }
1695  return CallExpr;
1696}
1697
1698}
1699
1700static bool ObjCEnumerationCollection(Expr *Collection) {
1701  return !Collection->isTypeDependent()
1702          && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1703}
1704
1705/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1706///
1707/// C++11 [stmt.ranged]:
1708///   A range-based for statement is equivalent to
1709///
1710///   {
1711///     auto && __range = range-init;
1712///     for ( auto __begin = begin-expr,
1713///           __end = end-expr;
1714///           __begin != __end;
1715///           ++__begin ) {
1716///       for-range-declaration = *__begin;
1717///       statement
1718///     }
1719///   }
1720///
1721/// The body of the loop is not available yet, since it cannot be analysed until
1722/// we have determined the type of the for-range-declaration.
1723StmtResult
1724Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1725                           Stmt *First, SourceLocation ColonLoc, Expr *Range,
1726                           SourceLocation RParenLoc) {
1727  if (!First || !Range)
1728    return StmtError();
1729
1730  if (ObjCEnumerationCollection(Range))
1731    return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1732
1733  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1734  assert(DS && "first part of for range not a decl stmt");
1735
1736  if (!DS->isSingleDecl()) {
1737    Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1738    return StmtError();
1739  }
1740  if (DS->getSingleDecl()->isInvalidDecl())
1741    return StmtError();
1742
1743  if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1744    return StmtError();
1745
1746  // Build  auto && __range = range-init
1747  SourceLocation RangeLoc = Range->getLocStart();
1748  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1749                                           Context.getAutoRRefDeductType(),
1750                                           "__range");
1751  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1752                            diag::err_for_range_deduction_failure))
1753    return StmtError();
1754
1755  // Claim the type doesn't contain auto: we've already done the checking.
1756  DeclGroupPtrTy RangeGroup =
1757    BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1758  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1759  if (RangeDecl.isInvalid())
1760    return StmtError();
1761
1762  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1763                              /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1764                              RParenLoc);
1765}
1766
1767/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1768StmtResult
1769Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1770                           Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1771                           Expr *Inc, Stmt *LoopVarDecl,
1772                           SourceLocation RParenLoc) {
1773  Scope *S = getCurScope();
1774
1775  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1776  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1777  QualType RangeVarType = RangeVar->getType();
1778
1779  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1780  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1781
1782  StmtResult BeginEndDecl = BeginEnd;
1783  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1784
1785  if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1786    SourceLocation RangeLoc = RangeVar->getLocation();
1787
1788    const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1789
1790    ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1791                                                VK_LValue, ColonLoc);
1792    if (BeginRangeRef.isInvalid())
1793      return StmtError();
1794
1795    ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1796                                              VK_LValue, ColonLoc);
1797    if (EndRangeRef.isInvalid())
1798      return StmtError();
1799
1800    QualType AutoType = Context.getAutoDeductType();
1801    Expr *Range = RangeVar->getInit();
1802    if (!Range)
1803      return StmtError();
1804    QualType RangeType = Range->getType();
1805
1806    if (RequireCompleteType(RangeLoc, RangeType,
1807                            diag::err_for_range_incomplete_type))
1808      return StmtError();
1809
1810    // Build auto __begin = begin-expr, __end = end-expr.
1811    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1812                                             "__begin");
1813    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1814                                           "__end");
1815
1816    // Build begin-expr and end-expr and attach to __begin and __end variables.
1817    ExprResult BeginExpr, EndExpr;
1818    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1819      // - if _RangeT is an array type, begin-expr and end-expr are __range and
1820      //   __range + __bound, respectively, where __bound is the array bound. If
1821      //   _RangeT is an array of unknown size or an array of incomplete type,
1822      //   the program is ill-formed;
1823
1824      // begin-expr is __range.
1825      BeginExpr = BeginRangeRef;
1826      if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1827                                diag::err_for_range_iter_deduction_failure)) {
1828        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1829        return StmtError();
1830      }
1831
1832      // Find the array bound.
1833      ExprResult BoundExpr;
1834      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1835        BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1836                                                 Context.getPointerDiffType(),
1837                                                 RangeLoc));
1838      else if (const VariableArrayType *VAT =
1839               dyn_cast<VariableArrayType>(UnqAT))
1840        BoundExpr = VAT->getSizeExpr();
1841      else {
1842        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1843        // UnqAT is not incomplete and Range is not type-dependent.
1844        llvm_unreachable("Unexpected array type in for-range");
1845      }
1846
1847      // end-expr is __range + __bound.
1848      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1849                           BoundExpr.get());
1850      if (EndExpr.isInvalid())
1851        return StmtError();
1852      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1853                                diag::err_for_range_iter_deduction_failure)) {
1854        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1855        return StmtError();
1856      }
1857    } else {
1858      DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1859                                        ColonLoc);
1860      DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1861                                      ColonLoc);
1862
1863      LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1864      LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1865
1866      if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1867        // - if _RangeT is a class type, the unqualified-ids begin and end are
1868        //   looked up in the scope of class _RangeT as if by class member access
1869        //   lookup (3.4.5), and if either (or both) finds at least one
1870        //   declaration, begin-expr and end-expr are __range.begin() and
1871        //   __range.end(), respectively;
1872        LookupQualifiedName(BeginMemberLookup, D);
1873        LookupQualifiedName(EndMemberLookup, D);
1874
1875        if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1876          Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1877            << RangeType << BeginMemberLookup.empty();
1878          return StmtError();
1879        }
1880      } else {
1881        // - otherwise, begin-expr and end-expr are begin(__range) and
1882        //   end(__range), respectively, where begin and end are looked up with
1883        //   argument-dependent lookup (3.4.2). For the purposes of this name
1884        //   lookup, namespace std is an associated namespace.
1885      }
1886
1887      BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1888                                            BEF_begin, BeginNameInfo,
1889                                            BeginMemberLookup,
1890                                            BeginRangeRef.get());
1891      if (BeginExpr.isInvalid())
1892        return StmtError();
1893
1894      EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1895                                          BEF_end, EndNameInfo,
1896                                          EndMemberLookup, EndRangeRef.get());
1897      if (EndExpr.isInvalid())
1898        return StmtError();
1899    }
1900
1901    // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1902    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1903    if (!Context.hasSameType(BeginType, EndType)) {
1904      Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1905        << BeginType << EndType;
1906      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1907      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1908    }
1909
1910    Decl *BeginEndDecls[] = { BeginVar, EndVar };
1911    // Claim the type doesn't contain auto: we've already done the checking.
1912    DeclGroupPtrTy BeginEndGroup =
1913      BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1914    BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1915
1916    const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1917    ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1918                                           VK_LValue, ColonLoc);
1919    if (BeginRef.isInvalid())
1920      return StmtError();
1921
1922    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1923                                         VK_LValue, ColonLoc);
1924    if (EndRef.isInvalid())
1925      return StmtError();
1926
1927    // Build and check __begin != __end expression.
1928    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1929                           BeginRef.get(), EndRef.get());
1930    NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1931    NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1932    if (NotEqExpr.isInvalid()) {
1933      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1934      if (!Context.hasSameType(BeginType, EndType))
1935        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1936      return StmtError();
1937    }
1938
1939    // Build and check ++__begin expression.
1940    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1941                                VK_LValue, ColonLoc);
1942    if (BeginRef.isInvalid())
1943      return StmtError();
1944
1945    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1946    IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1947    if (IncrExpr.isInvalid()) {
1948      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1949      return StmtError();
1950    }
1951
1952    // Build and check *__begin  expression.
1953    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1954                                VK_LValue, ColonLoc);
1955    if (BeginRef.isInvalid())
1956      return StmtError();
1957
1958    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1959    if (DerefExpr.isInvalid()) {
1960      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1961      return StmtError();
1962    }
1963
1964    // Attach  *__begin  as initializer for VD.
1965    if (!LoopVar->isInvalidDecl()) {
1966      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1967                           /*TypeMayContainAuto=*/true);
1968      if (LoopVar->isInvalidDecl())
1969        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1970    }
1971  } else {
1972    // The range is implicitly used as a placeholder when it is dependent.
1973    RangeVar->setUsed();
1974  }
1975
1976  return Owned(new (Context) CXXForRangeStmt(RangeDS,
1977                                     cast_or_null<DeclStmt>(BeginEndDecl.get()),
1978                                             NotEqExpr.take(), IncrExpr.take(),
1979                                             LoopVarDS, /*Body=*/0, ForLoc,
1980                                             ColonLoc, RParenLoc));
1981}
1982
1983/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
1984/// statement.
1985StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1986  if (!S || !B)
1987    return StmtError();
1988  ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
1989
1990  ForStmt->setBody(B);
1991  return S;
1992}
1993
1994/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1995/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1996/// body cannot be performed until after the type of the range variable is
1997/// determined.
1998StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1999  if (!S || !B)
2000    return StmtError();
2001
2002  if (isa<ObjCForCollectionStmt>(S))
2003    return FinishObjCForCollectionStmt(S, B);
2004
2005  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2006  ForStmt->setBody(B);
2007
2008  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2009                        diag::warn_empty_range_based_for_body);
2010
2011  return S;
2012}
2013
2014StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2015                               SourceLocation LabelLoc,
2016                               LabelDecl *TheDecl) {
2017  getCurFunction()->setHasBranchIntoScope();
2018  TheDecl->setUsed();
2019  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
2020}
2021
2022StmtResult
2023Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2024                            Expr *E) {
2025  // Convert operand to void*
2026  if (!E->isTypeDependent()) {
2027    QualType ETy = E->getType();
2028    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2029    ExprResult ExprRes = Owned(E);
2030    AssignConvertType ConvTy =
2031      CheckSingleAssignmentConstraints(DestTy, ExprRes);
2032    if (ExprRes.isInvalid())
2033      return StmtError();
2034    E = ExprRes.take();
2035    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2036      return StmtError();
2037    E = MaybeCreateExprWithCleanups(E);
2038  }
2039
2040  getCurFunction()->setHasIndirectGoto();
2041
2042  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
2043}
2044
2045StmtResult
2046Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2047  Scope *S = CurScope->getContinueParent();
2048  if (!S) {
2049    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2050    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2051  }
2052
2053  return Owned(new (Context) ContinueStmt(ContinueLoc));
2054}
2055
2056StmtResult
2057Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2058  Scope *S = CurScope->getBreakParent();
2059  if (!S) {
2060    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2061    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2062  }
2063
2064  return Owned(new (Context) BreakStmt(BreakLoc));
2065}
2066
2067/// \brief Determine whether the given expression is a candidate for
2068/// copy elision in either a return statement or a throw expression.
2069///
2070/// \param ReturnType If we're determining the copy elision candidate for
2071/// a return statement, this is the return type of the function. If we're
2072/// determining the copy elision candidate for a throw expression, this will
2073/// be a NULL type.
2074///
2075/// \param E The expression being returned from the function or block, or
2076/// being thrown.
2077///
2078/// \param AllowFunctionParameter Whether we allow function parameters to
2079/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2080/// we re-use this logic to determine whether we should try to move as part of
2081/// a return or throw (which does allow function parameters).
2082///
2083/// \returns The NRVO candidate variable, if the return statement may use the
2084/// NRVO, or NULL if there is no such candidate.
2085const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2086                                             Expr *E,
2087                                             bool AllowFunctionParameter) {
2088  QualType ExprType = E->getType();
2089  // - in a return statement in a function with ...
2090  // ... a class return type ...
2091  if (!ReturnType.isNull()) {
2092    if (!ReturnType->isRecordType())
2093      return 0;
2094    // ... the same cv-unqualified type as the function return type ...
2095    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2096      return 0;
2097  }
2098
2099  // ... the expression is the name of a non-volatile automatic object
2100  // (other than a function or catch-clause parameter)) ...
2101  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2102  if (!DR || DR->refersToEnclosingLocal())
2103    return 0;
2104  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2105  if (!VD)
2106    return 0;
2107
2108  // ...object (other than a function or catch-clause parameter)...
2109  if (VD->getKind() != Decl::Var &&
2110      !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2111    return 0;
2112  if (VD->isExceptionVariable()) return 0;
2113
2114  // ...automatic...
2115  if (!VD->hasLocalStorage()) return 0;
2116
2117  // ...non-volatile...
2118  if (VD->getType().isVolatileQualified()) return 0;
2119  if (VD->getType()->isReferenceType()) return 0;
2120
2121  // __block variables can't be allocated in a way that permits NRVO.
2122  if (VD->hasAttr<BlocksAttr>()) return 0;
2123
2124  // Variables with higher required alignment than their type's ABI
2125  // alignment cannot use NRVO.
2126  if (VD->hasAttr<AlignedAttr>() &&
2127      Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2128    return 0;
2129
2130  return VD;
2131}
2132
2133/// \brief Perform the initialization of a potentially-movable value, which
2134/// is the result of return value.
2135///
2136/// This routine implements C++0x [class.copy]p33, which attempts to treat
2137/// returned lvalues as rvalues in certain cases (to prefer move construction),
2138/// then falls back to treating them as lvalues if that failed.
2139ExprResult
2140Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2141                                      const VarDecl *NRVOCandidate,
2142                                      QualType ResultType,
2143                                      Expr *Value,
2144                                      bool AllowNRVO) {
2145  // C++0x [class.copy]p33:
2146  //   When the criteria for elision of a copy operation are met or would
2147  //   be met save for the fact that the source object is a function
2148  //   parameter, and the object to be copied is designated by an lvalue,
2149  //   overload resolution to select the constructor for the copy is first
2150  //   performed as if the object were designated by an rvalue.
2151  ExprResult Res = ExprError();
2152  if (AllowNRVO &&
2153      (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2154    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2155                              Value->getType(), CK_NoOp, Value, VK_XValue);
2156
2157    Expr *InitExpr = &AsRvalue;
2158    InitializationKind Kind
2159      = InitializationKind::CreateCopy(Value->getLocStart(),
2160                                       Value->getLocStart());
2161    InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
2162
2163    //   [...] If overload resolution fails, or if the type of the first
2164    //   parameter of the selected constructor is not an rvalue reference
2165    //   to the object's type (possibly cv-qualified), overload resolution
2166    //   is performed again, considering the object as an lvalue.
2167    if (Seq) {
2168      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2169           StepEnd = Seq.step_end();
2170           Step != StepEnd; ++Step) {
2171        if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2172          continue;
2173
2174        CXXConstructorDecl *Constructor
2175        = cast<CXXConstructorDecl>(Step->Function.Function);
2176
2177        const RValueReferenceType *RRefType
2178          = Constructor->getParamDecl(0)->getType()
2179                                                 ->getAs<RValueReferenceType>();
2180
2181        // If we don't meet the criteria, break out now.
2182        if (!RRefType ||
2183            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2184                            Context.getTypeDeclType(Constructor->getParent())))
2185          break;
2186
2187        // Promote "AsRvalue" to the heap, since we now need this
2188        // expression node to persist.
2189        Value = ImplicitCastExpr::Create(Context, Value->getType(),
2190                                         CK_NoOp, Value, 0, VK_XValue);
2191
2192        // Complete type-checking the initialization of the return type
2193        // using the constructor we found.
2194        Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
2195      }
2196    }
2197  }
2198
2199  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2200  // above, or overload resolution failed. Either way, we need to try
2201  // (again) now with the return value expression as written.
2202  if (Res.isInvalid())
2203    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2204
2205  return Res;
2206}
2207
2208/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2209/// for capturing scopes.
2210///
2211StmtResult
2212Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2213  // If this is the first return we've seen, infer the return type.
2214  // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2215  // rules which allows multiple return statements.
2216  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2217  QualType FnRetType = CurCap->ReturnType;
2218
2219  // For blocks/lambdas with implicit return types, we check each return
2220  // statement individually, and deduce the common return type when the block
2221  // or lambda is completed.
2222  if (CurCap->HasImplicitReturnType) {
2223    if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2224      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2225      if (Result.isInvalid())
2226        return StmtError();
2227      RetValExp = Result.take();
2228
2229      if (!RetValExp->isTypeDependent())
2230        FnRetType = RetValExp->getType();
2231      else
2232        FnRetType = CurCap->ReturnType = Context.DependentTy;
2233    } else {
2234      if (RetValExp) {
2235        // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2236        // initializer list, because it is not an expression (even
2237        // though we represent it as one). We still deduce 'void'.
2238        Diag(ReturnLoc, diag::err_lambda_return_init_list)
2239          << RetValExp->getSourceRange();
2240      }
2241
2242      FnRetType = Context.VoidTy;
2243    }
2244
2245    // Although we'll properly infer the type of the block once it's completed,
2246    // make sure we provide a return type now for better error recovery.
2247    if (CurCap->ReturnType.isNull())
2248      CurCap->ReturnType = FnRetType;
2249  }
2250  assert(!FnRetType.isNull());
2251
2252  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2253    if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2254      Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2255      return StmtError();
2256    }
2257  } else {
2258    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2259    if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2260      Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2261      return StmtError();
2262    }
2263  }
2264
2265  // Otherwise, verify that this result type matches the previous one.  We are
2266  // pickier with blocks than for normal functions because we don't have GCC
2267  // compatibility to worry about here.
2268  const VarDecl *NRVOCandidate = 0;
2269  if (FnRetType->isDependentType()) {
2270    // Delay processing for now.  TODO: there are lots of dependent
2271    // types we can conclusively prove aren't void.
2272  } else if (FnRetType->isVoidType()) {
2273    if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2274        !(getLangOpts().CPlusPlus &&
2275          (RetValExp->isTypeDependent() ||
2276           RetValExp->getType()->isVoidType()))) {
2277      if (!getLangOpts().CPlusPlus &&
2278          RetValExp->getType()->isVoidType())
2279        Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2280      else {
2281        Diag(ReturnLoc, diag::err_return_block_has_expr);
2282        RetValExp = 0;
2283      }
2284    }
2285  } else if (!RetValExp) {
2286    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2287  } else if (!RetValExp->isTypeDependent()) {
2288    // we have a non-void block with an expression, continue checking
2289
2290    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2291    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2292    // function return.
2293
2294    // In C++ the return statement is handled via a copy initialization.
2295    // the C version of which boils down to CheckSingleAssignmentConstraints.
2296    NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2297    InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2298                                                                   FnRetType,
2299                                                          NRVOCandidate != 0);
2300    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2301                                                     FnRetType, RetValExp);
2302    if (Res.isInvalid()) {
2303      // FIXME: Cleanup temporaries here, anyway?
2304      return StmtError();
2305    }
2306    RetValExp = Res.take();
2307    CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2308  }
2309
2310  if (RetValExp) {
2311    CheckImplicitConversions(RetValExp, ReturnLoc);
2312    RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2313  }
2314  ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2315                                                NRVOCandidate);
2316
2317  // If we need to check for the named return value optimization,
2318  // or if we need to infer the return type,
2319  // save the return statement in our scope for later processing.
2320  if (CurCap->HasImplicitReturnType ||
2321      (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2322       !CurContext->isDependentContext()))
2323    FunctionScopes.back()->Returns.push_back(Result);
2324
2325  return Owned(Result);
2326}
2327
2328StmtResult
2329Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2330  // Check for unexpanded parameter packs.
2331  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2332    return StmtError();
2333
2334  if (isa<CapturingScopeInfo>(getCurFunction()))
2335    return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2336
2337  QualType FnRetType;
2338  QualType RelatedRetType;
2339  if (const FunctionDecl *FD = getCurFunctionDecl()) {
2340    FnRetType = FD->getResultType();
2341    if (FD->hasAttr<NoReturnAttr>() ||
2342        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
2343      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2344        << FD->getDeclName();
2345  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2346    FnRetType = MD->getResultType();
2347    if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2348      // In the implementation of a method with a related return type, the
2349      // type used to type-check the validity of return statements within the
2350      // method body is a pointer to the type of the class being implemented.
2351      RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2352      RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2353    }
2354  } else // If we don't have a function/method context, bail.
2355    return StmtError();
2356
2357  ReturnStmt *Result = 0;
2358  if (FnRetType->isVoidType()) {
2359    if (RetValExp) {
2360      if (isa<InitListExpr>(RetValExp)) {
2361        // We simply never allow init lists as the return value of void
2362        // functions. This is compatible because this was never allowed before,
2363        // so there's no legacy code to deal with.
2364        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2365        int FunctionKind = 0;
2366        if (isa<ObjCMethodDecl>(CurDecl))
2367          FunctionKind = 1;
2368        else if (isa<CXXConstructorDecl>(CurDecl))
2369          FunctionKind = 2;
2370        else if (isa<CXXDestructorDecl>(CurDecl))
2371          FunctionKind = 3;
2372
2373        Diag(ReturnLoc, diag::err_return_init_list)
2374          << CurDecl->getDeclName() << FunctionKind
2375          << RetValExp->getSourceRange();
2376
2377        // Drop the expression.
2378        RetValExp = 0;
2379      } else if (!RetValExp->isTypeDependent()) {
2380        // C99 6.8.6.4p1 (ext_ since GCC warns)
2381        unsigned D = diag::ext_return_has_expr;
2382        if (RetValExp->getType()->isVoidType())
2383          D = diag::ext_return_has_void_expr;
2384        else {
2385          ExprResult Result = Owned(RetValExp);
2386          Result = IgnoredValueConversions(Result.take());
2387          if (Result.isInvalid())
2388            return StmtError();
2389          RetValExp = Result.take();
2390          RetValExp = ImpCastExprToType(RetValExp,
2391                                        Context.VoidTy, CK_ToVoid).take();
2392        }
2393
2394        // return (some void expression); is legal in C++.
2395        if (D != diag::ext_return_has_void_expr ||
2396            !getLangOpts().CPlusPlus) {
2397          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2398
2399          int FunctionKind = 0;
2400          if (isa<ObjCMethodDecl>(CurDecl))
2401            FunctionKind = 1;
2402          else if (isa<CXXConstructorDecl>(CurDecl))
2403            FunctionKind = 2;
2404          else if (isa<CXXDestructorDecl>(CurDecl))
2405            FunctionKind = 3;
2406
2407          Diag(ReturnLoc, D)
2408            << CurDecl->getDeclName() << FunctionKind
2409            << RetValExp->getSourceRange();
2410        }
2411      }
2412
2413      if (RetValExp) {
2414        CheckImplicitConversions(RetValExp, ReturnLoc);
2415        RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2416      }
2417    }
2418
2419    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2420  } else if (!RetValExp && !FnRetType->isDependentType()) {
2421    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
2422    // C99 6.8.6.4p1 (ext_ since GCC warns)
2423    if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2424
2425    if (FunctionDecl *FD = getCurFunctionDecl())
2426      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2427    else
2428      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2429    Result = new (Context) ReturnStmt(ReturnLoc);
2430  } else {
2431    const VarDecl *NRVOCandidate = 0;
2432    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2433      // we have a non-void function with an expression, continue checking
2434
2435      if (!RelatedRetType.isNull()) {
2436        // If we have a related result type, perform an extra conversion here.
2437        // FIXME: The diagnostics here don't really describe what is happening.
2438        InitializedEntity Entity =
2439            InitializedEntity::InitializeTemporary(RelatedRetType);
2440
2441        ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2442                                                   RetValExp);
2443        if (Res.isInvalid()) {
2444          // FIXME: Cleanup temporaries here, anyway?
2445          return StmtError();
2446        }
2447        RetValExp = Res.takeAs<Expr>();
2448      }
2449
2450      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2451      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2452      // function return.
2453
2454      // In C++ the return statement is handled via a copy initialization,
2455      // the C version of which boils down to CheckSingleAssignmentConstraints.
2456      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2457      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2458                                                                     FnRetType,
2459                                                            NRVOCandidate != 0);
2460      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2461                                                       FnRetType, RetValExp);
2462      if (Res.isInvalid()) {
2463        // FIXME: Cleanup temporaries here, anyway?
2464        return StmtError();
2465      }
2466
2467      RetValExp = Res.takeAs<Expr>();
2468      if (RetValExp)
2469        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2470    }
2471
2472    if (RetValExp) {
2473      CheckImplicitConversions(RetValExp, ReturnLoc);
2474      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2475    }
2476    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2477  }
2478
2479  // If we need to check for the named return value optimization, save the
2480  // return statement in our scope for later processing.
2481  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2482      !CurContext->isDependentContext())
2483    FunctionScopes.back()->Returns.push_back(Result);
2484
2485  return Owned(Result);
2486}
2487
2488/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2489/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2490/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2491/// provide a strong guidance to not use it.
2492///
2493/// This method checks to see if the argument is an acceptable l-value and
2494/// returns false if it is a case we can handle.
2495static bool CheckAsmLValue(const Expr *E, Sema &S) {
2496  // Type dependent expressions will be checked during instantiation.
2497  if (E->isTypeDependent())
2498    return false;
2499
2500  if (E->isLValue())
2501    return false;  // Cool, this is an lvalue.
2502
2503  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2504  // are supposed to allow.
2505  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
2506  if (E != E2 && E2->isLValue()) {
2507    if (!S.getLangOpts().HeinousExtensions)
2508      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2509        << E->getSourceRange();
2510    else
2511      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2512        << E->getSourceRange();
2513    // Accept, even if we emitted an error diagnostic.
2514    return false;
2515  }
2516
2517  // None of the above, just randomly invalid non-lvalue.
2518  return true;
2519}
2520
2521/// isOperandMentioned - Return true if the specified operand # is mentioned
2522/// anywhere in the decomposed asm string.
2523static bool isOperandMentioned(unsigned OpNo,
2524                         ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
2525  for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2526    const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2527    if (!Piece.isOperand()) continue;
2528
2529    // If this is a reference to the input and if the input was the smaller
2530    // one, then we have to reject this asm.
2531    if (Piece.getOperandNo() == OpNo)
2532      return true;
2533  }
2534  return false;
2535}
2536
2537StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2538                              bool IsVolatile, unsigned NumOutputs,
2539                              unsigned NumInputs, IdentifierInfo **Names,
2540                              MultiExprArg constraints, MultiExprArg exprs,
2541                              Expr *asmString, MultiExprArg clobbers,
2542                              SourceLocation RParenLoc, bool MSAsm) {
2543  unsigned NumClobbers = clobbers.size();
2544  StringLiteral **Constraints =
2545    reinterpret_cast<StringLiteral**>(constraints.get());
2546  Expr **Exprs = exprs.get();
2547  StringLiteral *AsmString = cast<StringLiteral>(asmString);
2548  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2549
2550  SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2551
2552  // The parser verifies that there is a string literal here.
2553  if (!AsmString->isAscii())
2554    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2555      << AsmString->getSourceRange());
2556
2557  for (unsigned i = 0; i != NumOutputs; i++) {
2558    StringLiteral *Literal = Constraints[i];
2559    if (!Literal->isAscii())
2560      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2561        << Literal->getSourceRange());
2562
2563    StringRef OutputName;
2564    if (Names[i])
2565      OutputName = Names[i]->getName();
2566
2567    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
2568    if (!Context.getTargetInfo().validateOutputConstraint(Info))
2569      return StmtError(Diag(Literal->getLocStart(),
2570                            diag::err_asm_invalid_output_constraint)
2571                       << Info.getConstraintStr());
2572
2573    // Check that the output exprs are valid lvalues.
2574    Expr *OutputExpr = Exprs[i];
2575    if (CheckAsmLValue(OutputExpr, *this)) {
2576      return StmtError(Diag(OutputExpr->getLocStart(),
2577                  diag::err_asm_invalid_lvalue_in_output)
2578        << OutputExpr->getSourceRange());
2579    }
2580
2581    OutputConstraintInfos.push_back(Info);
2582  }
2583
2584  SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2585
2586  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
2587    StringLiteral *Literal = Constraints[i];
2588    if (!Literal->isAscii())
2589      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2590        << Literal->getSourceRange());
2591
2592    StringRef InputName;
2593    if (Names[i])
2594      InputName = Names[i]->getName();
2595
2596    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
2597    if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
2598                                                NumOutputs, Info)) {
2599      return StmtError(Diag(Literal->getLocStart(),
2600                            diag::err_asm_invalid_input_constraint)
2601                       << Info.getConstraintStr());
2602    }
2603
2604    Expr *InputExpr = Exprs[i];
2605
2606    // Only allow void types for memory constraints.
2607    if (Info.allowsMemory() && !Info.allowsRegister()) {
2608      if (CheckAsmLValue(InputExpr, *this))
2609        return StmtError(Diag(InputExpr->getLocStart(),
2610                              diag::err_asm_invalid_lvalue_in_input)
2611                         << Info.getConstraintStr()
2612                         << InputExpr->getSourceRange());
2613    }
2614
2615    if (Info.allowsRegister()) {
2616      if (InputExpr->getType()->isVoidType()) {
2617        return StmtError(Diag(InputExpr->getLocStart(),
2618                              diag::err_asm_invalid_type_in_input)
2619          << InputExpr->getType() << Info.getConstraintStr()
2620          << InputExpr->getSourceRange());
2621      }
2622    }
2623
2624    ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2625    if (Result.isInvalid())
2626      return StmtError();
2627
2628    Exprs[i] = Result.take();
2629    InputConstraintInfos.push_back(Info);
2630  }
2631
2632  // Check that the clobbers are valid.
2633  for (unsigned i = 0; i != NumClobbers; i++) {
2634    StringLiteral *Literal = Clobbers[i];
2635    if (!Literal->isAscii())
2636      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2637        << Literal->getSourceRange());
2638
2639    StringRef Clobber = Literal->getString();
2640
2641    if (!Context.getTargetInfo().isValidClobber(Clobber))
2642      return StmtError(Diag(Literal->getLocStart(),
2643                  diag::err_asm_unknown_register_name) << Clobber);
2644  }
2645
2646  AsmStmt *NS =
2647    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2648                          NumOutputs, NumInputs, Names, Constraints, Exprs,
2649                          AsmString, NumClobbers, Clobbers, RParenLoc);
2650  // Validate the asm string, ensuring it makes sense given the operands we
2651  // have.
2652  SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2653  unsigned DiagOffs;
2654  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
2655    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2656           << AsmString->getSourceRange();
2657    return StmtError();
2658  }
2659
2660  // Validate tied input operands for type mismatches.
2661  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2662    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2663
2664    // If this is a tied constraint, verify that the output and input have
2665    // either exactly the same type, or that they are int/ptr operands with the
2666    // same size (int/long, int*/long, are ok etc).
2667    if (!Info.hasTiedOperand()) continue;
2668
2669    unsigned TiedTo = Info.getTiedOperand();
2670    unsigned InputOpNo = i+NumOutputs;
2671    Expr *OutputExpr = Exprs[TiedTo];
2672    Expr *InputExpr = Exprs[InputOpNo];
2673
2674    if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2675      continue;
2676
2677    QualType InTy = InputExpr->getType();
2678    QualType OutTy = OutputExpr->getType();
2679    if (Context.hasSameType(InTy, OutTy))
2680      continue;  // All types can be tied to themselves.
2681
2682    // Decide if the input and output are in the same domain (integer/ptr or
2683    // floating point.
2684    enum AsmDomain {
2685      AD_Int, AD_FP, AD_Other
2686    } InputDomain, OutputDomain;
2687
2688    if (InTy->isIntegerType() || InTy->isPointerType())
2689      InputDomain = AD_Int;
2690    else if (InTy->isRealFloatingType())
2691      InputDomain = AD_FP;
2692    else
2693      InputDomain = AD_Other;
2694
2695    if (OutTy->isIntegerType() || OutTy->isPointerType())
2696      OutputDomain = AD_Int;
2697    else if (OutTy->isRealFloatingType())
2698      OutputDomain = AD_FP;
2699    else
2700      OutputDomain = AD_Other;
2701
2702    // They are ok if they are the same size and in the same domain.  This
2703    // allows tying things like:
2704    //   void* to int*
2705    //   void* to int            if they are the same size.
2706    //   double to long double   if they are the same size.
2707    //
2708    uint64_t OutSize = Context.getTypeSize(OutTy);
2709    uint64_t InSize = Context.getTypeSize(InTy);
2710    if (OutSize == InSize && InputDomain == OutputDomain &&
2711        InputDomain != AD_Other)
2712      continue;
2713
2714    // If the smaller input/output operand is not mentioned in the asm string,
2715    // then we can promote the smaller one to a larger input and the asm string
2716    // won't notice.
2717    bool SmallerValueMentioned = false;
2718
2719    // If this is a reference to the input and if the input was the smaller
2720    // one, then we have to reject this asm.
2721    if (isOperandMentioned(InputOpNo, Pieces)) {
2722      // This is a use in the asm string of the smaller operand.  Since we
2723      // codegen this by promoting to a wider value, the asm will get printed
2724      // "wrong".
2725      SmallerValueMentioned |= InSize < OutSize;
2726    }
2727    if (isOperandMentioned(TiedTo, Pieces)) {
2728      // If this is a reference to the output, and if the output is the larger
2729      // value, then it's ok because we'll promote the input to the larger type.
2730      SmallerValueMentioned |= OutSize < InSize;
2731    }
2732
2733    // If the smaller value wasn't mentioned in the asm string, and if the
2734    // output was a register, just extend the shorter one to the size of the
2735    // larger one.
2736    if (!SmallerValueMentioned && InputDomain != AD_Other &&
2737        OutputConstraintInfos[TiedTo].allowsRegister())
2738      continue;
2739
2740    // Either both of the operands were mentioned or the smaller one was
2741    // mentioned.  One more special case that we'll allow: if the tied input is
2742    // integer, unmentioned, and is a constant, then we'll allow truncating it
2743    // down to the size of the destination.
2744    if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2745        !isOperandMentioned(InputOpNo, Pieces) &&
2746        InputExpr->isEvaluatable(Context)) {
2747      CastKind castKind =
2748        (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2749      InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2750      Exprs[InputOpNo] = InputExpr;
2751      NS->setInputExpr(i, InputExpr);
2752      continue;
2753    }
2754
2755    Diag(InputExpr->getLocStart(),
2756         diag::err_asm_tying_incompatible_types)
2757      << InTy << OutTy << OutputExpr->getSourceRange()
2758      << InputExpr->getSourceRange();
2759    return StmtError();
2760  }
2761
2762  return Owned(NS);
2763}
2764
2765// isMSAsmKeyword - Return true if this is an MS-style inline asm keyword. These
2766// require special handling.
2767static bool isMSAsmKeyword(StringRef Name) {
2768  bool Ret = llvm::StringSwitch<bool>(Name)
2769    .Cases("EVEN", "ALIGN", true) // Alignment directives.
2770    .Cases("LENGTH", "SIZE", "TYPE", true) // Type and variable sizes.
2771    .Case("_emit", true) // _emit Pseudoinstruction.
2772    .Default(false);
2773  return Ret;
2774}
2775
2776static StringRef getSpelling(Sema &SemaRef, Token AsmTok) {
2777  StringRef Asm;
2778  SmallString<512> TokenBuf;
2779  TokenBuf.resize(512);
2780  bool StringInvalid = false;
2781  Asm = SemaRef.PP.getSpelling(AsmTok, TokenBuf, &StringInvalid);
2782  assert (!StringInvalid && "Expected valid string!");
2783  return Asm;
2784}
2785
2786static void patchMSAsmStrings(Sema &SemaRef, bool &IsSimple,
2787                              SourceLocation AsmLoc,
2788                              ArrayRef<Token> AsmToks,
2789                              const TargetInfo &TI,
2790                              std::vector<llvm::BitVector> &AsmRegs,
2791                              std::vector<llvm::BitVector> &AsmNames,
2792                              std::vector<std::string> &AsmStrings) {
2793  assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
2794
2795  // Assume simple asm stmt until we parse a non-register identifer.
2796  IsSimple = true;
2797
2798  SmallString<512> Asm;
2799  unsigned NumAsmStrings = 0;
2800  for (unsigned i = 0, e = AsmToks.size(); i != e; ++i) {
2801
2802    // Determine if this should be considered a new asm.
2803    bool isNewAsm = i == 0 || AsmToks[i].isAtStartOfLine() ||
2804      AsmToks[i].is(tok::kw_asm);
2805
2806    // Emit the previous asm string.
2807    if (i && isNewAsm) {
2808      AsmStrings[NumAsmStrings++] = Asm.c_str();
2809      if (AsmToks[i].is(tok::kw_asm)) {
2810        ++i; // Skip __asm
2811        assert (i != e && "Expected another token.");
2812      }
2813    }
2814
2815    // Start a new asm string with the opcode.
2816    if (isNewAsm) {
2817      AsmRegs[NumAsmStrings].resize(AsmToks.size());
2818      AsmNames[NumAsmStrings].resize(AsmToks.size());
2819
2820      StringRef Piece = AsmToks[i].getIdentifierInfo()->getName();
2821      // MS-style inline asm keywords require special handling.
2822      if (isMSAsmKeyword(Piece))
2823        IsSimple = false;
2824
2825      // TODO: Verify this is a valid opcode.
2826      Asm = Piece;
2827      continue;
2828    }
2829
2830    if (i && AsmToks[i].hasLeadingSpace())
2831      Asm += ' ';
2832
2833    // Check the operand(s).
2834    switch (AsmToks[i].getKind()) {
2835    default:
2836      IsSimple = false;
2837      Asm += getSpelling(SemaRef, AsmToks[i]);
2838      break;
2839    case tok::comma: Asm += ","; break;
2840    case tok::colon: Asm += ":"; break;
2841    case tok::l_square: Asm += "["; break;
2842    case tok::r_square: Asm += "]"; break;
2843    case tok::l_brace: Asm += "{"; break;
2844    case tok::r_brace: Asm += "}"; break;
2845    case tok::numeric_constant:
2846      Asm += getSpelling(SemaRef, AsmToks[i]);
2847      break;
2848    case tok::identifier: {
2849      IdentifierInfo *II = AsmToks[i].getIdentifierInfo();
2850      StringRef Name = II->getName();
2851
2852      // Valid register?
2853      if (TI.isValidGCCRegisterName(Name)) {
2854        AsmRegs[NumAsmStrings].set(i);
2855        Asm += Name;
2856        break;
2857      }
2858
2859      IsSimple = false;
2860
2861      // MS-style inline asm keywords require special handling.
2862      if (isMSAsmKeyword(Name)) {
2863        IsSimple = false;
2864        Asm += Name;
2865        break;
2866      }
2867
2868      // FIXME: Why are we missing this segment register?
2869      if (Name == "fs") {
2870        Asm += Name;
2871        break;
2872      }
2873
2874      // Lookup the identifier.
2875      // TODO: Someone with more experience with clang should verify this the
2876      // proper way of doing a symbol lookup.
2877      DeclarationName DeclName(II);
2878      Scope *CurScope = SemaRef.getCurScope();
2879      LookupResult R(SemaRef, DeclName, AsmLoc, Sema::LookupOrdinaryName);
2880      if (!SemaRef.LookupName(R, CurScope, false/*AllowBuiltinCreation*/))
2881        break;
2882
2883      assert (R.isSingleResult() && "Expected a single result?!");
2884      NamedDecl *Decl = R.getFoundDecl();
2885      switch (Decl->getKind()) {
2886      default:
2887        assert(0 && "Unknown decl kind.");
2888        break;
2889      case Decl::Var: {
2890      case Decl::ParmVar:
2891        AsmNames[NumAsmStrings].set(i);
2892
2893        VarDecl *Var = cast<VarDecl>(Decl);
2894        QualType Ty = Var->getType();
2895        (void)Ty; // Avoid warning.
2896        // TODO: Patch identifier with valid operand.  One potential idea is to
2897        // probe the backend with type information to guess the possible
2898        // operand.
2899        break;
2900      }
2901      }
2902      break;
2903    }
2904    }
2905  }
2906
2907  // Emit the final (and possibly only) asm string.
2908  AsmStrings[NumAsmStrings] = Asm.c_str();
2909}
2910
2911// Build the unmodified MSAsmString.
2912static std::string buildMSAsmString(Sema &SemaRef,
2913                                    ArrayRef<Token> AsmToks,
2914                                    unsigned &NumAsmStrings) {
2915  assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
2916  NumAsmStrings = 0;
2917
2918  SmallString<512> Asm;
2919  for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
2920    bool isNewAsm = i == 0 || AsmToks[i].isAtStartOfLine() ||
2921      AsmToks[i].is(tok::kw_asm);
2922
2923    if (isNewAsm) {
2924      ++NumAsmStrings;
2925      if (i)
2926        Asm += '\n';
2927      if (AsmToks[i].is(tok::kw_asm)) {
2928        i++; // Skip __asm
2929        assert (i != e && "Expected another token");
2930      }
2931    }
2932
2933    if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
2934      Asm += ' ';
2935
2936    Asm += getSpelling(SemaRef, AsmToks[i]);
2937  }
2938  return Asm.c_str();
2939}
2940
2941StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
2942                                SourceLocation LBraceLoc,
2943                                ArrayRef<Token> AsmToks,
2944                                SourceLocation EndLoc) {
2945  // MS-style inline assembly is not fully supported, so emit a warning.
2946  Diag(AsmLoc, diag::warn_unsupported_msasm);
2947  SmallVector<StringRef,4> Clobbers;
2948  std::set<std::string> ClobberRegs;
2949  SmallVector<IdentifierInfo*, 4> Inputs;
2950  SmallVector<IdentifierInfo*, 4> Outputs;
2951
2952  // Empty asm statements don't need to instantiate the AsmParser, etc.
2953  if (AsmToks.empty()) {
2954    StringRef AsmString;
2955    MSAsmStmt *NS =
2956      new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
2957                              /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
2958                              AsmString, Clobbers, EndLoc);
2959    return Owned(NS);
2960  }
2961
2962  unsigned NumAsmStrings;
2963  std::string AsmString = buildMSAsmString(*this, AsmToks, NumAsmStrings);
2964
2965  bool IsSimple;
2966  std::vector<llvm::BitVector> Regs;
2967  std::vector<llvm::BitVector> Names;
2968  std::vector<std::string> PatchedAsmStrings;
2969
2970  Regs.resize(NumAsmStrings);
2971  Names.resize(NumAsmStrings);
2972  PatchedAsmStrings.resize(NumAsmStrings);
2973
2974  // Rewrite operands to appease the AsmParser.
2975  patchMSAsmStrings(*this, IsSimple, AsmLoc, AsmToks,
2976                    Context.getTargetInfo(), Regs, Names, PatchedAsmStrings);
2977
2978  // patchMSAsmStrings doesn't correctly patch non-simple asm statements.
2979  if (!IsSimple) {
2980    MSAsmStmt *NS =
2981      new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
2982                              /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
2983                              AsmString, Clobbers, EndLoc);
2984    return Owned(NS);
2985  }
2986
2987  // Initialize targets and assembly printers/parsers.
2988  llvm::InitializeAllTargetInfos();
2989  llvm::InitializeAllTargetMCs();
2990  llvm::InitializeAllAsmParsers();
2991
2992  // Get the target specific parser.
2993  std::string Error;
2994  const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
2995  const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
2996
2997  OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
2998  OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2999  OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
3000  OwningPtr<llvm::MCSubtargetInfo>
3001    STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
3002
3003  for (unsigned i = 0, e = PatchedAsmStrings.size(); i != e; ++i) {
3004    llvm::SourceMgr SrcMgr;
3005    llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
3006    llvm::MemoryBuffer *Buffer =
3007      llvm::MemoryBuffer::getMemBuffer(PatchedAsmStrings[i], "<inline asm>");
3008
3009    // Tell SrcMgr about this buffer, which is what the parser will pick up.
3010    SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
3011
3012    OwningPtr<llvm::MCStreamer> Str;
3013    OwningPtr<llvm::MCAsmParser>
3014      Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
3015    OwningPtr<llvm::MCTargetAsmParser>
3016      TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
3017    // Change to the Intel dialect.
3018    Parser->setAssemblerDialect(1);
3019    Parser->setTargetParser(*TargetParser.get());
3020
3021    // Prime the lexer.
3022    Parser->Lex();
3023
3024    // Parse the opcode.
3025    StringRef IDVal;
3026    Parser->ParseIdentifier(IDVal);
3027
3028    // Canonicalize the opcode to lower case.
3029    SmallString<128> Opcode;
3030    for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
3031      Opcode.push_back(tolower(IDVal[i]));
3032
3033    // Parse the operands.
3034    llvm::SMLoc IDLoc;
3035    SmallVector<llvm::MCParsedAsmOperand*, 8> Operands;
3036    bool HadError = TargetParser->ParseInstruction(Opcode.str(), IDLoc,
3037                                                   Operands);
3038    assert (!HadError && "Unexpected error parsing instruction");
3039
3040    // Match the MCInstr.
3041    SmallVector<llvm::MCInst, 2> Instrs;
3042    HadError = TargetParser->MatchInstruction(IDLoc, Operands, Instrs);
3043    assert (!HadError && "Unexpected error matching instruction");
3044    assert ((Instrs.size() == 1) && "Expected only a single instruction.");
3045
3046    // Get the instruction descriptor.
3047    llvm::MCInst Inst = Instrs[0];
3048    const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
3049    const llvm::MCInstrDesc &Desc = MII->get(Inst.getOpcode());
3050    llvm::MCInstPrinter *IP =
3051      TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
3052
3053    // Build the list of clobbers.
3054    for (unsigned i = 0, e = Desc.getNumDefs(); i != e; ++i) {
3055      const llvm::MCOperand &Op = Inst.getOperand(i);
3056      if (!Op.isReg())
3057        continue;
3058
3059      std::string Reg;
3060      llvm::raw_string_ostream OS(Reg);
3061      IP->printRegName(OS, Op.getReg());
3062
3063      StringRef Clobber(OS.str());
3064      if (!Context.getTargetInfo().isValidClobber(Clobber))
3065        return StmtError(Diag(AsmLoc, diag::err_asm_unknown_register_name) <<
3066                         Clobber);
3067      ClobberRegs.insert(Reg);
3068    }
3069  }
3070  for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3071         E = ClobberRegs.end(); I != E; ++I)
3072    Clobbers.push_back(*I);
3073
3074  MSAsmStmt *NS =
3075    new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
3076                            /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
3077                            AsmString, Clobbers, EndLoc);
3078  return Owned(NS);
3079}
3080
3081StmtResult
3082Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3083                           SourceLocation RParen, Decl *Parm,
3084                           Stmt *Body) {
3085  VarDecl *Var = cast_or_null<VarDecl>(Parm);
3086  if (Var && Var->isInvalidDecl())
3087    return StmtError();
3088
3089  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
3090}
3091
3092StmtResult
3093Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3094  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
3095}
3096
3097StmtResult
3098Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3099                         MultiStmtArg CatchStmts, Stmt *Finally) {
3100  if (!getLangOpts().ObjCExceptions)
3101    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3102
3103  getCurFunction()->setHasBranchProtectedScope();
3104  unsigned NumCatchStmts = CatchStmts.size();
3105  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
3106                                     CatchStmts.release(),
3107                                     NumCatchStmts,
3108                                     Finally));
3109}
3110
3111StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3112  if (Throw) {
3113    ExprResult Result = DefaultLvalueConversion(Throw);
3114    if (Result.isInvalid())
3115      return StmtError();
3116
3117    Throw = MaybeCreateExprWithCleanups(Result.take());
3118    QualType ThrowType = Throw->getType();
3119    // Make sure the expression type is an ObjC pointer or "void *".
3120    if (!ThrowType->isDependentType() &&
3121        !ThrowType->isObjCObjectPointerType()) {
3122      const PointerType *PT = ThrowType->getAs<PointerType>();
3123      if (!PT || !PT->getPointeeType()->isVoidType())
3124        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3125                         << Throw->getType() << Throw->getSourceRange());
3126    }
3127  }
3128
3129  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
3130}
3131
3132StmtResult
3133Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3134                           Scope *CurScope) {
3135  if (!getLangOpts().ObjCExceptions)
3136    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3137
3138  if (!Throw) {
3139    // @throw without an expression designates a rethrow (which much occur
3140    // in the context of an @catch clause).
3141    Scope *AtCatchParent = CurScope;
3142    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3143      AtCatchParent = AtCatchParent->getParent();
3144    if (!AtCatchParent)
3145      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3146  }
3147  return BuildObjCAtThrowStmt(AtLoc, Throw);
3148}
3149
3150ExprResult
3151Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3152  ExprResult result = DefaultLvalueConversion(operand);
3153  if (result.isInvalid())
3154    return ExprError();
3155  operand = result.take();
3156
3157  // Make sure the expression type is an ObjC pointer or "void *".
3158  QualType type = operand->getType();
3159  if (!type->isDependentType() &&
3160      !type->isObjCObjectPointerType()) {
3161    const PointerType *pointerType = type->getAs<PointerType>();
3162    if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3163      return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3164               << type << operand->getSourceRange();
3165  }
3166
3167  // The operand to @synchronized is a full-expression.
3168  return MaybeCreateExprWithCleanups(operand);
3169}
3170
3171StmtResult
3172Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3173                                  Stmt *SyncBody) {
3174  // We can't jump into or indirect-jump out of a @synchronized block.
3175  getCurFunction()->setHasBranchProtectedScope();
3176  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
3177}
3178
3179/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3180/// and creates a proper catch handler from them.
3181StmtResult
3182Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3183                         Stmt *HandlerBlock) {
3184  // There's nothing to test that ActOnExceptionDecl didn't already test.
3185  return Owned(new (Context) CXXCatchStmt(CatchLoc,
3186                                          cast_or_null<VarDecl>(ExDecl),
3187                                          HandlerBlock));
3188}
3189
3190StmtResult
3191Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3192  getCurFunction()->setHasBranchProtectedScope();
3193  return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3194}
3195
3196namespace {
3197
3198class TypeWithHandler {
3199  QualType t;
3200  CXXCatchStmt *stmt;
3201public:
3202  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3203  : t(type), stmt(statement) {}
3204
3205  // An arbitrary order is fine as long as it places identical
3206  // types next to each other.
3207  bool operator<(const TypeWithHandler &y) const {
3208    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3209      return true;
3210    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3211      return false;
3212    else
3213      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3214  }
3215
3216  bool operator==(const TypeWithHandler& other) const {
3217    return t == other.t;
3218  }
3219
3220  CXXCatchStmt *getCatchStmt() const { return stmt; }
3221  SourceLocation getTypeSpecStartLoc() const {
3222    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3223  }
3224};
3225
3226}
3227
3228/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3229/// handlers and creates a try statement from them.
3230StmtResult
3231Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3232                       MultiStmtArg RawHandlers) {
3233  // Don't report an error if 'try' is used in system headers.
3234  if (!getLangOpts().CXXExceptions &&
3235      !getSourceManager().isInSystemHeader(TryLoc))
3236      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3237
3238  unsigned NumHandlers = RawHandlers.size();
3239  assert(NumHandlers > 0 &&
3240         "The parser shouldn't call this if there are no handlers.");
3241  Stmt **Handlers = RawHandlers.get();
3242
3243  SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3244
3245  for (unsigned i = 0; i < NumHandlers; ++i) {
3246    CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3247    if (!Handler->getExceptionDecl()) {
3248      if (i < NumHandlers - 1)
3249        return StmtError(Diag(Handler->getLocStart(),
3250                              diag::err_early_catch_all));
3251
3252      continue;
3253    }
3254
3255    const QualType CaughtType = Handler->getCaughtType();
3256    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3257    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3258  }
3259
3260  // Detect handlers for the same type as an earlier one.
3261  if (NumHandlers > 1) {
3262    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3263
3264    TypeWithHandler prev = TypesWithHandlers[0];
3265    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3266      TypeWithHandler curr = TypesWithHandlers[i];
3267
3268      if (curr == prev) {
3269        Diag(curr.getTypeSpecStartLoc(),
3270             diag::warn_exception_caught_by_earlier_handler)
3271          << curr.getCatchStmt()->getCaughtType().getAsString();
3272        Diag(prev.getTypeSpecStartLoc(),
3273             diag::note_previous_exception_handler)
3274          << prev.getCatchStmt()->getCaughtType().getAsString();
3275      }
3276
3277      prev = curr;
3278    }
3279  }
3280
3281  getCurFunction()->setHasBranchProtectedScope();
3282
3283  // FIXME: We should detect handlers that cannot catch anything because an
3284  // earlier handler catches a superclass. Need to find a method that is not
3285  // quadratic for this.
3286  // Neither of these are explicitly forbidden, but every compiler detects them
3287  // and warns.
3288
3289  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
3290                                  Handlers, NumHandlers));
3291}
3292
3293StmtResult
3294Sema::ActOnSEHTryBlock(bool IsCXXTry,
3295                       SourceLocation TryLoc,
3296                       Stmt *TryBlock,
3297                       Stmt *Handler) {
3298  assert(TryBlock && Handler);
3299
3300  getCurFunction()->setHasBranchProtectedScope();
3301
3302  return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3303}
3304
3305StmtResult
3306Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3307                          Expr *FilterExpr,
3308                          Stmt *Block) {
3309  assert(FilterExpr && Block);
3310
3311  if(!FilterExpr->getType()->isIntegerType()) {
3312    return StmtError(Diag(FilterExpr->getExprLoc(),
3313                     diag::err_filter_expression_integral)
3314                     << FilterExpr->getType());
3315  }
3316
3317  return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3318}
3319
3320StmtResult
3321Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3322                           Stmt *Block) {
3323  assert(Block);
3324  return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3325}
3326
3327StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3328                                            bool IsIfExists,
3329                                            NestedNameSpecifierLoc QualifierLoc,
3330                                            DeclarationNameInfo NameInfo,
3331                                            Stmt *Nested)
3332{
3333  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3334                                             QualifierLoc, NameInfo,
3335                                             cast<CompoundStmt>(Nested));
3336}
3337
3338
3339StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3340                                            bool IsIfExists,
3341                                            CXXScopeSpec &SS,
3342                                            UnqualifiedId &Name,
3343                                            Stmt *Nested) {
3344  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3345                                    SS.getWithLocInContext(Context),
3346                                    GetNameFromUnqualifiedId(Name),
3347                                    Nested);
3348}
3349