15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//  This file implements semantic analysis for statements.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
142d88708cbe4e4ec5e04e4acb6bd7f5be68557379John McCall#include "clang/Sema/SemaInternal.h"
15f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner#include "clang/AST/ASTContext.h"
16a18e70b25c85d7e653e642b5e6e58d6063af3d83Fariborz Jahanian#include "clang/AST/ASTDiagnostic.h"
171cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall#include "clang/AST/CharUnits.h"
18c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
19694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu#include "clang/AST/EvaluatedExprVisitor.h"
2084fb9c0be621c9e4ca4e56f67dae2a0bb6e44821Douglas Gregor#include "clang/AST/ExprCXX.h"
21419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner#include "clang/AST/ExprObjC.h"
2216f0049415ec596504891259e2a83e19871c0d52Chris Lattner#include "clang/AST/StmtCXX.h"
2355fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/AST/StmtObjC.h"
24209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall#include "clang/AST/TypeLoc.h"
2555fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Lex/Preprocessor.h"
2655fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/Initialization.h"
2755fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/Lookup.h"
2855fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/Scope.h"
2955fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/ScopeInfo.h"
30ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner#include "llvm/ADT/ArrayRef.h"
31c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl#include "llvm/ADT/STLExtras.h"
32694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu#include "llvm/ADT/SmallPtrSet.h"
3350de5e3247a20e0e548dc47022a011250e6e4e8fDouglas Gregor#include "llvm/ADT/SmallString.h"
34c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl#include "llvm/ADT/SmallVector.h"
355f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
36781472fe99a120098c631b0cbe33c89f8cef5e70John McCallusing namespace sema;
375f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
38419563768ef4929a622d7c2b066856e82901bb91Richard SmithStmtResult Sema::ActOnExprStmt(ExprResult FE) {
39419563768ef4929a622d7c2b066856e82901bb91Richard Smith  if (FE.isInvalid())
40419563768ef4929a622d7c2b066856e82901bb91Richard Smith    return StmtError();
41419563768ef4929a622d7c2b066856e82901bb91Richard Smith
42419563768ef4929a622d7c2b066856e82901bb91Richard Smith  FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43419563768ef4929a622d7c2b066856e82901bb91Richard Smith                           /*DiscardedValue*/ true);
44419563768ef4929a622d7c2b066856e82901bb91Richard Smith  if (FE.isInvalid())
45bebbe0d9b7568ce43a464286bee49429489ef483Douglas Gregor    return StmtError();
46bebbe0d9b7568ce43a464286bee49429489ef483Douglas Gregor
47834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // void expression for its side effects.  Conversion to void allows any
49834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // operand, even incomplete types.
50a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl
51834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // Same thing in for stmt first clause (when expr) and third clause.
52419563768ef4929a622d7c2b066856e82901bb91Richard Smith  return Owned(static_cast<Stmt*>(FE.take()));
535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
545f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
555f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
56b760f11fae94e3003b9241ac50c02617465f2fa2John McCallStmtResult Sema::ActOnExprStmtError() {
57b760f11fae94e3003b9241ac50c02617465f2fa2John McCall  DiscardCleanupsInEvaluationContext();
58b760f11fae94e3003b9241ac50c02617465f2fa2John McCall  return StmtError();
59b760f11fae94e3003b9241ac50c02617465f2fa2John McCall}
60b760f11fae94e3003b9241ac50c02617465f2fa2John McCall
61b7d98d35ea723624345f06e5895ddce2e0388ef0Argyrios KyrtzidisStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
62e2ca828119b8bff4a5c25c6db8ee4fec558451e7Argyrios Kyrtzidis                               bool HasLeadingEmptyMacro) {
63e2ca828119b8bff4a5c25c6db8ee4fec558451e7Argyrios Kyrtzidis  return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
645f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
655f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
66337e550218128e7d922c09bb354fbc71de90c568Chris LattnerStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67337e550218128e7d922c09bb354fbc71de90c568Chris Lattner                               SourceLocation EndLoc) {
6820401698e3bd93a24bb5d9e18e435895cefe5fd1Chris Lattner  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
70682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner  // If we have an invalid decl, just return an error.
7120401698e3bd93a24bb5d9e18e435895cefe5fd1Chris Lattner  if (DG.isNull()) return StmtError();
721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7324e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
745f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
755f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
76a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanianvoid Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
77a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
7855c7d02e6c76cdf1dfc67bd9cbeb5d3b69eec353Wei Pan
7912849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  // If we don't have a declaration, or we have an invalid declaration,
8012849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  // just return.
8112849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  if (DG.isNull() || !DG.isSingleDecl())
8212849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor    return;
8312849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor
8412849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  Decl *decl = DG.getSingleDecl();
8512849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  if (!decl || decl->isInvalidDecl())
8612849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor    return;
87dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
8812849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  // Only variable declarations are permitted.
8912849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  VarDecl *var = dyn_cast<VarDecl>(decl);
9012849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  if (!var) {
9112849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor    Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
9212849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor    decl->setInvalidDecl();
9312849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor    return;
9412849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor  }
95f85e193739c953358c865005855253af4f68a497John McCall
967acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // foreach variables are never actually initialized in the way that
977acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // the parser came up with.
987acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  var->setInit(0);
997acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
1007acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // In ARC, we don't need to retain the iteration variable of a fast
1017acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // enumeration loop.  Rather than actually trying to catch that
1027acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // during declaration processing, we remove the consequences here.
1034e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().ObjCAutoRefCount) {
1047acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    QualType type = var->getType();
1057acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
1067acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // Only do this if we inferred the lifetime.  Inferred lifetime
1077acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // will show up as a local qualifier because explicit lifetime
1087acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // should have shown up as an AttributedType instead.
1097acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
1107acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      // Add 'const' and mark the variable as pseudo-strong.
1117acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      var->setType(type.withConst());
1127acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      var->setARCPseudoStrong(true);
113f85e193739c953358c865005855253af4f68a497John McCall    }
114f85e193739c953358c865005855253af4f68a497John McCall  }
115a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian}
116a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian
117ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
1189d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth///
1199d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth/// Adding a cast to void (or other expression wrappers) will prevent the
1209d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth/// warning from firing.
121ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruthstatic bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
1229d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  SourceLocation Loc;
12350bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  bool IsNotEqual, CanAssign;
1249d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1259d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
1269d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
127ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth      return false;
1289d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1299d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    Loc = Op->getOperatorLoc();
13050bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    IsNotEqual = Op->getOpcode() == BO_NE;
13150bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
1329d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
1339d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    if (Op->getOperator() != OO_EqualEqual &&
1349d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth        Op->getOperator() != OO_ExclaimEqual)
135ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth      return false;
1369d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1379d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    Loc = Op->getOperatorLoc();
13850bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
13950bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
1409d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  } else {
1419d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    // Not a typo-prone comparison.
142ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth    return false;
1439d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  }
1449d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1459d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  // Suppress warnings when the operator, suspicious as it may be, comes from
1469d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  // a macro expansion.
147c3cd6f7a5d33ad44f6c9cf4faa7046c77baa128eMatt Beaumont-Gay  if (S.SourceMgr.isMacroBodyExpansion(Loc))
148ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth    return false;
1499d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
150ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth  S.Diag(Loc, diag::warn_unused_comparison)
1519d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    << (unsigned)IsNotEqual << E->getSourceRange();
1529d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
15350bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  // If the LHS is a plausible entity to assign to, provide a fixit hint to
15450bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  // correct common typos.
15550bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  if (CanAssign) {
15650bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    if (IsNotEqual)
15750bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth      S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
15850bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth        << FixItHint::CreateReplacement(Loc, "|=");
15950bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    else
16050bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth      S.Diag(Loc, diag::note_equality_comparison_to_assign)
16150bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth        << FixItHint::CreateReplacement(Loc, "=");
16250bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  }
163ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth
164ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth  return true;
1659d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth}
1669d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
167636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlssonvoid Sema::DiagnoseUnusedExprResult(const Stmt *S) {
168d2827af6f96d441d72315dbe6d8505c3be0f2aa6Argyrios Kyrtzidis  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
169d2827af6f96d441d72315dbe6d8505c3be0f2aa6Argyrios Kyrtzidis    return DiagnoseUnusedExprResult(Label->getSubStmt());
170d2827af6f96d441d72315dbe6d8505c3be0f2aa6Argyrios Kyrtzidis
171754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  const Expr *E = dyn_cast_or_null<Expr>(S);
172636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson  if (!E)
173636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    return;
17487b73ba920f523ef13f2420cbdb958a281aa6f33Matt Beaumont-Gay  SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
1759016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  // In most cases, we don't want to warn if the expression is written in a
1769016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  // macro body, or if the macro comes from a system header. If the offending
1779016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  // expression is a call to a function with the warn_unused_result attribute,
1789016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  // we warn no matter the location. Because of the order in which the various
1799016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  // checks need to happen, we factor out the macro-related test here.
1809016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  bool ShouldSuppress =
1819016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay      SourceMgr.isMacroBodyExpansion(ExprLoc) ||
1829016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay      SourceMgr.isInSystemMacro(ExprLoc);
183636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson
184a6115068cde719142eb394db88612c185cabd05bEli Friedman  const Expr *WarnExpr;
185636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson  SourceLocation Loc;
186636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson  SourceRange R1, R2;
18787b73ba920f523ef13f2420cbdb958a281aa6f33Matt Beaumont-Gay  if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
188636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    return;
1891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19006b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner  // If this is a GNU statement expression expanded from a macro, it is probably
19106b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner  // unused because it is a function-like macro that can be used as either an
19206b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner  // expression or statement.  Don't warn, because it is almost certainly a
19306b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner  // false positive.
19406b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner  if (isa<StmtExpr>(E) && Loc.isMacroID())
19506b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner    return;
19606b3a06007e02aebe497f34651a4e50b00adb051Chris Lattner
197419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  // Okay, we have an unused result.  Depending on what the base expression is,
198419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  // we might want to make a more specific diagnostic.  Check for one of these
199419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  // cases now.
200419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  unsigned DiagID = diag::warn_unused_expr;
2014765fa05b5652fcc4356371c2f481d0ea9a1b007John McCall  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
2024dffad64c5c7106dc5ac506be94944299c8f7bc3Douglas Gregor    E = Temps->getSubExpr();
20334d49471e0b6386aefdc0f6bd15e4a4876ce5db1Chandler Carruth  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
20434d49471e0b6386aefdc0f6bd15e4a4876ce5db1Chandler Carruth    E = TempExpr->getSubExpr();
20512f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall
206ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth  if (DiagnoseUnusedComparison(*this, E))
207ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth    return;
208ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth
209a6115068cde719142eb394db88612c185cabd05bEli Friedman  E = WarnExpr;
210bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2110faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall    if (E->getType()->isVoidType())
2120faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall      return;
2130faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall
214bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner    // If the callee has attribute pure, const, or warn_unused_result, warn with
2159016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay    // a more specific message to make it clear what is happening. If the call
2169016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay    // is written in a macro body, only warn if it has the warn_unused_result
2179016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay    // attribute.
218d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes    if (const Decl *FD = CE->getCalleeDecl()) {
219bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      if (FD->getAttr<WarnUnusedResultAttr>()) {
22042d7b2d25b6f90dc397886d05502b10ab5a8b51bMatt Beaumont-Gay        Diag(Loc, diag::warn_unused_result) << R1 << R2;
221bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        return;
222bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      }
2239016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay      if (ShouldSuppress)
2249016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay        return;
225bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      if (FD->getAttr<PureAttr>()) {
226bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
227bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        return;
228bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      }
229bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      if (FD->getAttr<ConstAttr>()) {
230bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
231bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        return;
232bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      }
233dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    }
2349016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  } else if (ShouldSuppress)
2359016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay    return;
2369016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay
2379016bb771265a10f188c76342254badecc695253Matt Beaumont-Gay  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2384e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
239f85e193739c953358c865005855253af4f68a497John McCall      Diag(Loc, diag::err_arc_unused_init_message) << R1;
240f85e193739c953358c865005855253af4f68a497John McCall      return;
241f85e193739c953358c865005855253af4f68a497John McCall    }
242f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian    const ObjCMethodDecl *MD = ME->getMethodDecl();
243f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
24442d7b2d25b6f90dc397886d05502b10ab5a8b51bMatt Beaumont-Gay      Diag(Loc, diag::warn_unused_result) << R1 << R2;
245f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian      return;
246f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian    }
247ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
248ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek    const Expr *Source = POE->getSyntacticForm();
249ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek    if (isa<ObjCSubscriptRefExpr>(Source))
250ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek      DiagID = diag::warn_unused_container_subscript_expr;
251ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek    else
252ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek      DiagID = diag::warn_unused_property_expr;
253d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor  } else if (const CXXFunctionalCastExpr *FC
254d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
255d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
256d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
257d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor      return;
258f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian  }
259209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall  // Diagnose "(void*) blah" as a typo for "(void) blah".
260209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
261209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
262209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    QualType T = TI->getType();
263209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall
264209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    // We really do want to use the non-canonical type here.
265209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    if (T == Context.VoidPtrTy) {
26639e6ab4be93d9c5e729a578ddd9d415cd2d49872David Blaikie      PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
267209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall
268209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall      Diag(Loc, diag::warn_unused_voidptr)
269209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall        << FixItHint::CreateRemoval(TL.getStarLoc());
270209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall      return;
271209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    }
272209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall  }
273209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall
274a6115068cde719142eb394db88612c185cabd05bEli Friedman  if (E->isGLValue() && E->getType().isVolatileQualified()) {
275a6115068cde719142eb394db88612c185cabd05bEli Friedman    Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
276a6115068cde719142eb394db88612c185cabd05bEli Friedman    return;
277a6115068cde719142eb394db88612c185cabd05bEli Friedman  }
278a6115068cde719142eb394db88612c185cabd05bEli Friedman
279351ba91eaa6d30e523587b2d7ed676a5172c6e56Ted Kremenek  DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
280636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson}
281636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson
282625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenkovoid Sema::ActOnStartOfCompoundStmt() {
283625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  PushCompoundScope();
284625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko}
285625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
286625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenkovoid Sema::ActOnFinishOfCompoundStmt() {
287625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  PopCompoundScope();
288625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko}
289625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
290625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenkosema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
291625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  return getCurFunction()->CompoundScopes.back();
292625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko}
293625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
29460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2951b273c403734d343d720acb28f04011807c8aa56Steve NaroffSema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
296a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl                        MultiStmtArg elts, bool isStmtExpr) {
297a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl  unsigned NumElts = elts.size();
2985354e77e60e82828c7c2361f5c688c2667ab59ccBenjamin Kramer  Stmt **Elts = elts.data();
299c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner  // If we're in C89 mode, check that we don't have any decls after stmts.  If
300c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner  // so, emit an extension diagnostic.
3014e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
302c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    // Note that __extension__ can be around a decl.
303c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    unsigned i = 0;
304c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    // Skip over all declarations.
305c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
306c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner      /*empty*/;
307c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner
308c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    // We found the end of the list or a statement.  Scan for another declstmt.
309c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
310c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner      /*empty*/;
3111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
312c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    if (i != NumElts) {
3134afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
314c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner      Diag(D->getLocation(), diag::ext_mixed_decls_code);
315c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    }
316c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner  }
31798414c1b7d1944a57156d52e29bd41c005de09acChris Lattner  // Warn about unused expressions in statements.
31898414c1b7d1944a57156d52e29bd41c005de09acChris Lattner  for (unsigned i = 0; i != NumElts; ++i) {
319636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    // Ignore statements that are last in a statement expression.
320636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    if (isStmtExpr && i == NumElts - 1)
32198414c1b7d1944a57156d52e29bd41c005de09acChris Lattner      continue;
3221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
323636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    DiagnoseUnusedExprResult(Elts[i]);
32498414c1b7d1944a57156d52e29bd41c005de09acChris Lattner  }
325a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl
326625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  // Check for suspicious empty body (null statement) in `for' and `while'
327625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  // statements.  Don't do anything for template instantiations, this just adds
328625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  // noise.
329625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  if (NumElts != 0 && !CurrentInstantiationScope &&
330625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko      getCurCompoundScope().HasEmptyLoopBodies) {
331625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    for (unsigned i = 0; i != NumElts - 1; ++i)
332625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko      DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
333625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  }
334625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
335d36aa359e2f45cd22c7366a015ad94de08044dbbNico Weber  return Owned(new (Context) CompoundStmt(Context,
336d36aa359e2f45cd22c7366a015ad94de08044dbbNico Weber                                          llvm::makeArrayRef(Elts, NumElts),
337d36aa359e2f45cd22c7366a015ad94de08044dbbNico Weber                                          L, R));
3385f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
3395f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
34060d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
3419ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3429ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                    SourceLocation DotDotDotLoc, Expr *RHSVal,
34324e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner                    SourceLocation ColonLoc) {
3449ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  assert((LHSVal != 0) && "missing expression in case statement");
345117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
3468ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith  if (getCurFunction()->SwitchStack.empty()) {
3478ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    Diag(CaseLoc, diag::err_case_not_in_switch);
34824e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner    return StmtError();
3498ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith  }
3505f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
35180ad52f327b532bded5c5b0ee38779d841c6cd35Richard Smith  if (!getLangOpts().CPlusPlus11) {
3528ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    // C99 6.8.4.2p3: The expression shall be an integer constant.
3538ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    // However, GCC allows any evaluatable integer expression.
354282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith    if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
355282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
356282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      if (!LHSVal)
357282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith        return StmtError();
358282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith    }
359117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
3608ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    // GCC extension: The expression shall be an integer constant.
361117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
362282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith    if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
363282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
364282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      // Recover from an error by just forgetting about it.
3658ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    }
3668a87e57beb96212ee61dc08a5f691cd7f7710703Chris Lattner  }
367a0152d4e8a602c71ca403172ba0fd025a0b353caBen Langmuir
368ad48a500596d7d678b99c7f94326cfa856c3b49fFariborz Jahanian  LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
369ad48a500596d7d678b99c7f94326cfa856c3b49fFariborz Jahanian                               getLangOpts().CPlusPlus11).take();
370ad48a500596d7d678b99c7f94326cfa856c3b49fFariborz Jahanian  if (RHSVal)
371ad48a500596d7d678b99c7f94326cfa856c3b49fFariborz Jahanian    RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
372ad48a500596d7d678b99c7f94326cfa856c3b49fFariborz Jahanian                                 getLangOpts().CPlusPlus11).take();
3735f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
374dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
375dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                        ColonLoc);
376781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
377117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl  return Owned(CS);
3785f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
3795f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
38024e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner/// ActOnCaseStmtBody - This installs a statement as the body of a case.
3819ae2f076ca5ab1feb3ba95629099ec2319833701John McCallvoid Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
3825440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth  DiagnoseUnusedExprResult(SubStmt);
3835440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth
38424e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
38524e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner  CS->setSubStmt(SubStmt);
38624e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner}
38724e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner
38860d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
3891eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpSema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
3909ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                       Stmt *SubStmt, Scope *CurScope) {
3915440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth  DiagnoseUnusedExprResult(SubStmt);
3925440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth
393781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  if (getCurFunction()->SwitchStack.empty()) {
3940fa152e72bb71c4aa184d0edd91caa9cbebbf70eChris Lattner    Diag(DefaultLoc, diag::err_default_not_in_switch);
395117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl    return Owned(SubStmt);
3960fa152e72bb71c4aa184d0edd91caa9cbebbf70eChris Lattner  }
397117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
398dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
399781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
400117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl  return Owned(DS);
4015f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
4025f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
40360d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
40457ad37823e198f977cac605dbfbaefb4daf325e9Chris LattnerSema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
40557ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                     SourceLocation ColonLoc, Stmt *SubStmt) {
406ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  // If the label was multiply defined, reject it now.
407ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  if (TheDecl->getStmt()) {
408ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
409ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner    Diag(TheDecl->getLocation(), diag::note_previous_definition);
410de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl    return Owned(SubStmt);
4115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
412de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
413ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  // Otherwise, things are good.  Fill in the declaration and return it.
414ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
415ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  TheDecl->setStmt(LS);
416ac7027872b55c43389308b51b36ade04bb50081fAbramo Bagnara  if (!TheDecl->isGnuLocal()) {
417ac7027872b55c43389308b51b36ade04bb50081fAbramo Bagnara    TheDecl->setLocStart(IdentLoc);
418203548ba4b72e7e59320d352afc1eb0b5ab131deAbramo Bagnara    TheDecl->setLocation(IdentLoc);
419ac7027872b55c43389308b51b36ade04bb50081fAbramo Bagnara  }
420ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  return Owned(LS);
4215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
4225f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
423534986f2b21e6050bf00163cd6423fd92155a6edRichard SmithStmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
4244990890fc9428f98bef90ba349203a648c592778Alexander Kornienko                                     ArrayRef<const Attr*> Attrs,
425534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith                                     Stmt *SubStmt) {
4264990890fc9428f98bef90ba349203a648c592778Alexander Kornienko  // Fill in the declaration and return it.
4274990890fc9428f98bef90ba349203a648c592778Alexander Kornienko  AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
428534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith  return Owned(LS);
429534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith}
430534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith
43160d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
432d226f65006733ed7f709c3174f22ce33391cb58fJohn McCallSema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
43344aa1f397855f130e88e62ffc1029f7f83bb5d2eArgyrios Kyrtzidis                  Stmt *thenStmt, SourceLocation ElseLoc,
43444aa1f397855f130e88e62ffc1029f7f83bb5d2eArgyrios Kyrtzidis                  Stmt *elseStmt) {
435820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis  // If the condition was invalid, discard the if statement.  We could recover
436820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis  // better by replacing it with a valid expr, but don't do that yet.
437820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis  if (!CondVal.get() && !CondVar) {
438820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis    getCurFunction()->setHasDroppedStmt();
439820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis    return StmtError();
440820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis  }
441820b23dc924a4ae7af07d5a75d6b1d781c267d57Argyrios Kyrtzidis
44260d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult CondResult(CondVal.release());
4431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4448cfe5a784133d90bf329fd20801824a6f71bb8caDouglas Gregor  VarDecl *ConditionVar = 0;
445d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (CondVar) {
446d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(CondVar);
447586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
44899e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    if (CondResult.isInvalid())
44999e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor      return StmtError();
4508cfe5a784133d90bf329fd20801824a6f71bb8caDouglas Gregor  }
45199e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  Expr *ConditionExpr = CondResult.takeAs<Expr>();
45299e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  if (!ConditionExpr)
45399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    return StmtError();
454dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
455754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  DiagnoseUnusedExprResult(thenStmt);
4565f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
4579ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (!elseStmt) {
458625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
459625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko                          diag::warn_empty_if_body);
4602d85f8ba62fd6fdcf0ae303d77112b413d412caeAnders Carlsson  }
4612d85f8ba62fd6fdcf0ae303d77112b413d412caeAnders Carlsson
462754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  DiagnoseUnusedExprResult(elseStmt);
4631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
464dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
46544aa1f397855f130e88e62ffc1029f7f83bb5d2eArgyrios Kyrtzidis                                    thenStmt, ElseLoc, elseStmt));
4665f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
4675f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
468f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
469f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner/// the specified width and sign.  If an overflow occurs, detect it and emit
470f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner/// the specified diagnostic.
471f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattnervoid Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
472f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner                                              unsigned NewWidth, bool NewSign,
4731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              SourceLocation Loc,
474f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner                                              unsigned DiagID) {
475f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Perform a conversion to the promoted condition type if needed.
476f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  if (NewWidth > Val.getBitWidth()) {
477f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // If this is an extension, just do it.
4789f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.extend(NewWidth);
479f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    Val.setIsSigned(NewSign);
480f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor
481f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // If the input was signed and negative and the output is
482f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // unsigned, don't bother to warn: this is implementation-defined
483f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // behavior.
484f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // FIXME: Introduce a second, default-ignored warning for this case?
485f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  } else if (NewWidth < Val.getBitWidth()) {
486f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // If this is a truncation, check for overflow.
487f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    llvm::APSInt ConvVal(Val);
4889f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    ConvVal = ConvVal.trunc(NewWidth);
489b2137ae3f1bd0aadb0552189af2824a324ffaa69Chris Lattner    ConvVal.setIsSigned(NewSign);
4909f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    ConvVal = ConvVal.extend(Val.getBitWidth());
491b2137ae3f1bd0aadb0552189af2824a324ffaa69Chris Lattner    ConvVal.setIsSigned(Val.isSigned());
492f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    if (ConvVal != Val)
493d3a94e24ddf3fb90de76b17bd176d9ed61e66f2cChris Lattner      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
4941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
495f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // Regardless of whether a diagnostic was emitted, really do the
496f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // truncation.
4979f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.trunc(NewWidth);
498b2137ae3f1bd0aadb0552189af2824a324ffaa69Chris Lattner    Val.setIsSigned(NewSign);
499f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  } else if (NewSign != Val.isSigned()) {
500f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // Convert the sign to match the sign of the condition.  This can cause
501f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // overflow as well: unsigned(INTMIN)
502dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    // We don't diagnose this overflow, because it is implementation-defined
5032853eac24e2e70a74d7da817653b0528b976039fDouglas Gregor    // behavior.
5042853eac24e2e70a74d7da817653b0528b976039fDouglas Gregor    // FIXME: Introduce a second, default-ignored warning for this case?
505f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    llvm::APSInt OldVal(Val);
506f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    Val.setIsSigned(NewSign);
507f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  }
508f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner}
509f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner
5100471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattnernamespace {
5110471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner  struct CaseCompareFunctor {
5120471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
5130471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner                    const llvm::APSInt &RHS) {
5140471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      return LHS.first < RHS;
5150471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    }
5160e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
5170e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
5180e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner      return LHS.first < RHS.first;
5190e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner    }
5200471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    bool operator()(const llvm::APSInt &LHS,
5210471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
5220471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      return LHS < RHS.first;
5230471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    }
5240471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner  };
5250471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner}
5260471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner
527764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner/// CmpCaseVals - Comparison predicate for sorting case values.
528764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner///
529764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattnerstatic bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
530764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
531764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner  if (lhs.first < rhs.first)
532764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner    return true;
533764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner
534764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner  if (lhs.first == rhs.first &&
535764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner      lhs.second->getCaseLoc().getRawEncoding()
536764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner       < rhs.second->getCaseLoc().getRawEncoding())
537764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner    return true;
538764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner  return false;
539764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner}
540764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner
541ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor/// CmpEnumVals - Comparison predicate for sorting enumeration values.
542ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor///
543ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregorstatic bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
544ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
545ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor{
546ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  return lhs.first < rhs.first;
547ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor}
548ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
549ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor/// EqEnumVals - Comparison preficate for uniqing enumeration values.
550ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor///
551ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregorstatic bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
552ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
553ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor{
554ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  return lhs.first == rhs.first;
555ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor}
556ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
5575f04881eb025f61396d0555d8173730fe2759e0aChris Lattner/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
5585f04881eb025f61396d0555d8173730fe2759e0aChris Lattner/// potentially integral-promoted expression @p expr.
559a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCallstatic QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
560a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
561a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall    expr = cleanups->getSubExpr();
562a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
563a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall    if (impcast->getCastKind() != CK_IntegralCast) break;
564a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall    expr = impcast->getSubExpr();
5655f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  }
5665f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  return expr->getType();
5675f04881eb025f61396d0555d8173730fe2759e0aChris Lattner}
5685f04881eb025f61396d0555d8173730fe2759e0aChris Lattner
56960d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
570dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
571d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall                             Decl *CondVar) {
57260d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult CondResult;
5739ae2f076ca5ab1feb3ba95629099ec2319833701John McCall
574586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  VarDecl *ConditionVar = 0;
575d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (CondVar) {
576d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(CondVar);
5779ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
5789ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    if (CondResult.isInvalid())
579586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor      return StmtError();
580dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
5819ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    Cond = CondResult.release();
582586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  }
583dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
5849ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (!Cond)
585586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    return StmtError();
586dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
587ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor  class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
588ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    Expr *Cond;
5898e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
590ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor  public:
591ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    SwitchConvertDiagnoser(Expr *Cond)
592097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith        : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
593097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith          Cond(Cond) {}
5948e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
595097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
596097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith                                                 QualType T) {
597ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
598ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
5998e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
600097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder diagnoseIncomplete(
601097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith        Sema &S, SourceLocation Loc, QualType T) {
602ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      return S.Diag(Loc, diag::err_switch_incomplete_class_type)
603ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor               << T << Cond->getSourceRange();
604ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
6058e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
606097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder diagnoseExplicitConv(
607097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
608ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
609ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
6108e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
611097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder noteExplicitConv(
612097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith        Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
613ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
614ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor        << ConvTy->isEnumeralType() << ConvTy;
615ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
6168e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
617097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
618097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith                                                    QualType T) {
619ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
620ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
6218e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
622097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder noteAmbiguous(
623097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith        Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
624ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
625ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor      << ConvTy->isEnumeralType() << ConvTy;
626ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
6278e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
628097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith    virtual SemaDiagnosticBuilder diagnoseConversion(
629097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
630097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith      llvm_unreachable("conversion functions are permitted");
631ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor    }
632ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor  } SwitchDiagnoser(Cond);
633ab41fe914f63bb470dfa7e400876ada72f57a931Douglas Gregor
634097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith  CondResult =
635097e0a2cb08c8244a6923489acc8f890e6a99b59Richard Smith      PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
6369ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (CondResult.isInvalid()) return StmtError();
6379ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Cond = CondResult.take();
638dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
639a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
640a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  CondResult = UsualUnaryConversions(Cond);
641a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  if (CondResult.isInvalid()) return StmtError();
642a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  Cond = CondResult.take();
643a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall
644d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (!CondVar) {
645419563768ef4929a622d7c2b066856e82901bb91Richard Smith    CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
6469ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    if (CondResult.isInvalid())
647586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor      return StmtError();
6489ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    Cond = CondResult.take();
649586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  }
650b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
651781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasBranchIntoScope();
652dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
6539ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
654781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.push_back(SS);
655586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  return Owned(SS);
6567e52de4b45286d057b367bb1f9283a1e32d79252Chris Lattner}
6577e52de4b45286d057b367bb1f9283a1e32d79252Chris Lattner
65828164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greifstatic void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
65928164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif  if (Val.getBitWidth() < BitWidth)
6609f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.extend(BitWidth);
66128164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif  else if (Val.getBitWidth() > BitWidth)
6629f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.trunc(BitWidth);
66328164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif  Val.setIsSigned(IsSigned);
66428164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif}
66528164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif
66660d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
6679ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
6689ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                            Stmt *BodyStmt) {
6699ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  SwitchStmt *SS = cast<SwitchStmt>(Switch);
670781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  assert(SS == getCurFunction()->SwitchStack.back() &&
671781472fe99a120098c631b0cbe33c89f8cef5e70John McCall         "switch stack missing push/pop!");
672de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
6739dcbfa450d751bd68fc4af8b75da381d4f6984b9Steve Naroff  SS->setBody(BodyStmt, SwitchLoc);
674781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.pop_back();
675c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson
676f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  Expr *CondExpr = SS->getCond();
677a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  if (!CondExpr) return StmtError();
678de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
679a0d3ca1ea5578bc736bb71bcec50ab41fefc87b9Douglas Gregor  QualType CondType = CondExpr->getType();
680a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall
681a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  Expr *CondExprBeforePromotion = CondExpr;
682a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  QualType CondTypeBeforePromotion =
683a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall      GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
68484fb9c0be621c9e4ca4e56f67dae2a0bb6e44821Douglas Gregor
6855f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // C++ 6.4.2.p2:
6865f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // Integral promotions are performed (on the switch condition).
6875f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  //
6885f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // A case value unrepresentable by the original switch condition
6895f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // type (before the promotion) doesn't make sense, even when it can
6905f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // be represented by the promoted type.  Therefore we need to find
6915f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // the pre-promotion type of the switch condition.
69212356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan  if (!CondExpr->isTypeDependent()) {
693acb0bd85d30ecacbe872ca9d9cfac5d7b6038a43Douglas Gregor    // We have already converted the expression to an integral or enumeration
694dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    // type, when we started the switch statement. If we don't have an
695acb0bd85d30ecacbe872ca9d9cfac5d7b6038a43Douglas Gregor    // appropriate type now, just return an error.
696acb0bd85d30ecacbe872ca9d9cfac5d7b6038a43Douglas Gregor    if (!CondType->isIntegralOrEnumerationType())
69712356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      return StmtError();
69812356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan
6992b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner    if (CondExpr->isKnownToHaveBooleanValue()) {
70012356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      // switch(bool_expr) {...} is often a programmer error, e.g.
70112356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
70212356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      // One can always use an if statement instead of switch(bool_expr).
70312356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      Diag(SwitchLoc, diag::warn_bool_switch_condition)
70412356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan          << CondExpr->getSourceRange();
70512356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan    }
706c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson  }
707de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
708f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Get the bitwidth of the switched-on value before promotions.  We must
709f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // convert the integer case values to this width before comparison.
7101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  bool HasDependentValue
711dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
7121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  unsigned CondWidth
7131d6ab7af99a1fc059a6aa5da083640c1d94b07f7Chris Lattner    = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
7141093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  bool CondIsSigned
715575a1c9dc8dc5b4977194993e289f9eda7295c39Douglas Gregor    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
7161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
717f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Accumulate all of the case values in a vector so that we can sort them
718f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // and detect duplicates.  This vector contains the APInt for the case after
719f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // it has been converted to the condition type.
7205f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
7210471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner  CaseValsTy CaseVals;
7221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
723f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
724ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
725ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  CaseRangesTy CaseRanges;
7261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
727f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  DefaultStmt *TheDefaultStmt = 0;
7281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
729b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner  bool CaseListIsErroneous = false;
7301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
731dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
732c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson       SC = SC->getNextSwitchCase()) {
7331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
734c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
735f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      if (TheDefaultStmt) {
736f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
7375f4a6829dc58cab2f76e2b98492859aa3b91e3f2Chris Lattner        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
738de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
739f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner        // FIXME: Remove the default statement from the switch block so that
740390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump        // we'll return a valid AST.  This requires recursing down the AST and
741390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump        // finding it, not something we are set up to do right now.  For now,
742390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump        // just lop the entire switch stmt out of the AST.
743b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner        CaseListIsErroneous = true;
744c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson      }
745f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      TheDefaultStmt = DS;
7461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
747f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    } else {
748f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      CaseStmt *CS = cast<CaseStmt>(SC);
7491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7501e0a39012467b4f409142c32148036a9ee05e1d7Chris Lattner      Expr *Lo = CS->getLHS();
751dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor
752dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
753dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        HasDependentValue = true;
754dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        break;
755dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      }
7561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7578ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      llvm::APSInt LoVal;
7581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
75980ad52f327b532bded5c5b0ee38779d841c6cd35Richard Smith      if (getLangOpts().CPlusPlus11) {
7608ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // C++11 [stmt.switch]p2: the constant-expression shall be a converted
7618ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // constant expression of the promoted type of the switch condition.
7628ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        ExprResult ConvLo =
7638ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
7648ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        if (ConvLo.isInvalid()) {
7658ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          CaseListIsErroneous = true;
7668ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          continue;
7678ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        }
7688ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        Lo = ConvLo.take();
7698ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      } else {
7708ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // We already verified that the expression has a i-c-e value (C99
7718ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // 6.8.4.2p3) - get that value now.
772ad48a500596d7d678b99c7f94326cfa856c3b49fFariborz Jahanian        LoVal = Lo->EvaluateKnownConstInt(Context);
7738ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
7748ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // If the LHS is not the same type as the condition, insert an implicit
7758ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // cast.
7768ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        Lo = DefaultLvalueConversion(Lo).take();
7778ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
7788ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      }
7798ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
7808ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // Convert the value to the same width/sign as the condition had prior to
7818ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // integral promotions.
7828ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      //
7838ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // FIXME: This causes us to reject valid code:
7848ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      //   switch ((char)c) { case 256: case 0: return 0; }
7858ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // Here we claim there is a duplicated condition value, but there is not.
786f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
78728164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif                                         Lo->getLocStart(),
788f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner                                         diag::warn_case_value_overflow);
7896c36be5b383875b490684bcf439d6d427298c1afChris Lattner
7901e0a39012467b4f409142c32148036a9ee05e1d7Chris Lattner      CS->setLHS(Lo);
7911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
792b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
793dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      if (CS->getRHS()) {
7941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        if (CS->getRHS()->isTypeDependent() ||
795dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor            CS->getRHS()->isValueDependent()) {
796dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          HasDependentValue = true;
797dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          break;
798dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
799f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner        CaseRanges.push_back(std::make_pair(LoVal, CS));
8001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      } else
801b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner        CaseVals.push_back(std::make_pair(LoVal, CS));
802f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    }
803f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  }
804b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner
805dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  if (!HasDependentValue) {
8060fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // If we don't have a default statement, check whether the
8070fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // condition is constant.
8080fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    llvm::APSInt ConstantCondValue;
8090fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    bool HasConstantCond = false;
8100fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    if (!HasDependentValue && !TheDefaultStmt) {
81151f4708c00110940ca3f337961915f2ca1668375Richard Smith      HasConstantCond
81280d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith        = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
81380d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith                                                 Expr::SE_AllowSideEffects);
81480d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith      assert(!HasConstantCond ||
81580d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith             (ConstantCondValue.getBitWidth() == CondWidth &&
81680d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith              ConstantCondValue.isSigned() == CondIsSigned));
8170fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    }
81880d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith    bool ShouldCheckConstantCond = HasConstantCond;
8190fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
820dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    // Sort all the scalar case values so we can easily detect duplicates.
821dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
822dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor
823dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    if (!CaseVals.empty()) {
8240fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
8250fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (ShouldCheckConstantCond &&
8260fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall            CaseVals[i].first == ConstantCondValue)
8270fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall          ShouldCheckConstantCond = false;
8280fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
8290fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
830dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          // If we have a duplicate, report it.
8313940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          // First, determine if either case value has a name
8323940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          StringRef PrevString, CurrString;
8333940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
8343940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
8353940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
8363940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor            PrevString = DeclRef->getDecl()->getName();
8373940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          }
8383940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
8393940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor            CurrString = DeclRef->getDecl()->getName();
8403940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          }
841cfa88f893915ceb8ae4ce2f17c46c24a4d67502fDmitri Gribenko          SmallString<16> CaseValStr;
84250de5e3247a20e0e548dc47022a011250e6e4e8fDouglas Gregor          CaseVals[i-1].first.toString(CaseValStr);
8433940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor
8443940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          if (PrevString == CurrString)
8453940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor            Diag(CaseVals[i].second->getLHS()->getLocStart(),
8463940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor                 diag::err_duplicate_case) <<
84750de5e3247a20e0e548dc47022a011250e6e4e8fDouglas Gregor                 (PrevString.empty() ? CaseValStr.str() : PrevString);
8483940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor          else
8493940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor            Diag(CaseVals[i].second->getLHS()->getLocStart(),
8503940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor                 diag::err_duplicate_case_differing_expr) <<
85150de5e3247a20e0e548dc47022a011250e6e4e8fDouglas Gregor                 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
85250de5e3247a20e0e548dc47022a011250e6e4e8fDouglas Gregor                 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
8533940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor                 CaseValStr;
8543940ce83438e2332ba541f4e65e700fbefe0c7a8Douglas Gregor
8550fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
856dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor               diag::note_duplicate_case_prev);
857390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // FIXME: We really want to remove the bogus case stmt from the
858390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // substmt, but we have no way to do this right now.
859dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          CaseListIsErroneous = true;
860dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
8616efc4d3659632ddcea4a58cb62e9ee54ca4a373eChris Lattner      }
862b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner    }
8631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
864dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    // Detect duplicate case ranges, which usually don't exist at all in
865dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    // the first place.
866dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    if (!CaseRanges.empty()) {
867dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // Sort all the case ranges by their low value so we can easily detect
868dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // overlaps between ranges.
869dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
8701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
871dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // Scan the ranges, computing the high values and removing empty ranges.
872dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      std::vector<llvm::APSInt> HiVals;
873dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
8740fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        llvm::APSInt &LoVal = CaseRanges[i].first;
875dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseStmt *CR = CaseRanges[i].second;
876dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        Expr *Hi = CR->getRHS();
8778ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        llvm::APSInt HiVal;
8788ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
87980ad52f327b532bded5c5b0ee38779d841c6cd35Richard Smith        if (getLangOpts().CPlusPlus11) {
8808ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // C++11 [stmt.switch]p2: the constant-expression shall be a converted
8818ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // constant expression of the promoted type of the switch condition.
8828ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          ExprResult ConvHi =
8838ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith            CheckConvertedConstantExpression(Hi, CondType, HiVal,
8848ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith                                             CCEK_CaseValue);
8858ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          if (ConvHi.isInvalid()) {
8868ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith            CaseListIsErroneous = true;
8878ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith            continue;
8888ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          }
8898ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          Hi = ConvHi.take();
8908ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        } else {
8918ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          HiVal = Hi->EvaluateKnownConstInt(Context);
8928ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
8938ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // If the RHS is not the same type as the condition, insert an
8948ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // implicit cast.
8958ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          Hi = DefaultLvalueConversion(Hi).take();
8968ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
8978ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        }
8981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
899dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Convert the value to the same width/sign as the condition.
900dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
90128164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif                                           Hi->getLocStart(),
902dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                           diag::warn_case_value_overflow);
9031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
904dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CR->setRHS(Hi);
9051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
906dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // If the low value is bigger than the high value, the case is empty.
9070fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (LoVal > HiVal) {
908dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
909dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor            << SourceRange(CR->getLHS()->getLocStart(),
91028164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif                           Hi->getLocEnd());
911dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          CaseRanges.erase(CaseRanges.begin()+i);
912dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          --i, --e;
913dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          continue;
914dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
9150fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
9160fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (ShouldCheckConstantCond &&
9170fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall            LoVal <= ConstantCondValue &&
9180fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall            ConstantCondValue <= HiVal)
9190fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall          ShouldCheckConstantCond = false;
9200fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
921dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        HiVals.push_back(HiVal);
9220471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      }
9231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
924dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // Rescan the ranges, looking for overlap with singleton values and other
925dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // ranges.  Since the range list is sorted, we only need to compare case
926dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // ranges with their neighbors.
927dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
928dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        llvm::APSInt &CRLo = CaseRanges[i].first;
929dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        llvm::APSInt &CRHi = HiVals[i];
930dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseStmt *CR = CaseRanges[i].second;
9311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
932dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Check to see whether the case range overlaps with any
933dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // singleton cases.
934dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseStmt *OverlapStmt = 0;
935dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        llvm::APSInt OverlapVal(32);
9361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
937dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Find the smallest value >= the lower bound.  If I is in the
938dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // case range, then we have overlap.
939dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
940dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                                  CaseVals.end(), CRLo,
941dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                                  CaseCompareFunctor());
942dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (I != CaseVals.end() && I->first < CRHi) {
943dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapVal  = I->first;   // Found overlap with scalar.
944dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapStmt = I->second;
945dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
9461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
947dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Find the smallest value bigger than the upper bound.
948dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
949dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
950dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
951dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapStmt = (I-1)->second;
952dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
9531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
954dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Check to see if this case stmt overlaps with the subsequent
955dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // case range.
956dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (i && CRLo <= HiVals[i-1]) {
957dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapVal  = HiVals[i-1];       // Found overlap with range.
958dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapStmt = CaseRanges[i-1].second;
959dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
9601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
961dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (OverlapStmt) {
962dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          // If we have a duplicate, report it.
963dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
964dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor            << OverlapVal.toString(10);
9651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Diag(OverlapStmt->getLHS()->getLocStart(),
966dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor               diag::note_duplicate_case_prev);
967390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // FIXME: We really want to remove the bogus case stmt from the
968390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // substmt, but we have no way to do this right now.
969dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          CaseListIsErroneous = true;
970dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
9710471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      }
972b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner    }
973ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
9740fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // Complain if we have a constant condition and we didn't find a match.
9750fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
9760fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // TODO: it would be nice if we printed enums as enums, chars as
9770fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // chars, etc.
9780fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
9790fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        << ConstantCondValue.toString(10)
9800fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        << CondExpr->getSourceRange();
9810fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    }
9820fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
9830fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // Check to see if switch is over an Enum and handles all of its
984559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    // values.  We only issue a warning if there is not 'default:', but
985559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    // we still do the analysis to preserve this information in the AST
986559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    // (which can be used by flow-based analyes).
9870fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    //
988ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
989559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
990ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor    // If switch has default case, then ignore it.
991559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
992ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      const EnumDecl *ED = ET->getDecl();
9935f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
99458f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet        EnumValsTy;
995ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      EnumValsTy EnumVals;
996ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
9970fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // Gather all enum values, set their type and sort them,
9980fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // allowing easier comparison with CaseVals.
9990fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
100028164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif           EDI != ED->enumerator_end(); ++EDI) {
100128164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif        llvm::APSInt Val = EDI->getInitVal();
100228164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif        AdjustAPSInt(Val, CondWidth, CondIsSigned);
1003581deb3da481053c4993c7600f97acf7768caac5David Blaikie        EnumVals.push_back(std::make_pair(Val, *EDI));
1004ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      }
1005ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
10060fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      EnumValsTy::iterator EIend =
10070fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1008559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
1009559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      // See which case values aren't in enum.
10109366750a5a97c8aeae1df4898ea849b087865195David Blaikie      EnumValsTy::const_iterator EI = EnumVals.begin();
10119366750a5a97c8aeae1df4898ea849b087865195David Blaikie      for (CaseValsTy::const_iterator CI = CaseVals.begin();
10129366750a5a97c8aeae1df4898ea849b087865195David Blaikie           CI != CaseVals.end(); CI++) {
10139366750a5a97c8aeae1df4898ea849b087865195David Blaikie        while (EI != EIend && EI->first < CI->first)
10149366750a5a97c8aeae1df4898ea849b087865195David Blaikie          EI++;
10159366750a5a97c8aeae1df4898ea849b087865195David Blaikie        if (EI == EIend || EI->first > CI->first)
10169366750a5a97c8aeae1df4898ea849b087865195David Blaikie          Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
101754faba4f7f3f0e8f1376da1c459312596ad5486dFariborz Jahanian            << CondTypeBeforePromotion;
10189366750a5a97c8aeae1df4898ea849b087865195David Blaikie      }
10199366750a5a97c8aeae1df4898ea849b087865195David Blaikie      // See which of case ranges aren't in enum
10209366750a5a97c8aeae1df4898ea849b087865195David Blaikie      EI = EnumVals.begin();
10219366750a5a97c8aeae1df4898ea849b087865195David Blaikie      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
10229366750a5a97c8aeae1df4898ea849b087865195David Blaikie           RI != CaseRanges.end() && EI != EIend; RI++) {
10239366750a5a97c8aeae1df4898ea849b087865195David Blaikie        while (EI != EIend && EI->first < RI->first)
10249366750a5a97c8aeae1df4898ea849b087865195David Blaikie          EI++;
10259366750a5a97c8aeae1df4898ea849b087865195David Blaikie
10269366750a5a97c8aeae1df4898ea849b087865195David Blaikie        if (EI == EIend || EI->first != RI->first) {
10279366750a5a97c8aeae1df4898ea849b087865195David Blaikie          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
102854faba4f7f3f0e8f1376da1c459312596ad5486dFariborz Jahanian            << CondTypeBeforePromotion;
102947bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek        }
1030e0ba9d1beeba01a96808c2fc61f9ca89acec313bTed Kremenek
10311093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier        llvm::APSInt Hi =
10329366750a5a97c8aeae1df4898ea849b087865195David Blaikie          RI->second->getRHS()->EvaluateKnownConstInt(Context);
10339366750a5a97c8aeae1df4898ea849b087865195David Blaikie        AdjustAPSInt(Hi, CondWidth, CondIsSigned);
10349366750a5a97c8aeae1df4898ea849b087865195David Blaikie        while (EI != EIend && EI->first < Hi)
10359366750a5a97c8aeae1df4898ea849b087865195David Blaikie          EI++;
10369366750a5a97c8aeae1df4898ea849b087865195David Blaikie        if (EI == EIend || EI->first != Hi)
10379366750a5a97c8aeae1df4898ea849b087865195David Blaikie          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
103854faba4f7f3f0e8f1376da1c459312596ad5486dFariborz Jahanian            << CondTypeBeforePromotion;
1039ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      }
1040dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1041559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      // Check which enum vals aren't in switch
1042ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      CaseValsTy::const_iterator CI = CaseVals.begin();
1043ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      CaseRangesTy::const_iterator RI = CaseRanges.begin();
1044559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      bool hasCasesNotInSwitch = false;
1045559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
10465f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      SmallVector<DeclarationName,8> UnhandledNames;
1047dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
10489366750a5a97c8aeae1df4898ea849b087865195David Blaikie      for (EI = EnumVals.begin(); EI != EIend; EI++){
1049ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        // Drop unneeded case values
1050ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        llvm::APSInt CIVal;
1051ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        while (CI != CaseVals.end() && CI->first < EI->first)
1052ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor          CI++;
1053dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1054ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        if (CI != CaseVals.end() && CI->first == EI->first)
1055ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor          continue;
1056ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
1057559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek        // Drop unneeded case ranges
1058ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        for (; RI != CaseRanges.end(); RI++) {
1059a6b8b2c09610b8bc4330e948ece8b940c2386406Richard Smith          llvm::APSInt Hi =
1060a6b8b2c09610b8bc4330e948ece8b940c2386406Richard Smith            RI->second->getRHS()->EvaluateKnownConstInt(Context);
106128164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1062ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor          if (EI->first <= Hi)
1063ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor            break;
1064ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        }
1065ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
1066559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek        if (RI == CaseRanges.end() || EI->first < RI->first) {
106747bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek          hasCasesNotInSwitch = true;
106831ceb61172bca7ebc3fb90e9125864c7a29c55c0David Blaikie          UnhandledNames.push_back(EI->second->getDeclName());
106947bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek        }
1070ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      }
1071dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1072585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie      if (TheDefaultStmt && UnhandledNames.empty())
1073585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
107431ceb61172bca7ebc3fb90e9125864c7a29c55c0David Blaikie
1075ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      // Produce a nice diagnostic if multiple values aren't handled.
1076ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      switch (UnhandledNames.size()) {
1077ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 0: break;
1078ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 1:
10791093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1080585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1081ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0];
1082ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
1083ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 2:
10841093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1085585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1086ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0] << UnhandledNames[1];
1087ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
1088ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 3:
1089585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1090585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1091ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1092ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
1093ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      default:
1094585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1095585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1096ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << (unsigned)UnhandledNames.size()
1097ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1098ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
1099ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      }
1100559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
1101559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      if (!hasCasesNotInSwitch)
110247bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek        SS->setAllEnumCasesCovered();
1103ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor    }
1104b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner  }
1105dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor
1106625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1107625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko                        diag::warn_empty_switch_body);
1108625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
1109390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump  // FIXME: If the case list was broken is some way, we don't have a good system
1110390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump  // to patch it up.  Instead, just return the whole substmt as broken.
1111b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner  if (CaseListIsErroneous)
1112de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl    return StmtError();
1113de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
1114de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl  return Owned(SS);
11155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
11165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1117379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanianvoid
1118379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz JahanianSema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1119379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian                             Expr *SrcExpr) {
112048a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly  if (Diags.getDiagnosticLevel(diag::warn_not_in_enum_assignment,
112148a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly                               SrcExpr->getExprLoc()) ==
112248a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly      DiagnosticsEngine::Ignored)
1123379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian    return;
11241093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
1125379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian  if (const EnumType *ET = DstType->getAs<EnumType>())
1126379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian    if (!Context.hasSameType(SrcType, DstType) &&
1127379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        SrcType->isIntegerType()) {
1128379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian      if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1129379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian          SrcExpr->isIntegerConstantExpr(Context)) {
1130379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        // Get the bitwidth of the enum value before promotions.
113148a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly        unsigned DstWidth = Context.getIntWidth(DstType);
1132379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1133379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian
1134379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
113548a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly        AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1136379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        const EnumDecl *ED = ET->getDecl();
113748a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly        typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
113848a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly            EnumValsTy;
1139379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        EnumValsTy EnumVals;
11401093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
1141379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        // Gather all enum values, set their type and sort them,
1142379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        // allowing easier comparison with rhs constant.
1143379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1144379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian             EDI != ED->enumerator_end(); ++EDI) {
1145379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian          llvm::APSInt Val = EDI->getInitVal();
114648a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly          AdjustAPSInt(Val, DstWidth, DstIsSigned);
1147379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian          EnumVals.push_back(std::make_pair(Val, *EDI));
1148379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        }
1149379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        if (EnumVals.empty())
1150379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian          return;
1151379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1152379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        EnumValsTy::iterator EIend =
115348a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly            std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
11541093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
115548a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly        // See which values aren't in the enum.
1156379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        EnumValsTy::const_iterator EI = EnumVals.begin();
1157379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        while (EI != EIend && EI->first < RhsVal)
1158379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian          EI++;
1159379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        if (EI == EIend || EI->first != RhsVal) {
116048a1e81715bf9c37a4168d83f4218e6517e29541Joey Gouly          Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1161379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian          << DstType;
1162379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian        }
1163379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian      }
1164379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian    }
1165379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian}
1166379b28183a7dcb715c3f3eb2da4b0157d6d8ffbeFariborz Jahanian
116760d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
1168dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
11699ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                     Decl *CondVar, Stmt *Body) {
117060d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult CondResult(Cond.release());
1171dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
11725656e14d91405417182171a705ed3e3d2d6d7aa3Douglas Gregor  VarDecl *ConditionVar = 0;
1173d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (CondVar) {
1174d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(CondVar);
1175586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
117699e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    if (CondResult.isInvalid())
117799e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor      return StmtError();
11785656e14d91405417182171a705ed3e3d2d6d7aa3Douglas Gregor  }
11799ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Expr *ConditionExpr = CondResult.take();
118099e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  if (!ConditionExpr)
118199e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    return StmtError();
1182dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
11839ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  DiagnoseUnusedExprResult(Body);
11841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1185625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  if (isa<NullStmt>(Body))
1186625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    getCurCompoundScope().setHasEmptyLoopBodies();
1187625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
118843dec6bbde2d0a16c35978983761c8b7030c8e18Douglas Gregor  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
11899ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                       Body, WhileLoc));
11905f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
11915f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
119260d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
11939ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1194989135901c750af61ef012b6b0a0368be415bc46Chris Lattner                  SourceLocation WhileLoc, SourceLocation CondLParen,
11959ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                  Expr *Cond, SourceLocation CondRParen) {
11969ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  assert(Cond && "ActOnDoStmt(): missing expression");
1197f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl
1198429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1199898a7a298185c53a36e923f86fe3f938ebfea67fDmitri Gribenko  if (CondResult.isInvalid())
12005a881bb09928b7ade891efc680088aaad276f8d6John McCall    return StmtError();
1201429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley  Cond = CondResult.take();
12025f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1203419563768ef4929a622d7c2b066856e82901bb91Richard Smith  CondResult = ActOnFinishFullExpr(Cond, DoLoc);
12049ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (CondResult.isInvalid())
1205586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    return StmtError();
12069ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Cond = CondResult.take();
1207dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
12089ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  DiagnoseUnusedExprResult(Body);
1209754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson
12109ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
12115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
12125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1213694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieunamespace {
1214694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  // This visitor will traverse a conditional statement and store all
1215694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  // the evaluated decls into a vector.  Simple is set to true if none
1216694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  // of the excluded constructs are used.
1217694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1218694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1219ad5b69da4774a4eec09af96af23a2fe793fd00f8Craig Topper    SmallVectorImpl<SourceRange> &Ranges;
1220694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    bool Simple;
1221923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu  public:
1222923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1223694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1224923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1225ad5b69da4774a4eec09af96af23a2fe793fd00f8Craig Topper                  SmallVectorImpl<SourceRange> &Ranges) :
1226923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Inherited(S.Context),
1227923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Decls(Decls),
1228923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Ranges(Ranges),
1229923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Simple(true) {}
1230694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1231923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    bool isSimple() { return Simple; }
1232694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1233923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    // Replaces the method in EvaluatedExprVisitor.
1234923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitMemberExpr(MemberExpr* E) {
1235923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Simple = false;
1236923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1237694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1238923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    // Any Stmt not whitelisted will cause the condition to be marked complex.
1239923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitStmt(Stmt *S) {
1240923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Simple = false;
1241923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1242694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1243923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitBinaryOperator(BinaryOperator *E) {
1244923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getLHS());
1245923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getRHS());
1246923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1247694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1248923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitCastExpr(CastExpr *E) {
1249694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      Visit(E->getSubExpr());
1250923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1251694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1252923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitUnaryOperator(UnaryOperator *E) {
1253923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      // Skip checking conditionals with derefernces.
1254923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (E->getOpcode() == UO_Deref)
1255923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Simple = false;
1256923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      else
1257923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Visit(E->getSubExpr());
1258923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1259694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1260923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitConditionalOperator(ConditionalOperator *E) {
1261923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getCond());
1262923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getTrueExpr());
1263923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getFalseExpr());
1264923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1265694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1266923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitParenExpr(ParenExpr *E) {
1267923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getSubExpr());
1268923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1269694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1270923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1271923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getOpaqueValue()->getSourceExpr());
1272923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E->getFalseExpr());
1273923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1274694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1275923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitIntegerLiteral(IntegerLiteral *E) { }
1276923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitFloatingLiteral(FloatingLiteral *E) { }
1277923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1278923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitCharacterLiteral(CharacterLiteral *E) { }
1279923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitGNUNullExpr(GNUNullExpr *E) { }
1280923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1281694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1282923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitDeclRefExpr(DeclRefExpr *E) {
1283923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1284923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (!VD) return;
1285694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1286923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Ranges.push_back(E->getSourceRange());
1287923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu
1288923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Decls.insert(VD);
1289923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1290694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1291694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  }; // end class DeclExtractor
1292694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1293694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  // DeclMatcher checks to see if the decls are used in a non-evauluated
12941093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  // context.
1295694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1296694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1297694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    bool FoundDecl;
1298694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1299923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu  public:
1300923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1301694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1302923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1303923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu                Stmt *Statement) :
1304923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1305923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (!Statement) return;
1306694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1307923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(Statement);
1308923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1309694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1310923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitReturnStmt(ReturnStmt *S) {
1311923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      FoundDecl = true;
1312923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1313694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1314923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitBreakStmt(BreakStmt *S) {
1315923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      FoundDecl = true;
1316923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1317694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1318923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitGotoStmt(GotoStmt *S) {
1319923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      FoundDecl = true;
1320923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1321694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1322923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitCastExpr(CastExpr *E) {
1323923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (E->getCastKind() == CK_LValueToRValue)
1324923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        CheckLValueToRValueCast(E->getSubExpr());
1325923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      else
1326923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Visit(E->getSubExpr());
1327923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1328694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1329923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void CheckLValueToRValueCast(Expr *E) {
1330923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      E = E->IgnoreParenImpCasts();
1331694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1332923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (isa<DeclRefExpr>(E)) {
1333923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        return;
1334923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      }
1335694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1336923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1337923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        Visit(CO->getCond());
1338923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        CheckLValueToRValueCast(CO->getTrueExpr());
1339923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        CheckLValueToRValueCast(CO->getFalseExpr());
1340923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        return;
1341923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      }
1342694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1343923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (BinaryConditionalOperator *BCO =
1344923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu              dyn_cast<BinaryConditionalOperator>(E)) {
1345923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1346923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        CheckLValueToRValueCast(BCO->getFalseExpr());
1347923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        return;
1348923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      }
1349694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1350923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      Visit(E);
1351923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1352694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1353923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    void VisitDeclRefExpr(DeclRefExpr *E) {
1354923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu      if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1355923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu        if (Decls.count(VD))
1356923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu          FoundDecl = true;
1357923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    }
1358694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1359923cadadd2662827ce9029f72d399cf22c443ff9Richard Trieu    bool FoundDeclInUse() { return FoundDecl; }
1360694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1361694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  };  // end class DeclMatcher
1362694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1363694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1364694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu                                        Expr *Third, Stmt *Body) {
1365694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    // Condition is empty
1366694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (!Second) return;
1367694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1368694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1369694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu                                   Second->getLocStart())
1370694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu        == DiagnosticsEngine::Ignored)
1371694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      return;
1372694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1373694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1374694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    llvm::SmallPtrSet<VarDecl*, 8> Decls;
1375cfa88f893915ceb8ae4ce2f17c46c24a4d67502fDmitri Gribenko    SmallVector<SourceRange, 10> Ranges;
1376facde171ae4b8926622a1bffa833732a06f1875bBenjamin Kramer    DeclExtractor DE(S, Decls, Ranges);
1377694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    DE.Visit(Second);
1378694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1379694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    // Don't analyze complex conditionals.
1380694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (!DE.isSimple()) return;
1381694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1382694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    // No decls found.
1383694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (Decls.size() == 0) return;
1384694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
13859087599e5ee64ecd30194b3d89f8748ac95c62f7Richard Trieu    // Don't warn on volatile, static, or global variables.
1386694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1387694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu                                                  E = Decls.end();
1388694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu         I != E; ++I)
13899087599e5ee64ecd30194b3d89f8748ac95c62f7Richard Trieu      if ((*I)->getType().isVolatileQualified() ||
13909087599e5ee64ecd30194b3d89f8748ac95c62f7Richard Trieu          (*I)->hasGlobalStorage()) return;
1391694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1392694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1393694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu        DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1394694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu        DeclMatcher(S, Decls, Body).FoundDeclInUse())
1395694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      return;
1396694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1397694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    // Load decl names into diagnostic.
1398694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (Decls.size() > 4)
1399694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      PDiag << 0;
1400694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    else {
1401694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      PDiag << Decls.size();
1402694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1403694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu                                                    E = Decls.end();
1404694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu           I != E; ++I)
1405694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu        PDiag << (*I)->getDeclName();
1406694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    }
1407694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1408694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    // Load SourceRanges into diagnostic if there is room.
1409694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    // Otherwise, load the SourceRange of the conditional expression.
1410694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    if (Ranges.size() <= PartialDiagnostic::MaxArguments)
141109d19efaa147762f84aed55efa7930bb3616a4e5Craig Topper      for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1412cfa88f893915ceb8ae4ce2f17c46c24a4d67502fDmitri Gribenko                                                  E = Ranges.end();
1413694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu           I != E; ++I)
1414694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu        PDiag << *I;
1415694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    else
1416694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu      PDiag << Second->getSourceRange();
1417694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1418694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu    S.Diag(Ranges.begin()->getBegin(), PDiag);
1419694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  }
1420694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
1421acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // If Statement is an incemement or decrement, return true and sets the
1422acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // variables Increment and DRE.
1423acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1424acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu                            DeclRefExpr *&DRE) {
1425acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1426acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      switch (UO->getOpcode()) {
1427acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        default: return false;
1428acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        case UO_PostInc:
1429acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        case UO_PreInc:
1430acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          Increment = true;
1431acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          break;
1432acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        case UO_PostDec:
1433acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        case UO_PreDec:
1434acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          Increment = false;
1435acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          break;
1436acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      }
1437acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1438acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      return DRE;
1439acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    }
1440acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1441acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1442acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      FunctionDecl *FD = Call->getDirectCallee();
1443acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      if (!FD || !FD->isOverloadedOperator()) return false;
1444acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      switch (FD->getOverloadedOperator()) {
1445acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        default: return false;
1446acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        case OO_PlusPlus:
1447acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          Increment = true;
1448acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          break;
1449acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        case OO_MinusMinus:
1450acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          Increment = false;
1451acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu          break;
1452acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      }
1453acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1454acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      return DRE;
1455acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    }
1456acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1457acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    return false;
1458acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  }
1459acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1460acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // A visitor to determine if a continue statement is a subexpression.
1461acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  class ContinueFinder : public EvaluatedExprVisitor<ContinueFinder> {
1462acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    bool Found;
1463acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  public:
1464acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    ContinueFinder(Sema &S, Stmt* Body) :
1465acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        Inherited(S.Context),
1466acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        Found(false) {
1467acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      Visit(Body);
1468acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    }
1469acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1470acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    typedef EvaluatedExprVisitor<ContinueFinder> Inherited;
1471acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1472acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    void VisitContinueStmt(ContinueStmt* E) {
1473acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      Found = true;
1474acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    }
1475acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1476acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    bool ContinueFound() { return Found; }
1477acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1478acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  };  // end class ContinueFinder
1479acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1480acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // Emit a warning when a loop increment/decrement appears twice per loop
1481acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // iteration.  The conditions which trigger this warning are:
1482acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // 1) The last statement in the loop body and the third expression in the
1483acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  //    for loop are both increment or both decrement of the same variable
1484acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  // 2) No continue statements in the loop body.
1485acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1486acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    // Return when there is nothing to check.
1487acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (!Body || !Third) return;
1488acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1489acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (S.Diags.getDiagnosticLevel(diag::warn_redundant_loop_iteration,
1490acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu                                   Third->getLocStart())
1491acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        == DiagnosticsEngine::Ignored)
1492acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu      return;
1493acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1494acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    // Get the last statement from the loop body.
1495acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1496acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (!CS || CS->body_empty()) return;
1497acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    Stmt *LastStmt = CS->body_back();
1498acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (!LastStmt) return;
1499acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1500acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    bool LoopIncrement, LastIncrement;
1501acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    DeclRefExpr *LoopDRE, *LastDRE;
1502acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1503acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1504acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1505acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1506acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    // Check that the two statements are both increments or both decrements
1507acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    // on the same varaible.
1508acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (LoopIncrement != LastIncrement ||
1509acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu        LoopDRE->getDecl() != LastDRE->getDecl()) return;
1510acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1511acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    if (ContinueFinder(S, Body).ContinueFound()) return;
1512acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1513acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1514acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu         << LastDRE->getDecl() << LastIncrement;
1515acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu    S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1516acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu         << LoopIncrement;
1517acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  }
1518acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu
1519694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu} // end namespace
1520694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
152160d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
1522f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian RedlSema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
15239ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                   Stmt *First, FullExprArg second, Decl *secondVar,
152499e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor                   FullExprArg third,
15259ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                   SourceLocation RParenLoc, Stmt *Body) {
15264e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().CPlusPlus) {
15275921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1528f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1529f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // declare identifiers for objects having storage class 'auto' or
1530f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // 'register'.
15315921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
15325921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis           DI!=DE; ++DI) {
15335921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis        VarDecl *VD = dyn_cast<VarDecl>(*DI);
1534b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall        if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
15355921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis          VD = 0;
153612849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor        if (VD == 0) {
153712849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor          Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
153812849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor          (*DI)->setInvalidDecl();
153912849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor        }
15405921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis      }
1541ae3b701f59e78e058b83344be17206af3bf5d277Chris Lattner    }
15425f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
154399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor
1544694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu  CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1545acdbbc7811c6045a718669a8a0740488edbbbd66Richard Trieu  CheckForRedundantIteration(*this, third.get(), Body);
1546694e796f462748ab4dc7ecdf4be5da44dd2c8c94Richard Trieu
154760d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult SecondResult(second.release());
154899e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  VarDecl *ConditionVar = 0;
1549d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (secondVar) {
1550d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(secondVar);
1551586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
155299e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    if (SecondResult.isInvalid())
155399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor      return StmtError();
155499e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  }
1555dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
155699e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  Expr *Third  = third.release().takeAs<Expr>();
1557dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
15583af708ff19e4ae2bf9e40550548361b00e5916bfAnders Carlsson  DiagnoseUnusedExprResult(First);
15593af708ff19e4ae2bf9e40550548361b00e5916bfAnders Carlsson  DiagnoseUnusedExprResult(Third);
1560754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  DiagnoseUnusedExprResult(Body);
1561754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson
1562625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  if (isa<NullStmt>(Body))
1563625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    getCurCompoundScope().setHasEmptyLoopBodies();
1564625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
1565dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  return Owned(new (Context) ForStmt(Context, First,
1566dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi                                     SecondResult.take(), ConditionVar,
1567dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi                                     Third, Body, ForLoc, LParenLoc,
156843dec6bbde2d0a16c35978983761c8b7030c8e18Douglas Gregor                                     RParenLoc));
15695f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
15705f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1571f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall/// In an Objective C collection iteration statement:
1572f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall///   for (x in y)
1573f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall/// x can be an arbitrary l-value expression.  Bind it up as a
1574f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall/// full-expression.
1575f6a1648197562e0b133440d612d9af297d0a86ccJohn McCallStmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
157629bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  // Reduce placeholder expressions here.  Note that this rejects the
157729bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  // use of pseudo-object l-values in this position.
157829bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  ExprResult result = CheckPlaceholderExpr(E);
157929bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  if (result.isInvalid()) return StmtError();
158029bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  E = result.take();
158129bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall
1582419563768ef4929a622d7c2b066856e82901bb91Richard Smith  ExprResult FullExpr = ActOnFinishFullExpr(E);
1583419563768ef4929a622d7c2b066856e82901bb91Richard Smith  if (FullExpr.isInvalid())
1584419563768ef4929a622d7c2b066856e82901bb91Richard Smith    return StmtError();
1585419563768ef4929a622d7c2b066856e82901bb91Richard Smith  return StmtResult(static_cast<Stmt*>(FullExpr.take()));
1586f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall}
1587f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall
1588990567cb60e8530ba01b41d4e056e32b44b95ec0John McCallExprResult
1589a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz JahanianSema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1590a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian  if (!collection)
1591a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian    return ExprError();
15921093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
1593990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Bail out early if we've got a type-dependent expression.
1594990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  if (collection->isTypeDependent()) return Owned(collection);
1595990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1596990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Perform normal l-value conversion.
1597990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1598990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  if (result.isInvalid())
1599990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    return ExprError();
1600990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  collection = result.take();
1601990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1602990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // The operand needs to have object-pointer type.
1603990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // TODO: should we do a contextual conversion?
1604990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  const ObjCObjectPointerType *pointerType =
1605990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    collection->getType()->getAs<ObjCObjectPointerType>();
1606990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  if (!pointerType)
1607990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    return Diag(forLoc, diag::err_collection_expr_type)
1608990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall             << collection->getType() << collection->getSourceRange();
1609990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1610990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Check that the operand provides
1611990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  //   - countByEnumeratingWithState:objects:count:
1612990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  const ObjCObjectType *objectType = pointerType->getObjectType();
1613990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  ObjCInterfaceDecl *iface = objectType->getInterface();
1614990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1615990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // If we have a forward-declared type, we can't do this check.
1616b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor  // Under ARC, it is an error not to have a forward-declared class.
16171093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  if (iface &&
1618b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor      RequireCompleteType(forLoc, QualType(objectType, 0),
16194e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie                          getLangOpts().ObjCAutoRefCount
1620d10099e5c8238fa0327f03921cf2e3c8975c881eDouglas Gregor                            ? diag::err_arc_collection_forward
1621d10099e5c8238fa0327f03921cf2e3c8975c881eDouglas Gregor                            : 0,
1622d10099e5c8238fa0327f03921cf2e3c8975c881eDouglas Gregor                          collection)) {
1623990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // Otherwise, if we have any useful type information, check that
1624990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // the type declares the appropriate method.
1625990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  } else if (iface || !objectType->qual_empty()) {
1626990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    IdentifierInfo *selectorIdents[] = {
1627990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      &Context.Idents.get("countByEnumeratingWithState"),
1628990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      &Context.Idents.get("objects"),
1629990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      &Context.Idents.get("count")
1630990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    };
1631990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1632990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1633990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    ObjCMethodDecl *method = 0;
1634990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1635990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // If there's an interface, look in both the public and private APIs.
1636990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    if (iface) {
1637990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      method = iface->lookupInstanceMethod(selector);
1638e61354b274ec5aa6acf3d15271896ce7596bb123Anna Zaks      if (!method) method = iface->lookupPrivateMethod(selector);
1639990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    }
1640990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1641990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // Also check protocol qualifiers.
1642990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    if (!method)
1643990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      method = LookupMethodInQualifiedType(selector, pointerType,
1644990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall                                           /*instance*/ true);
1645990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1646990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // If we didn't find it anywhere, give up.
1647990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    if (!method) {
1648990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      Diag(forLoc, diag::warn_collection_expr_type)
1649990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall        << collection->getType() << selector << collection->getSourceRange();
1650990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    }
1651990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1652990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // TODO: check for an incompatible signature?
1653990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  }
1654990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1655990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Wrap up any cleanups in the expression.
1656419563768ef4929a622d7c2b066856e82901bb91Richard Smith  return Owned(collection);
1657990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall}
1658990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
165960d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
1660f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian RedlSema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1661a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian                                 Stmt *First, Expr *collection,
1662a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian                                 SourceLocation RParenLoc) {
16631093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
16641093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  ExprResult CollectionExprResult =
1665a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian    CheckObjCForCollectionOperand(ForLoc, collection);
16661093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
166720552d2842245692b649e0d25380670922f954a2Fariborz Jahanian  if (First) {
166820552d2842245692b649e0d25380670922f954a2Fariborz Jahanian    QualType FirstType;
166920552d2842245692b649e0d25380670922f954a2Fariborz Jahanian    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
16707e24e82a70a2c681f4291a3397bcd1e1005f251aChris Lattner      if (!DS->isSingleDecl())
1671f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl        return StmtError(Diag((*DS->decl_begin())->getLocation(),
1672f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl                         diag::err_toomany_element_decls));
1673f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl
167412849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor      VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
167512849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor      if (!D || D->isInvalidDecl())
167612849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor        return StmtError();
167712849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor
1678f85e193739c953358c865005855253af4f68a497John McCall      FirstType = D->getType();
1679f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1680f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // declare identifiers for objects having storage class 'auto' or
1681f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // 'register'.
1682f85e193739c953358c865005855253af4f68a497John McCall      if (!D->hasLocalStorage())
1683f85e193739c953358c865005855253af4f68a497John McCall        return StmtError(Diag(D->getLocation(),
168412849d0ed2e88f8c6420944538b9c9d1985df14aDouglas Gregor                              diag::err_non_local_variable_decl_in_for));
16851cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor
16861cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor      // If the type contained 'auto', deduce the 'auto' to 'id'.
16871cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor      if (FirstType->getContainedAutoType()) {
16881cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor        OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
16891cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor                                 VK_RValue);
16901cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor        Expr *DeducedInit = &OpaqueId;
16919b1317531d376738fd6631291b0a04109c76a63bRichard Smith        if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
16929b1317531d376738fd6631291b0a04109c76a63bRichard Smith                DAR_Failed)
16931cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor          DiagnoseAutoDeductionFailure(D, DeducedInit);
16949b1317531d376738fd6631291b0a04109c76a63bRichard Smith        if (FirstType.isNull()) {
16951cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor          D->setInvalidDecl();
16961cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor          return StmtError();
16971cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor        }
16981cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor
16999b1317531d376738fd6631291b0a04109c76a63bRichard Smith        D->setType(FirstType);
17001cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor
17011cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor        if (ActiveTemplateInstantiations.empty()) {
17029b1317531d376738fd6631291b0a04109c76a63bRichard Smith          SourceLocation Loc =
17039b1317531d376738fd6631291b0a04109c76a63bRichard Smith              D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
17041cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor          Diag(Loc, diag::warn_auto_var_is_id)
17051cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor            << D->getDeclName();
17061cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor        }
17071cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor      }
17081cd1f73f09c6ddcf01e3a287d6604cd705190d14Douglas Gregor
17091fe379f0fa6fbc0a6057e8966253aea2957ca953Anders Carlsson    } else {
1710c3203e7ee1464a096f341c2e2a83a10be2da000aDouglas Gregor      Expr *FirstE = cast<Expr>(First);
17117eb0a9eb0cde8444b97f9c5b713d9be7a6f1e607John McCall      if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1712f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl        return StmtError(Diag(First->getLocStart(),
1713f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl                   diag::err_selector_element_not_lvalue)
1714f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl          << First->getSourceRange());
17151fe379f0fa6fbc0a6057e8966253aea2957ca953Anders Carlsson
17161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      FirstType = static_cast<Expr*>(First)->getType();
17171fe379f0fa6fbc0a6057e8966253aea2957ca953Anders Carlsson    }
1718c3203e7ee1464a096f341c2e2a83a10be2da000aDouglas Gregor    if (!FirstType->isDependentType() &&
1719c3203e7ee1464a096f341c2e2a83a10be2da000aDouglas Gregor        !FirstType->isObjCObjectPointerType() &&
1720a5e42a82ce055f29f3733f3a1f10da6cb9877deeFariborz Jahanian        !FirstType->isBlockPointerType())
1721a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian        return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1722a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian                           << FirstType << First->getSourceRange());
17233ba5a0f90a03d5e13d02cbee9abd2a1ba01b18bcFariborz Jahanian  }
17241093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
1725a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian  if (CollectionExprResult.isInvalid())
1726a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian    return StmtError();
17271093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
1728419563768ef4929a622d7c2b066856e82901bb91Richard Smith  CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1729419563768ef4929a622d7c2b066856e82901bb91Richard Smith  if (CollectionExprResult.isInvalid())
1730419563768ef4929a622d7c2b066856e82901bb91Richard Smith    return StmtError();
1731419563768ef4929a622d7c2b066856e82901bb91Richard Smith
17321093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  return Owned(new (Context) ObjCForCollectionStmt(First,
17331093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier                                                   CollectionExprResult.take(), 0,
17348189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                                                   ForLoc, RParenLoc));
17353ba5a0f90a03d5e13d02cbee9abd2a1ba01b18bcFariborz Jahanian}
17365f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1737ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// Finish building a variable declaration for a for-range statement.
1738ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// \return true if an error occurs.
1739ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithstatic bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
17409b1317531d376738fd6631291b0a04109c76a63bRichard Smith                                  SourceLocation Loc, int DiagID) {
1741ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // Deduce the type for the iterator variable now rather than leaving it to
1742ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
17439b1317531d376738fd6631291b0a04109c76a63bRichard Smith  QualType InitType;
174462b7cfb73e202051e7ab0dad42ba213acd0dec7eSebastian Redl  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
17459b1317531d376738fd6631291b0a04109c76a63bRichard Smith      SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1746b832f6dea893f25b40500a04781286236281cb20Sebastian Redl          Sema::DAR_Failed)
17479b1317531d376738fd6631291b0a04109c76a63bRichard Smith    SemaRef.Diag(Loc, DiagID) << Init->getType();
17489b1317531d376738fd6631291b0a04109c76a63bRichard Smith  if (InitType.isNull()) {
1749ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Decl->setInvalidDecl();
1750ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return true;
1751ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
17529b1317531d376738fd6631291b0a04109c76a63bRichard Smith  Decl->setType(InitType);
1753ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1754f85e193739c953358c865005855253af4f68a497John McCall  // In ARC, infer lifetime.
1755f85e193739c953358c865005855253af4f68a497John McCall  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1756f85e193739c953358c865005855253af4f68a497John McCall  // we're doing the equivalent of fast iteration.
17571093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1758f85e193739c953358c865005855253af4f68a497John McCall      SemaRef.inferObjCARCLifetime(Decl))
1759f85e193739c953358c865005855253af4f68a497John McCall    Decl->setInvalidDecl();
1760f85e193739c953358c865005855253af4f68a497John McCall
1761ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1762ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                               /*TypeMayContainAuto=*/false);
1763ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SemaRef.FinalizeDeclaration(Decl);
1764b403d6d746239095a2c7bac958c924d92434e2b4Richard Smith  SemaRef.CurContext->addHiddenDecl(Decl);
1765ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return false;
1766ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1767ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1768e1715b66a878bcab315513351e5df68bfc010d2eSam Panzernamespace {
1769e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1770ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// Produce a note indicating which begin/end function was implicitly called
1771e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// by a C++11 for-range statement. This is often not obvious from the code,
1772ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// nor from the diagnostics produced when analysing the implicit expressions
1773ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// required in a for-range statement.
1774ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithvoid NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1775e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                  Sema::BeginEndFunction BEF) {
1776ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  CallExpr *CE = dyn_cast<CallExpr>(E);
1777ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!CE)
1778ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return;
1779ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1780ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!D)
1781ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return;
1782ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SourceLocation Loc = D->getLocation();
1783ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1784ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  std::string Description;
1785ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  bool IsTemplate = false;
1786ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1787ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Description = SemaRef.getTemplateArgumentBindingsText(
1788ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1789ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    IsTemplate = true;
1790ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1791ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1792ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1793ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    << BEF << IsTemplate << Description << E->getType();
1794ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1795ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1796e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// Build a variable declaration for a for-range statement.
1797e1715b66a878bcab315513351e5df68bfc010d2eSam PanzerVarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1798e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                              QualType Type, const char *Name) {
1799e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  DeclContext *DC = SemaRef.CurContext;
1800e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1801e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1802e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1803d2615cc53b916e8aae45783ca7113b93de515ce3Rafael Espindola                                  TInfo, SC_None);
1804e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  Decl->setImplicit();
1805e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  return Decl;
1806ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1807ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1808ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1809ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
18104d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanianstatic bool ObjCEnumerationCollection(Expr *Collection) {
18114d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian  return !Collection->isTypeDependent()
18124d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian          && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
18134d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian}
18144d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian
1815bc20bbb0bf90446a469848c658ca376832f43dc8Sam Panzer/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1816ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///
1817bc20bbb0bf90446a469848c658ca376832f43dc8Sam Panzer/// C++11 [stmt.ranged]:
1818ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///   A range-based for statement is equivalent to
1819ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///
1820ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///   {
1821ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///     auto && __range = range-init;
1822ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///     for ( auto __begin = begin-expr,
1823ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///           __end = end-expr;
1824ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///           __begin != __end;
1825ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///           ++__begin ) {
1826ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///       for-range-declaration = *__begin;
1827ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///       statement
1828ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///     }
1829ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///   }
1830ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///
1831ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// The body of the loop is not available yet, since it cannot be analysed until
1832ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// we have determined the type of the for-range-declaration.
1833ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithStmtResult
1834bc20bbb0bf90446a469848c658ca376832f43dc8Sam PanzerSema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1835ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           Stmt *First, SourceLocation ColonLoc, Expr *Range,
18368b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                           SourceLocation RParenLoc, BuildForRangeKind Kind) {
1837ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!First || !Range)
1838ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
18391093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
18404d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian  if (ObjCEnumerationCollection(Range))
1841bc20bbb0bf90446a469848c658ca376832f43dc8Sam Panzer    return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1842ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1843ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1844ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  assert(DS && "first part of for range not a decl stmt");
1845ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1846ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!DS->isSingleDecl()) {
1847ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1848ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1849ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1850ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (DS->getSingleDecl()->isInvalidDecl())
1851ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1852ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1853ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1854ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1855ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1856ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // Build  auto && __range = range-init
1857ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SourceLocation RangeLoc = Range->getLocStart();
1858ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1859ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           Context.getAutoRRefDeductType(),
1860ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           "__range");
1861ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1862ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                            diag::err_for_range_deduction_failure))
1863ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1864ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1865ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // Claim the type doesn't contain auto: we've already done the checking.
1866ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclGroupPtrTy RangeGroup =
18674549d7ffc15bdd7ab860aa68db089d9f559b79e7Rafael Espindola      BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
18684549d7ffc15bdd7ab860aa68db089d9f559b79e7Rafael Espindola                           /*TypeMayContainAuto=*/ false);
1869ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1870ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (RangeDecl.isInvalid())
1871ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1872ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1873ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1874ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                              /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
18758b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                              RParenLoc, Kind);
1876e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer}
1877e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1878e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// \brief Create the initialization, compare, and increment steps for
1879e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// the range-based for loop expression.
1880e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// This function does not handle array-based for loops,
1881e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// which are created in Sema::BuildCXXForRangeStmt.
1882e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer///
1883e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1884e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1885e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// CandidateSet and BEF are set and some non-success value is returned on
1886e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// failure.
1887e1715b66a878bcab315513351e5df68bfc010d2eSam Panzerstatic Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1888e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            Expr *BeginRange, Expr *EndRange,
1889e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            QualType RangeType,
1890e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            VarDecl *BeginVar,
1891e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            VarDecl *EndVar,
1892e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            SourceLocation ColonLoc,
1893e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            OverloadCandidateSet *CandidateSet,
1894e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            ExprResult *BeginExpr,
1895e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            ExprResult *EndExpr,
1896e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                            Sema::BeginEndFunction *BEF) {
1897e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  DeclarationNameInfo BeginNameInfo(
1898e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1899e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1900e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                  ColonLoc);
1901e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1902e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1903e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                 Sema::LookupMemberName);
1904e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1905e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1906e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1907e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    // - if _RangeT is a class type, the unqualified-ids begin and end are
1908e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   looked up in the scope of class _RangeT as if by class member access
1909e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   lookup (3.4.5), and if either (or both) finds at least one
1910e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   declaration, begin-expr and end-expr are __range.begin() and
1911e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   __range.end(), respectively;
1912e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1913e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    SemaRef.LookupQualifiedName(EndMemberLookup, D);
1914e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1915e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1916e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      SourceLocation RangeLoc = BeginVar->getLocation();
1917e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1918e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1919e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1920e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer          << RangeLoc << BeginRange->getType() << *BEF;
1921e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      return Sema::FRS_DiagnosticIssued;
1922e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    }
1923e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  } else {
1924e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    // - otherwise, begin-expr and end-expr are begin(__range) and
1925e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   end(__range), respectively, where begin and end are looked up with
1926e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   argument-dependent lookup (3.4.2). For the purposes of this name
1927e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    //   lookup, namespace std is an associated namespace.
1928e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1929e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  }
1930e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1931e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  *BEF = Sema::BEF_begin;
1932e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  Sema::ForRangeStatus RangeStatus =
1933e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1934e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                        Sema::BEF_begin, BeginNameInfo,
1935e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                        BeginMemberLookup, CandidateSet,
1936e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                        BeginRange, BeginExpr);
1937e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1938e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  if (RangeStatus != Sema::FRS_Success)
1939e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    return RangeStatus;
1940e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1941e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                            diag::err_for_range_iter_deduction_failure)) {
1942e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1943e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    return Sema::FRS_DiagnosticIssued;
1944e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  }
1945e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1946e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  *BEF = Sema::BEF_end;
1947e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  RangeStatus =
1948e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1949e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                        Sema::BEF_end, EndNameInfo,
1950e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                        EndMemberLookup, CandidateSet,
1951e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                        EndRange, EndExpr);
1952e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  if (RangeStatus != Sema::FRS_Success)
1953e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    return RangeStatus;
1954e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1955e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                            diag::err_for_range_iter_deduction_failure)) {
1956e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1957e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    return Sema::FRS_DiagnosticIssued;
1958e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  }
1959e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer  return Sema::FRS_Success;
1960e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer}
1961e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
1962e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer/// Speculatively attempt to dereference an invalid range expression.
19638b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith/// If the attempt fails, this function will return a valid, null StmtResult
19648b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith/// and emit no diagnostics.
1965e1715b66a878bcab315513351e5df68bfc010d2eSam Panzerstatic StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1966e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                 SourceLocation ForLoc,
1967e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                 Stmt *LoopVarDecl,
1968e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                 SourceLocation ColonLoc,
1969e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                 Expr *Range,
1970e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                 SourceLocation RangeLoc,
1971e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                 SourceLocation RParenLoc) {
19728b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // Determine whether we can rebuild the for-range statement with a
19738b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // dereferenced range expression.
19748b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  ExprResult AdjustedRange;
19758b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  {
19768b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    Sema::SFINAETrap Trap(SemaRef);
19778b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith
19788b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
19798b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    if (AdjustedRange.isInvalid())
19808b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith      return StmtResult();
19818b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith
19828b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    StmtResult SR =
19838b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith      SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
19848b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                                   AdjustedRange.get(), RParenLoc,
19858b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                                   Sema::BFRK_Check);
19868b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    if (SR.isInvalid())
19878b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith      return StmtResult();
19888b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  }
19898b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith
19908b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // The attempt to dereference worked well enough that it could produce a valid
19918b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
19928b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // case there are any other (non-fatal) problems with it.
19938b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
19948b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
19958b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
19968b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                                      AdjustedRange.get(), RParenLoc,
19978b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                                      Sema::BFRK_Rebuild);
1998ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1999ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
20008b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2001ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithStmtResult
2002ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithSema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2003ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2004ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           Expr *Inc, Stmt *LoopVarDecl,
20058b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith                           SourceLocation RParenLoc, BuildForRangeKind Kind) {
2006ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  Scope *S = getCurScope();
2007ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2008ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2009ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2010ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  QualType RangeVarType = RangeVar->getType();
2011ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2012ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2013ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2014ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2015ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  StmtResult BeginEndDecl = BeginEnd;
2016ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2017ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2018dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith  if (RangeVarType->isDependentType()) {
2019dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith    // The range is implicitly used as a placeholder when it is dependent.
2020dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith    RangeVar->setUsed();
2021dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith
2022dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith    // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2023dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith    // them in properly when we instantiate the loop.
2024dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith    if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2025dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith      LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2026dc7a4f5d7a7e3b60d4dc4a80338d7a2728540998Richard Smith  } else if (!BeginEndDecl.get()) {
2027ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    SourceLocation RangeLoc = RangeVar->getLocation();
2028ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2029e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2030e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
2031e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2032e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                                VK_LValue, ColonLoc);
2033e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRangeRef.isInvalid())
2034e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
2035e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
2036e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2037e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                              VK_LValue, ColonLoc);
2038e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (EndRangeRef.isInvalid())
2039ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
2040ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2041ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    QualType AutoType = Context.getAutoDeductType();
2042ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Expr *Range = RangeVar->getInit();
2043ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (!Range)
2044ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
2045ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    QualType RangeType = Range->getType();
2046ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2047ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (RequireCompleteType(RangeLoc, RangeType,
2048d10099e5c8238fa0327f03921cf2e3c8975c881eDouglas Gregor                            diag::err_for_range_incomplete_type))
2049ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
2050ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2051ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build auto __begin = begin-expr, __end = end-expr.
2052ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2053ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             "__begin");
2054ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2055ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           "__end");
2056ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2057ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build begin-expr and end-expr and attach to __begin and __end variables.
2058ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult BeginExpr, EndExpr;
2059ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2060ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // - if _RangeT is an array type, begin-expr and end-expr are __range and
2061ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      //   __range + __bound, respectively, where __bound is the array bound. If
2062ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      //   _RangeT is an array of unknown size or an array of incomplete type,
2063ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      //   the program is ill-formed;
2064ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2065ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // begin-expr is __range.
2066e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      BeginExpr = BeginRangeRef;
2067e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2068ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                diag::err_for_range_iter_deduction_failure)) {
2069ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2070ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
2071ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
2072ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2073ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // Find the array bound.
2074ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      ExprResult BoundExpr;
2075ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2076ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
20771dd986dff9ddfbec687975700770bb377988e9edRichard Trieu                                                 Context.getPointerDiffType(),
20781dd986dff9ddfbec687975700770bb377988e9edRichard Trieu                                                 RangeLoc));
2079ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      else if (const VariableArrayType *VAT =
2080ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith               dyn_cast<VariableArrayType>(UnqAT))
208139b0e269dc8895ecc0f92f08126d3082b2a837a8Richard Smith        // FIXME: Need to build an OpaqueValueExpr for this rather than
208239b0e269dc8895ecc0f92f08126d3082b2a837a8Richard Smith        // recomputing it!
2083ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        BoundExpr = VAT->getSizeExpr();
2084ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      else {
2085ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2086ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        // UnqAT is not incomplete and Range is not type-dependent.
2087b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie        llvm_unreachable("Unexpected array type in for-range");
2088ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
2089ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2090ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // end-expr is __range + __bound.
2091e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2092ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           BoundExpr.get());
2093ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (EndExpr.isInvalid())
2094ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
2095ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2096ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                diag::err_for_range_iter_deduction_failure)) {
2097ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2098ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
2099ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
2100ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    } else {
2101e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      OverloadCandidateSet CandidateSet(RangeLoc);
2102e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      Sema::BeginEndFunction BEFFailure;
2103e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      ForRangeStatus RangeStatus =
2104e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer          BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2105e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                EndRangeRef.get(), RangeType,
2106e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                BeginVar, EndVar, ColonLoc, &CandidateSet,
2107e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                &BeginExpr, &EndExpr, &BEFFailure);
2108e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
2109e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      // If building the range failed, try dereferencing the range expression
2110e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      // unless a diagnostic was issued or the end function is problematic.
21118b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith      if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2112e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer          BEFFailure == BEF_begin) {
2113e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer        StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2114e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                       LoopVarDecl, ColonLoc,
2115e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                       Range, RangeLoc,
2116e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer                                                       RParenLoc);
21178b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith        if (SR.isInvalid() || SR.isUsable())
2118e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer          return SR;
2119ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
2120ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2121e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      // Otherwise, emit diagnostics if we haven't already.
2122e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      if (RangeStatus == FRS_NoViableFunction) {
21238b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith        Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2124e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer        Diag(Range->getLocStart(), diag::err_for_range_invalid)
2125e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer            << RangeLoc << Range->getType() << BEFFailure;
2126d36aa359e2f45cd22c7366a015ad94de08044dbbNico Weber        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2127e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      }
2128e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      // Return an error if no fix was discovered.
2129e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer      if (RangeStatus != FRS_Success)
2130ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
2131ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
2132ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2133e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2134e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer           "invalid range expression in for loop");
2135e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer
2136e1715b66a878bcab315513351e5df68bfc010d2eSam Panzer    // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2137ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2138ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (!Context.hasSameType(BeginType, EndType)) {
2139ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2140ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        << BeginType << EndType;
2141ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2142ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2143ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
2144ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2145ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Decl *BeginEndDecls[] = { BeginVar, EndVar };
2146ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Claim the type doesn't contain auto: we've already done the checking.
2147ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    DeclGroupPtrTy BeginEndGroup =
21484549d7ffc15bdd7ab860aa68db089d9f559b79e7Rafael Espindola        BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>(BeginEndDecls, 2),
21494549d7ffc15bdd7ab860aa68db089d9f559b79e7Rafael Espindola                             /*TypeMayContainAuto=*/ false);
2150ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2151ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2152e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2153e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2154ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           VK_LValue, ColonLoc);
2155e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRef.isInvalid())
2156e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
2157e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
2158ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2159ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                         VK_LValue, ColonLoc);
2160e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (EndRef.isInvalid())
2161e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
2162ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2163ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build and check __begin != __end expression.
2164ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2165ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           BeginRef.get(), EndRef.get());
2166ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2167ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2168ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (NotEqExpr.isInvalid()) {
21698123b6e7838216a53ba050f07e36fee28e1bbdafSam Panzer      Diag(RangeLoc, diag::note_for_range_invalid_iterator)
21708123b6e7838216a53ba050f07e36fee28e1bbdafSam Panzer        << RangeLoc << 0 << BeginRangeRef.get()->getType();
2171ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2172ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (!Context.hasSameType(BeginType, EndType))
2173ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2174ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
2175ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
2176ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2177ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build and check ++__begin expression.
2178e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2179e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                VK_LValue, ColonLoc);
2180e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRef.isInvalid())
2181e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
2182e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
2183ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2184ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2185ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (IncrExpr.isInvalid()) {
21868123b6e7838216a53ba050f07e36fee28e1bbdafSam Panzer      Diag(RangeLoc, diag::note_for_range_invalid_iterator)
21878123b6e7838216a53ba050f07e36fee28e1bbdafSam Panzer        << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2188ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2189ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
2190ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
2191ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
2192ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build and check *__begin  expression.
2193e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2194e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                VK_LValue, ColonLoc);
2195e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRef.isInvalid())
2196e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
2197e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
2198ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2199ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (DerefExpr.isInvalid()) {
22008123b6e7838216a53ba050f07e36fee28e1bbdafSam Panzer      Diag(RangeLoc, diag::note_for_range_invalid_iterator)
22018123b6e7838216a53ba050f07e36fee28e1bbdafSam Panzer        << RangeLoc << 1 << BeginRangeRef.get()->getType();
2202ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2203ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
2204ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
2205ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
22068b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    // Attach  *__begin  as initializer for VD. Don't touch it if we're just
22078b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    // trying to determine whether this would be a valid range.
22088b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2209ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2210ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           /*TypeMayContainAuto=*/true);
2211ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (LoopVar->isInvalidDecl())
2212ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2213ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
2214ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
2215ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
22168b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // Don't bother to actually allocate the result if we're just trying to
22178b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  // determine whether it would be valid.
22188b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith  if (Kind == BFRK_Check)
22198b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith    return StmtResult();
22208b533d97e0683a0c87096b95927a2e9ce02243d4Richard Smith
2221ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return Owned(new (Context) CXXForRangeStmt(RangeDS,
2222ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                     cast_or_null<DeclStmt>(BeginEndDecl.get()),
2223ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             NotEqExpr.take(), IncrExpr.take(),
2224ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             LoopVarDS, /*Body=*/0, ForLoc,
2225ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             ColonLoc, RParenLoc));
2226ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
2227ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
22281093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2229a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian/// statement.
2230a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz JahanianStmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2231a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian  if (!S || !B)
2232a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian    return StmtError();
2233a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian  ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
22341093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
2235a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian  ForStmt->setBody(B);
2236a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian  return S;
2237a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian}
2238a1eec4bd198b96ef40a7c15cd0e131ca94511ad8Fariborz Jahanian
2239ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2240ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2241ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// body cannot be performed until after the type of the range variable is
2242ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// determined.
2243ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithStmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2244ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!S || !B)
2245ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
2246ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
22474d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian  if (isa<ObjCForCollectionStmt>(S))
22484d3db4eb6caa49a7cdbfe1798728ce4b23cd0b53Fariborz Jahanian    return FinishObjCForCollectionStmt(S, B);
22491093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
2250625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2251625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  ForStmt->setBody(B);
2252625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
2253625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2254625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko                        diag::warn_empty_range_based_for_body);
2255625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
2256ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return S;
2257ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
2258ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
225957ad37823e198f977cac605dbfbaefb4daf325e9Chris LattnerStmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
226057ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                               SourceLocation LabelLoc,
226157ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                               LabelDecl *TheDecl) {
226257ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner  getCurFunction()->setHasBranchIntoScope();
2263ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  TheDecl->setUsed();
2264ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
22655f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
22665f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
226760d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2268ad56d684259f706b7c0ae5ad9c23adb4f2926817Chris LattnerSema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
22699ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                            Expr *E) {
2270bbf462314b1dc8e422b7c4dd4cac47e566aedf6dEli Friedman  // Convert operand to void*
22715f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor  if (!E->isTypeDependent()) {
22725f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor    QualType ETy = E->getType();
22732877998bd8db2fac1c56430a4edcfa0ce138aff9Chandler Carruth    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2274429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    ExprResult ExprRes = Owned(E);
22755f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor    AssignConvertType ConvTy =
2276429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      CheckSingleAssignmentConstraints(DestTy, ExprRes);
2277429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    if (ExprRes.isInvalid())
2278429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      return StmtError();
2279429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    E = ExprRes.take();
22802877998bd8db2fac1c56430a4edcfa0ce138aff9Chandler Carruth    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
22815f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor      return StmtError();
22825f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor  }
2283b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
2284419563768ef4929a622d7c2b066856e82901bb91Richard Smith  ExprResult ExprRes = ActOnFinishFullExpr(E);
2285419563768ef4929a622d7c2b066856e82901bb91Richard Smith  if (ExprRes.isInvalid())
2286419563768ef4929a622d7c2b066856e82901bb91Richard Smith    return StmtError();
2287419563768ef4929a622d7c2b066856e82901bb91Richard Smith  E = ExprRes.take();
2288419563768ef4929a622d7c2b066856e82901bb91Richard Smith
2289781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasIndirectGoto();
2290b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
22915f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
22925f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
22935f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
229460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
22951b273c403734d343d720acb28f04011807c8aa56Steve NaroffSema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
22965f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  Scope *S = CurScope->getContinueParent();
22975f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (!S) {
22985f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
22994cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
23005f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
23014cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
23028189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) ContinueStmt(ContinueLoc));
23035f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
23045f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
230560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
23061b273c403734d343d720acb28f04011807c8aa56Steve NaroffSema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
23075f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  Scope *S = CurScope->getBreakParent();
23085f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (!S) {
23095f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
23104cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
23115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
23124cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
23138189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) BreakStmt(BreakLoc));
23145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
23155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
2316dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi/// \brief Determine whether the given expression is a candidate for
2317f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// copy elision in either a return statement or a throw expression.
23185077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
2319f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// \param ReturnType If we're determining the copy elision candidate for
2320f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// a return statement, this is the return type of the function. If we're
2321f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// determining the copy elision candidate for a throw expression, this will
2322f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// be a NULL type.
23235077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
2324f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// \param E The expression being returned from the function or block, or
2325f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// being thrown.
23265077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
23274926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// \param AllowFunctionParameter Whether we allow function parameters to
23284926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
23294926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// we re-use this logic to determine whether we should try to move as part of
23304926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// a return or throw (which does allow function parameters).
23315077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
23325077c3876beeaed32280af88244e8050078619a8Douglas Gregor/// \returns The NRVO candidate variable, if the return statement may use the
23335077c3876beeaed32280af88244e8050078619a8Douglas Gregor/// NRVO, or NULL if there is no such candidate.
2334f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregorconst VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2335f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor                                             Expr *E,
2336f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor                                             bool AllowFunctionParameter) {
2337f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  QualType ExprType = E->getType();
23383c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  // - in a return statement in a function with ...
23393c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  // ... a class return type ...
2340f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  if (!ReturnType.isNull()) {
2341f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor    if (!ReturnType->isRecordType())
2342f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor      return 0;
2343f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor    // ... the same cv-unqualified type as the function return type ...
2344f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2345f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor      return 0;
2346f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  }
2347dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2348dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // ... the expression is the name of a non-volatile automatic object
2349f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  // (other than a function or catch-clause parameter)) ...
2350f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
23518951067a2bc35fb2a535bc18432cb2d02a762b73Nico Weber  if (!DR || DR->refersToEnclosingLocal())
23525077c3876beeaed32280af88244e8050078619a8Douglas Gregor    return 0;
23533c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
23543c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  if (!VD)
23555077c3876beeaed32280af88244e8050078619a8Douglas Gregor    return 0;
2356dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
23571cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // ...object (other than a function or catch-clause parameter)...
23581cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->getKind() != Decl::Var &&
23591cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall      !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
23601cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall    return 0;
23611cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->isExceptionVariable()) return 0;
23621cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
23631cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // ...automatic...
23641cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (!VD->hasLocalStorage()) return 0;
23651cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
23661cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // ...non-volatile...
23671cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->getType().isVolatileQualified()) return 0;
23681cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->getType()->isReferenceType()) return 0;
23691cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
23701cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // __block variables can't be allocated in a way that permits NRVO.
23711cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->hasAttr<BlocksAttr>()) return 0;
23721cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
23731cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // Variables with higher required alignment than their type's ABI
23741cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // alignment cannot use NRVO.
23751cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->hasAttr<AlignedAttr>() &&
23761cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall      Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
23771cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall    return 0;
2378dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
23791cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  return VD;
23803c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor}
23813c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor
238207f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor/// \brief Perform the initialization of a potentially-movable value, which
238307f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor/// is the result of return value.
2384cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor///
2385cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor/// This routine implements C++0x [class.copy]p33, which attempts to treat
2386cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor/// returned lvalues as rvalues in certain cases (to prefer move construction),
2387cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor/// then falls back to treating them as lvalues if that failed.
2388dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiExprResult
238907f402cff25354c5f06f307f19b0c57c09d964bdDouglas GregorSema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
239007f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                      const VarDecl *NRVOCandidate,
239107f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                      QualType ResultType,
2392bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor                                      Expr *Value,
2393bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor                                      bool AllowNRVO) {
2394cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  // C++0x [class.copy]p33:
2395dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  //   When the criteria for elision of a copy operation are met or would
2396dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  //   be met save for the fact that the source object is a function
2397dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  //   parameter, and the object to be copied is designated by an lvalue,
2398cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  //   overload resolution to select the constructor for the copy is first
2399cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  //   performed as if the object were designated by an rvalue.
2400cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  ExprResult Res = ExprError();
2401bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor  if (AllowNRVO &&
2402bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor      (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2403dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2404dbbecccb8431bb4545fc01c6401abc4253667360Richard Smith                              Value->getType(), CK_NoOp, Value, VK_XValue);
2405dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2406cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    Expr *InitExpr = &AsRvalue;
2407dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    InitializationKind Kind
240807f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor      = InitializationKind::CreateCopy(Value->getLocStart(),
240907f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                       Value->getLocStart());
24101f78a50f8aee58f8e07f6307f4b8d0b1742e9a2bDmitri Gribenko    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2411dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2412dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    //   [...] If overload resolution fails, or if the type of the first
2413cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    //   parameter of the selected constructor is not an rvalue reference
24140099530a2288df7c2140dd8992b7310b9f6930a9NAKAMURA Takumi    //   to the object's type (possibly cv-qualified), overload resolution
2415cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    //   is performed again, considering the object as an lvalue.
2416383616cd2e61131a534afd9364ef53f643e1f834Sebastian Redl    if (Seq) {
2417cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2418cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor           StepEnd = Seq.step_end();
2419cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor           Step != StepEnd; ++Step) {
2420383616cd2e61131a534afd9364ef53f643e1f834Sebastian Redl        if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2421cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor          continue;
2422dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2423dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi        CXXConstructorDecl *Constructor
2424cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        = cast<CXXConstructorDecl>(Step->Function.Function);
2425dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2426cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        const RValueReferenceType *RRefType
242707f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor          = Constructor->getParamDecl(0)->getType()
242807f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                                 ->getAs<RValueReferenceType>();
2429dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2430cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // If we don't meet the criteria, break out now.
2431dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi        if (!RRefType ||
243207f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
243307f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                            Context.getTypeDeclType(Constructor->getParent())))
2434cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor          break;
2435dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2436cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // Promote "AsRvalue" to the heap, since we now need this
2437cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // expression node to persist.
243807f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor        Value = ImplicitCastExpr::Create(Context, Value->getType(),
2439dbbecccb8431bb4545fc01c6401abc4253667360Richard Smith                                         CK_NoOp, Value, 0, VK_XValue);
2440dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2441cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // Complete type-checking the initialization of the return type
2442cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // using the constructor we found.
24431f78a50f8aee58f8e07f6307f4b8d0b1742e9a2bDmitri Gribenko        Res = Seq.Perform(*this, Entity, Kind, Value);
2444cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor      }
2445cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    }
2446cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  }
2447dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2448cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2449dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // above, or overload resolution failed. Either way, we need to try
2450cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  // (again) now with the return value expression as written.
2451cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  if (Res.isInvalid())
245207f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2453dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2454cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  return Res;
2455cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor}
2456cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor
245784b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
245884b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman/// for capturing scopes.
24594eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff///
246060d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
246184b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli FriedmanSema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
246284b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  // If this is the first return we've seen, infer the return type.
2463f45c2992a3aac7591310cd824b7c7319afd432fcRichard Smith  // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
246484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
24657dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  QualType FnRetType = CurCap->ReturnType;
24667dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose
24677dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  // For blocks/lambdas with implicit return types, we check each return
24687dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  // statement individually, and deduce the common return type when the block
24697dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  // or lambda is completed.
2470ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith  if (CurCap->HasImplicitReturnType) {
2471ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith    // FIXME: Fold this into the 'auto' codepath below.
2472a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor    if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2473429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2474429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      if (Result.isInvalid())
2475429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley        return StmtError();
2476429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      RetValExp = Result.take();
24776a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor
247814d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith      if (!CurContext->isDependentContext()) {
24797dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose        FnRetType = RetValExp->getType();
248014d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith        // In C++11, we take the type of the expression after decay and
248114d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith        // lvalue-to-rvalue conversion, so a class type can be cv-qualified.
248214d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith        // In C++1y, we perform template argument deduction as if the return
248314d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith        // type were 'auto', so an implicit return type is never cv-qualified.
248414d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith        if (getLangOpts().CPlusPlus1y && FnRetType.hasQualifiers())
248514d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith          FnRetType = FnRetType.getUnqualifiedType();
248614d937afc2ad8f65dccbafeb62271e80dbd46a78Richard Smith      } else
24877dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose        FnRetType = CurCap->ReturnType = Context.DependentTy;
24881093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier    } else {
2489a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor      if (RetValExp) {
2490a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2491a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        // initializer list, because it is not an expression (even
2492a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        // though we represent it as one). We still deduce 'void'.
2493a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        Diag(ReturnLoc, diag::err_lambda_return_init_list)
2494a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor          << RetValExp->getSourceRange();
2495a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor      }
2496a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor
24977dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose      FnRetType = Context.VoidTy;
2498649657e7d6c150136cae5ab22e39b9794cff80ccFariborz Jahanian    }
24997dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose
25007dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose    // Although we'll properly infer the type of the block once it's completed,
25017dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose    // make sure we provide a return type now for better error recovery.
25027dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose    if (CurCap->ReturnType.isNull())
25037dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose      CurCap->ReturnType = FnRetType;
2504ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith  } else if (AutoType *AT =
2505ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith                 FnRetType.isNull() ? 0 : FnRetType->getContainedAutoType()) {
2506ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith    // In C++1y, the return type may involve 'auto'.
2507ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith    FunctionDecl *FD = cast<LambdaScopeInfo>(CurCap)->CallOperator;
2508ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith    if (CurContext->isDependentContext()) {
2509ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      // C++1y [dcl.spec.auto]p12:
2510ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      //   Return type deduction [...] occurs when the definition is
2511ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      //   instantiated even if the function body contains a return
2512ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      //   statement with a non-type-dependent operand.
2513ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      CurCap->ReturnType = FnRetType = Context.DependentTy;
2514ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith    } else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2515ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      FD->setInvalidDecl();
2516ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      return StmtError();
2517ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith    } else
2518ec0808decc682f76e411eed7206a82a34b87dd7dRichard Smith      CurCap->ReturnType = FnRetType = FD->getResultType();
25194eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  }
252084b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  assert(!FnRetType.isNull());
25214cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
2522793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
252384b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
252484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
252584b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      return StmtError();
252684b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    }
25276afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  } else if (CapturedRegionScopeInfo *CurRegion =
25286afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj                 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
25296afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
25306afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    return StmtError();
2531793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor  } else {
2532793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2533793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor    if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2534793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor      Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2535793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor      return StmtError();
2536793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor    }
2537793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor  }
25386c92fa75e62937f9738696840efcb258560f4568Mike Stump
25394eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  // Otherwise, verify that this result type matches the previous one.  We are
25404eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  // pickier with blocks than for normal functions because we don't have GCC
25414eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  // compatibility to worry about here.
2542d963c37eb912342c8325048749e449861cf0a6e3John McCall  const VarDecl *NRVOCandidate = 0;
25430a7efe1142d241678c91bf93ee6adb51289863a4John McCall  if (FnRetType->isDependentType()) {
25440a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // Delay processing for now.  TODO: there are lots of dependent
25450a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // types we can conclusively prove aren't void.
25460a7efe1142d241678c91bf93ee6adb51289863a4John McCall  } else if (FnRetType->isVoidType()) {
25475b38a0f98e4420dae1bd3e13959bc207c97a9e98Sebastian Redl    if (RetValExp && !isa<InitListExpr>(RetValExp) &&
25484e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        !(getLangOpts().CPlusPlus &&
25490a7efe1142d241678c91bf93ee6adb51289863a4John McCall          (RetValExp->isTypeDependent() ||
25500a7efe1142d241678c91bf93ee6adb51289863a4John McCall           RetValExp->getType()->isVoidType()))) {
25514e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian      if (!getLangOpts().CPlusPlus &&
25524e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian          RetValExp->getType()->isVoidType())
25539354f6aaa70e1543d122644fee0c3f834324d2fcFariborz Jahanian        Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
25544e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian      else {
25554e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian        Diag(ReturnLoc, diag::err_return_block_has_expr);
25564e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian        RetValExp = 0;
25574e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian      }
25584eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff    }
25595077c3876beeaed32280af88244e8050078619a8Douglas Gregor  } else if (!RetValExp) {
25600a7efe1142d241678c91bf93ee6adb51289863a4John McCall    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
25610a7efe1142d241678c91bf93ee6adb51289863a4John McCall  } else if (!RetValExp->isTypeDependent()) {
25620a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // we have a non-void block with an expression, continue checking
25630a7efe1142d241678c91bf93ee6adb51289863a4John McCall
25640a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
25650a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
25660a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // function return.
25670a7efe1142d241678c91bf93ee6adb51289863a4John McCall
25680a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // In C++ the return statement is handled via a copy initialization.
25690a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // the C version of which boils down to CheckSingleAssignmentConstraints.
25700a7efe1142d241678c91bf93ee6adb51289863a4John McCall    NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
25710a7efe1142d241678c91bf93ee6adb51289863a4John McCall    InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
25720a7efe1142d241678c91bf93ee6adb51289863a4John McCall                                                                   FnRetType,
25730586520acb2f368c874943353a222be7f00c3068Fariborz Jahanian                                                          NRVOCandidate != 0);
25740a7efe1142d241678c91bf93ee6adb51289863a4John McCall    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
25750a7efe1142d241678c91bf93ee6adb51289863a4John McCall                                                     FnRetType, RetValExp);
25760a7efe1142d241678c91bf93ee6adb51289863a4John McCall    if (Res.isInvalid()) {
25770a7efe1142d241678c91bf93ee6adb51289863a4John McCall      // FIXME: Cleanup temporaries here, anyway?
25780a7efe1142d241678c91bf93ee6adb51289863a4John McCall      return StmtError();
2579c6acbc58a7aef0a3382775424c80e9534b54b2edAnders Carlsson    }
25800a7efe1142d241678c91bf93ee6adb51289863a4John McCall    RetValExp = Res.take();
25810a7efe1142d241678c91bf93ee6adb51289863a4John McCall    CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2582d963c37eb912342c8325048749e449861cf0a6e3John McCall  }
2583dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2584d963c37eb912342c8325048749e449861cf0a6e3John McCall  if (RetValExp) {
2585419563768ef4929a622d7c2b066856e82901bb91Richard Smith    ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2586419563768ef4929a622d7c2b066856e82901bb91Richard Smith    if (ER.isInvalid())
2587419563768ef4929a622d7c2b066856e82901bb91Richard Smith      return StmtError();
2588419563768ef4929a622d7c2b066856e82901bb91Richard Smith    RetValExp = ER.take();
258998eb8a7a702b95183ed015706b1f1c66f5cb27a4Mike Stump  }
25900a7efe1142d241678c91bf93ee6adb51289863a4John McCall  ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
25910a7efe1142d241678c91bf93ee6adb51289863a4John McCall                                                NRVOCandidate);
25924cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
25937dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  // If we need to check for the named return value optimization,
25947dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  // or if we need to infer the return type,
25957dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  // save the return statement in our scope for later processing.
25967dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose  if (CurCap->HasImplicitReturnType ||
25977dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose      (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
25987dd900ed308506f9cf1cb72c70db1652f94cab37Jordan Rose       !CurContext->isDependentContext()))
25995077c3876beeaed32280af88244e8050078619a8Douglas Gregor    FunctionScopes.back()->Returns.push_back(Result);
2600dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
26015077c3876beeaed32280af88244e8050078619a8Douglas Gregor  return Owned(Result);
26024eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff}
26035f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
260460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith/// Deduce the return type for a function from a returned expression, per
260560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith/// C++1y [dcl.spec.auto]p6.
260660e141e1f87211ca831de6821003d80fe20a06f3Richard Smithbool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
260760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith                                            SourceLocation ReturnLoc,
260860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith                                            Expr *&RetExpr,
260960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith                                            AutoType *AT) {
261060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
261160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
261260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  QualType Deduced;
261360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
261460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  if (RetExpr) {
261560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //  If the deduction is for a return statement and the initializer is
261660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //  a braced-init-list, the program is ill-formed.
261760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (isa<InitListExpr>(RetExpr)) {
261860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
261960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      return true;
262060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    }
262160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
262260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //  Otherwise, [...] deduce a value for U using the rules of template
262360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //  argument deduction.
262460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
262560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
262660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (DAR == DAR_Failed && !FD->isInvalidDecl())
262760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
262860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        << OrigResultType.getType() << RetExpr->getType();
262960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
263060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (DAR != DAR_Succeeded)
263160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      return true;
263260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  } else {
263360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //  In the case of a return with no operand, the initializer is considered
263460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //  to be void().
263560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    //
263660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    // Deduction here can only succeed if the return type is exactly 'cv auto'
263760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    // or 'decltype(auto)', so just check for that case directly.
263860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (!OrigResultType.getType()->getAs<AutoType>()) {
263960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
264060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        << OrigResultType.getType();
264160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      return true;
264260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    }
264360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    // We always deduce U = void in this case.
264460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
264560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (Deduced.isNull())
264660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      return true;
264760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  }
264860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
264960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //  If a function with a declared return type that contains a placeholder type
265060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //  has multiple return statements, the return type is deduced for each return
265160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //  statement. [...] if the type deduced is not the same in each deduction,
265260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //  the program is ill-formed.
265360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  if (AT->isDeduced() && !FD->isInvalidDecl()) {
265460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    AutoType *NewAT = Deduced->getContainedAutoType();
265560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (!Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
265660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
265760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        << (AT->isDecltypeAuto() ? 1 : 0)
265860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        << NewAT->getDeducedType() << AT->getDeducedType();
265960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      return true;
266060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    }
266160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  } else if (!FD->isInvalidDecl()) {
266260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    // Update all declarations of the function to have the deduced return type.
266360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    Context.adjustDeducedFunctionResultType(FD, Deduced);
266460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  }
266560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
266660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  return false;
266760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith}
266860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
266960d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
26709ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2671fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor  // Check for unexpanded parameter packs.
2672fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2673fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor    return StmtError();
26741093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier
267584b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  if (isa<CapturingScopeInfo>(getCurFunction()))
267684b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
26774cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
2678371f258e61e1365b951b17931a3c5ac1530fd1a0Chris Lattner  QualType FnRetType;
267938ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman  QualType RelatedRetType;
2680f7c41dab1a8de29b0991e853b8822bb0d1ddc01cMike Stump  if (const FunctionDecl *FD = getCurFunctionDecl()) {
2681371f258e61e1365b951b17931a3c5ac1530fd1a0Chris Lattner    FnRetType = FD->getResultType();
2682cd8ab51a44e80625d84126780b0d85a7732e25afRichard Smith    if (FD->isNoReturn())
26838662587fa75d3fb04f873e265841c9314c7f5523Chris Lattner      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
268479430e9983f5e67a378fc1f50cd6278f2cea8259Eli Friedman        << FD->getDeclName();
2685926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
268638ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman    FnRetType = MD->getResultType();
2687926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor    if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2688926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor      // In the implementation of a method with a related return type, the
26891093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier      // type used to type-check the validity of return statements within the
2690926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor      // method body is a pointer to the type of the class being implemented.
269138ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman      RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
269238ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman      RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2693926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor    }
2694926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor  } else // If we don't have a function/method context, bail.
2695c97fb9a394ce2cc5e664fcb472e93553528378adSteve Naroff    return StmtError();
26961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
269760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
269860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  // deduction.
269960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  bool HasDependentReturnType = FnRetType->isDependentType();
270060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  if (getLangOpts().CPlusPlus1y) {
270160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (AutoType *AT = FnRetType->getContainedAutoType()) {
270260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      FunctionDecl *FD = cast<FunctionDecl>(CurContext);
270360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      if (CurContext->isDependentContext())
270460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        HasDependentReturnType = true;
270560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
270660e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        FD->setInvalidDecl();
270760e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        return StmtError();
270860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      } else {
270960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith        FnRetType = FD->getResultType();
271060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      }
271160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    }
271260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  }
271360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith
27145077c3876beeaed32280af88244e8050078619a8Douglas Gregor  ReturnStmt *Result = 0;
27155cf216b7fa64b933b60743b0b26053e8e7aa87beChris Lattner  if (FnRetType->isVoidType()) {
27168d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky    if (RetValExp) {
271733deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      if (isa<InitListExpr>(RetValExp)) {
271833deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // We simply never allow init lists as the return value of void
271933deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // functions. This is compatible because this was never allowed before,
272033deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // so there's no legacy code to deal with.
272133deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
272233deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        int FunctionKind = 0;
272333deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        if (isa<ObjCMethodDecl>(CurDecl))
272433deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          FunctionKind = 1;
272533deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        else if (isa<CXXConstructorDecl>(CurDecl))
272633deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          FunctionKind = 2;
272733deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        else if (isa<CXXDestructorDecl>(CurDecl))
272833deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          FunctionKind = 3;
272933deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl
273033deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        Diag(ReturnLoc, diag::err_return_init_list)
273133deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          << CurDecl->getDeclName() << FunctionKind
273233deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          << RetValExp->getSourceRange();
273333deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl
273433deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // Drop the expression.
273533deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        RetValExp = 0;
273633deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      } else if (!RetValExp->isTypeDependent()) {
27378d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        // C99 6.8.6.4p1 (ext_ since GCC warns)
27388d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        unsigned D = diag::ext_return_has_expr;
27398d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        if (RetValExp->getType()->isVoidType())
27408d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          D = diag::ext_return_has_void_expr;
27418d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        else {
27428d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          ExprResult Result = Owned(RetValExp);
27438d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          Result = IgnoredValueConversions(Result.take());
27448d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          if (Result.isInvalid())
27458d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky            return StmtError();
27468d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          RetValExp = Result.take();
27478d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          RetValExp = ImpCastExprToType(RetValExp,
27488d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky                                        Context.VoidTy, CK_ToVoid).take();
27498d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        }
27504cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
27518d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        // return (some void expression); is legal in C++.
27528d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        if (D != diag::ext_return_has_void_expr ||
27534e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie            !getLangOpts().CPlusPlus) {
27548d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2755ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth
2756ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          int FunctionKind = 0;
2757ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          if (isa<ObjCMethodDecl>(CurDecl))
2758ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            FunctionKind = 1;
2759ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          else if (isa<CXXConstructorDecl>(CurDecl))
2760ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            FunctionKind = 2;
2761ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          else if (isa<CXXDestructorDecl>(CurDecl))
2762ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            FunctionKind = 3;
2763ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth
27648d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          Diag(ReturnLoc, D)
2765ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            << CurDecl->getDeclName() << FunctionKind
27668d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky            << RetValExp->getSourceRange();
27678d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        }
2768e878eb035b343d7d819c092102364ec9849716aeChris Lattner      }
27691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
277033deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      if (RetValExp) {
2771419563768ef4929a622d7c2b066856e82901bb91Richard Smith        ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2772419563768ef4929a622d7c2b066856e82901bb91Richard Smith        if (ER.isInvalid())
2773419563768ef4929a622d7c2b066856e82901bb91Richard Smith          return StmtError();
2774419563768ef4929a622d7c2b066856e82901bb91Richard Smith        RetValExp = ER.take();
277533deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      }
27765f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    }
2777dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
27785077c3876beeaed32280af88244e8050078619a8Douglas Gregor    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
277960e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  } else if (!RetValExp && !HasDependentReturnType) {
27803c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
27813c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    // C99 6.8.6.4p1 (ext_ since GCC warns)
27824e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
27833c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner
27843c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    if (FunctionDecl *FD = getCurFunctionDecl())
278508631c5fa053867146b5ee8be658c229f6bf127cChris Lattner      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
27863c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    else
278708631c5fa053867146b5ee8be658c229f6bf127cChris Lattner      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
27885077c3876beeaed32280af88244e8050078619a8Douglas Gregor    Result = new (Context) ReturnStmt(ReturnLoc);
27895077c3876beeaed32280af88244e8050078619a8Douglas Gregor  } else {
279060e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    assert(RetValExp || HasDependentReturnType);
27915077c3876beeaed32280af88244e8050078619a8Douglas Gregor    const VarDecl *NRVOCandidate = 0;
279260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith    if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
27935077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // we have a non-void function with an expression, continue checking
27945077c3876beeaed32280af88244e8050078619a8Douglas Gregor
27957cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
279638ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman
27975077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
27985077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
27995077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // function return.
28005077c3876beeaed32280af88244e8050078619a8Douglas Gregor
2801856d3798af7c2f7251e4a295f3da7a09ce4c62abJohn McCall      // In C++ the return statement is handled via a copy initialization,
28025077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // the C version of which boils down to CheckSingleAssignmentConstraints.
2803f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2804dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
28057cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall                                                                     RetType,
280658f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet                                                            NRVOCandidate != 0);
2807dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
28087cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall                                                       RetType, RetValExp);
28095077c3876beeaed32280af88244e8050078619a8Douglas Gregor      if (Res.isInvalid()) {
28107cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall        // FIXME: Clean up temporaries here anyway?
28115077c3876beeaed32280af88244e8050078619a8Douglas Gregor        return StmtError();
28125077c3876beeaed32280af88244e8050078619a8Douglas Gregor      }
28135077c3876beeaed32280af88244e8050078619a8Douglas Gregor      RetValExp = Res.takeAs<Expr>();
28147cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall
28157cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      // If we have a related result type, we need to implicitly
28167cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      // convert back to the formal result type.  We can't pretend to
28177cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      // initialize the result again --- we might end double-retaining
2818f92a509d870f05a0e26babd8072171957770649eFariborz Jahanian      // --- so instead we initialize a notional temporary.
28197cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      if (!RelatedRetType.isNull()) {
2820f92a509d870f05a0e26babd8072171957770649eFariborz Jahanian        Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
2821f92a509d870f05a0e26babd8072171957770649eFariborz Jahanian                                                            FnRetType);
28227cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall        Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
28237cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall        if (Res.isInvalid()) {
28247cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall          // FIXME: Clean up temporaries here anyway?
28257cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall          return StmtError();
28267cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall        }
28277cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall        RetValExp = Res.takeAs<Expr>();
28287cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      }
28297cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall
28307cca821e1acf0f1b4fe892c3111bfb2086832e4eJohn McCall      CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
283166724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor    }
2832dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2833b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall    if (RetValExp) {
2834419563768ef4929a622d7c2b066856e82901bb91Richard Smith      ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2835419563768ef4929a622d7c2b066856e82901bb91Richard Smith      if (ER.isInvalid())
2836419563768ef4929a622d7c2b066856e82901bb91Richard Smith        return StmtError();
2837419563768ef4929a622d7c2b066856e82901bb91Richard Smith      RetValExp = ER.take();
2838b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall    }
28395077c3876beeaed32280af88244e8050078619a8Douglas Gregor    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2840898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor  }
2841dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2842dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // If we need to check for the named return value optimization, save the
28435077c3876beeaed32280af88244e8050078619a8Douglas Gregor  // return statement in our scope for later processing.
28444e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
28455077c3876beeaed32280af88244e8050078619a8Douglas Gregor      !CurContext->isDependentContext())
28465077c3876beeaed32280af88244e8050078619a8Douglas Gregor    FunctionScopes.back()->Returns.push_back(Result);
28478e1e0543cc3b63e0bc116bae0d2f1e8fc530b436Chad Rosier
28485077c3876beeaed32280af88244e8050078619a8Douglas Gregor  return Owned(Result);
28495f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
28505f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
285160d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2852431e90e887c21c0d0d56fc12a2d359df8d53ea66Sebastian RedlSema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2853d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall                           SourceLocation RParen, Decl *Parm,
28549ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                           Stmt *Body) {
2855d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  VarDecl *Var = cast_or_null<VarDecl>(Parm);
2856160b5630aa781ac348303e1ae088d27016637778Douglas Gregor  if (Var && Var->isInvalidDecl())
2857160b5630aa781ac348303e1ae088d27016637778Douglas Gregor    return StmtError();
2858dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
28599ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
28603b1191d7eaf2f4984564e01ab84b6713a9d80e70Fariborz Jahanian}
28613b1191d7eaf2f4984564e01ab84b6713a9d80e70Fariborz Jahanian
286260d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
28639ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
28649ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2865161a9c5afaafb4d527b7efba9675a8b2cbbe32e0Fariborz Jahanian}
2866bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian
286760d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2868dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
28699ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                         MultiStmtArg CatchStmts, Stmt *Finally) {
28704e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().ObjCExceptions)
2871da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2872da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson
2873781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasBranchProtectedScope();
28748f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor  unsigned NumCatchStmts = CatchStmts.size();
28759ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
28765354e77e60e82828c7c2361f5c688c2667ab59ccBenjamin Kramer                                     CatchStmts.data(),
28778f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor                                     NumCatchStmts,
28789ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                     Finally));
2879bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian}
2880bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian
2881d1376ee0945a4eba0590ae33d14bade860b08a7dJohn McCallStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
2882d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor  if (Throw) {
2883429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    ExprResult Result = DefaultLvalueConversion(Throw);
2884429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    if (Result.isInvalid())
2885429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      return StmtError();
28865e3c67b4bd894a926282d24b4d0cbc0e123c9f4aJohn McCall
2887419563768ef4929a622d7c2b066856e82901bb91Richard Smith    Result = ActOnFinishFullExpr(Result.take());
2888419563768ef4929a622d7c2b066856e82901bb91Richard Smith    if (Result.isInvalid())
2889419563768ef4929a622d7c2b066856e82901bb91Richard Smith      return StmtError();
2890419563768ef4929a622d7c2b066856e82901bb91Richard Smith    Throw = Result.take();
2891419563768ef4929a622d7c2b066856e82901bb91Richard Smith
2892d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    QualType ThrowType = Throw->getType();
2893d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    // Make sure the expression type is an ObjC pointer or "void *".
2894d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    if (!ThrowType->isDependentType() &&
2895d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor        !ThrowType->isObjCObjectPointerType()) {
2896d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor      const PointerType *PT = ThrowType->getAs<PointerType>();
2897d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor      if (!PT || !PT->getPointeeType()->isVoidType())
2898d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2899d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor                         << Throw->getType() << Throw->getSourceRange());
2900d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    }
2901d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor  }
2902dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
29039ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2904d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor}
2905d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor
290660d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2907dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2908d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor                           Scope *CurScope) {
29094e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().ObjCExceptions)
2910da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2911da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson
29129ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (!Throw) {
2913e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    // @throw without an expression designates a rethrow (which much occur
2914e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    // in the context of an @catch clause).
2915e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    Scope *AtCatchParent = CurScope;
2916e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2917e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff      AtCatchParent = AtCatchParent->getParent();
2918e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    if (!AtCatchParent)
29194ab2414f297fab1b290e77bfc3b049ccf45eda81Steve Naroff      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2920dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  }
29219ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return BuildObjCAtThrowStmt(AtLoc, Throw);
292239f8f159c488a900e5958d5aab3e467af9ec8a2bFariborz Jahanian}
2923bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian
292407524039dce5c820f111a1b3f772b4261f004b4aJohn McCallExprResult
292507524039dce5c820f111a1b3f772b4261f004b4aJohn McCallSema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
292607524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  ExprResult result = DefaultLvalueConversion(operand);
292707524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  if (result.isInvalid())
292807524039dce5c820f111a1b3f772b4261f004b4aJohn McCall    return ExprError();
292907524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  operand = result.take();
29305e3c67b4bd894a926282d24b4d0cbc0e123c9f4aJohn McCall
2931a868a203a18571d091e5d226f5f100d4440f3d94Chris Lattner  // Make sure the expression type is an ObjC pointer or "void *".
293207524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  QualType type = operand->getType();
293307524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  if (!type->isDependentType() &&
293407524039dce5c820f111a1b3f772b4261f004b4aJohn McCall      !type->isObjCObjectPointerType()) {
293507524039dce5c820f111a1b3f772b4261f004b4aJohn McCall    const PointerType *pointerType = type->getAs<PointerType>();
293607524039dce5c820f111a1b3f772b4261f004b4aJohn McCall    if (!pointerType || !pointerType->getPointeeType()->isVoidType())
293707524039dce5c820f111a1b3f772b4261f004b4aJohn McCall      return Diag(atLoc, diag::error_objc_synchronized_expects_object)
293807524039dce5c820f111a1b3f772b4261f004b4aJohn McCall               << type << operand->getSourceRange();
2939a868a203a18571d091e5d226f5f100d4440f3d94Chris Lattner  }
29401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
294107524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  // The operand to @synchronized is a full-expression.
2942419563768ef4929a622d7c2b066856e82901bb91Richard Smith  return ActOnFinishFullExpr(operand);
294307524039dce5c820f111a1b3f772b4261f004b4aJohn McCall}
294407524039dce5c820f111a1b3f772b4261f004b4aJohn McCall
294507524039dce5c820f111a1b3f772b4261f004b4aJohn McCallStmtResult
294607524039dce5c820f111a1b3f772b4261f004b4aJohn McCallSema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
294707524039dce5c820f111a1b3f772b4261f004b4aJohn McCall                                  Stmt *SyncBody) {
294807524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  // We can't jump into or indirect-jump out of a @synchronized block.
294907524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  getCurFunction()->setHasBranchProtectedScope();
29509ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2951fa3ee8e6776634caf064ba5928ca7699d317a280Fariborz Jahanian}
29524b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl
29534b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
29544b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl/// and creates a proper catch handler from them.
295560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2956d226f65006733ed7f709c3174f22ce33391cb58fJohn McCallSema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
29579ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                         Stmt *HandlerBlock) {
29584b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl  // There's nothing to test that ActOnExceptionDecl didn't already test.
29598189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) CXXCatchStmt(CatchLoc,
2960d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall                                          cast_or_null<VarDecl>(ExDecl),
29619ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                          HandlerBlock));
29624b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl}
29638351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl
2964f85e193739c953358c865005855253af4f68a497John McCallStmtResult
2965f85e193739c953358c865005855253af4f68a497John McCallSema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2966f85e193739c953358c865005855253af4f68a497John McCall  getCurFunction()->setHasBranchProtectedScope();
2967f85e193739c953358c865005855253af4f68a497John McCall  return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2968f85e193739c953358c865005855253af4f68a497John McCall}
2969f85e193739c953358c865005855253af4f68a497John McCall
29703c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohmannamespace {
29713c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohman
2972c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redlclass TypeWithHandler {
2973c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  QualType t;
2974c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  CXXCatchStmt *stmt;
2975c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redlpublic:
2976c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2977c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  : t(type), stmt(statement) {}
2978c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl
29790953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  // An arbitrary order is fine as long as it places identical
29800953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  // types next to each other.
2981c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  bool operator<(const TypeWithHandler &y) const {
29820953e767ff7817f97b3ab20896b229891eeff45bJohn McCall    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2983c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      return true;
29840953e767ff7817f97b3ab20896b229891eeff45bJohn McCall    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2985c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      return false;
2986c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    else
2987c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2988c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
29891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2990c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  bool operator==(const TypeWithHandler& other) const {
29910953e767ff7817f97b3ab20896b229891eeff45bJohn McCall    return t == other.t;
2992c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
29931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2994c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  CXXCatchStmt *getCatchStmt() const { return stmt; }
2995c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  SourceLocation getTypeSpecStartLoc() const {
2996c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2997c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
2998c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl};
2999c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl
30003c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohman}
30013c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohman
30028351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
30038351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl/// handlers and creates a try statement from them.
300460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
30059ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
30068351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl                       MultiStmtArg RawHandlers) {
3007729b853f4bfa83e53c638a06a9dccf83b4e1f720Anders Carlsson  // Don't report an error if 'try' is used in system headers.
30084e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().CXXExceptions &&
3009729b853f4bfa83e53c638a06a9dccf83b4e1f720Anders Carlsson      !getSourceManager().isInSystemHeader(TryLoc))
3010729b853f4bfa83e53c638a06a9dccf83b4e1f720Anders Carlsson      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
30117f11d9cf5df1f8ce82af46eabc4ec5cec7d580b0Anders Carlsson
30128351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  unsigned NumHandlers = RawHandlers.size();
30138351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  assert(NumHandlers > 0 &&
30148351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl         "The parser shouldn't call this if there are no handlers.");
30155354e77e60e82828c7c2361f5c688c2667ab59ccBenjamin Kramer  Stmt **Handlers = RawHandlers.data();
30168351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl
30175f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TypeWithHandler, 8> TypesWithHandlers;
30181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
30191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (unsigned i = 0; i < NumHandlers; ++i) {
30205f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3021c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    if (!Handler->getExceptionDecl()) {
3022c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      if (i < NumHandlers - 1)
3023c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl        return StmtError(Diag(Handler->getLocStart(),
3024c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl                              diag::err_early_catch_all));
30251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3026c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      continue;
3027c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    }
30281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3029c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    const QualType CaughtType = Handler->getCaughtType();
3030c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3031c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3032c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
3033c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl
3034c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  // Detect handlers for the same type as an earlier one.
3035c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  if (NumHandlers > 1) {
3036c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
30371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3038c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    TypeWithHandler prev = TypesWithHandlers[0];
3039c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3040c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      TypeWithHandler curr = TypesWithHandlers[i];
30411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3042c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      if (curr == prev) {
3043c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl        Diag(curr.getTypeSpecStartLoc(),
3044c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl             diag::warn_exception_caught_by_earlier_handler)
3045c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl          << curr.getCatchStmt()->getCaughtType().getAsString();
3046c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl        Diag(prev.getTypeSpecStartLoc(),
3047c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl             diag::note_previous_exception_handler)
3048c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl          << prev.getCatchStmt()->getCaughtType().getAsString();
3049c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      }
30501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3051c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      prev = curr;
3052c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    }
30538351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  }
30541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3055781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasBranchProtectedScope();
3056b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
30578351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // FIXME: We should detect handlers that cannot catch anything because an
30588351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // earlier handler catches a superclass. Need to find a method that is not
30598351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // quadratic for this.
30608351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // Neither of these are explicitly forbidden, but every compiler detects them
30618351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // and warns.
30628351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl
30639ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
306407cf58c96dc599d1c25dae4efd9445b6f5d3596cNico Weber                                  llvm::makeArrayRef(Handlers, NumHandlers)));
30658351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl}
306628bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
306728bbe4b8acc338476fe0825769b41fb32b423c72John WiegleyStmtResult
306828bbe4b8acc338476fe0825769b41fb32b423c72John WiegleySema::ActOnSEHTryBlock(bool IsCXXTry,
306928bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                       SourceLocation TryLoc,
307028bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                       Stmt *TryBlock,
307128bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                       Stmt *Handler) {
307228bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  assert(TryBlock && Handler);
307328bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
307428bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  getCurFunction()->setHasBranchProtectedScope();
307528bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
307628bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
307728bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley}
307828bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
307928bbe4b8acc338476fe0825769b41fb32b423c72John WiegleyStmtResult
308028bbe4b8acc338476fe0825769b41fb32b423c72John WiegleySema::ActOnSEHExceptBlock(SourceLocation Loc,
308128bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                          Expr *FilterExpr,
308228bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                          Stmt *Block) {
308328bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  assert(FilterExpr && Block);
308428bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
308528bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  if(!FilterExpr->getType()->isIntegerType()) {
308658f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet    return StmtError(Diag(FilterExpr->getExprLoc(),
308758f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet                     diag::err_filter_expression_integral)
308858f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet                     << FilterExpr->getType());
308928bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  }
309028bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
309128bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
309228bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley}
309328bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
309428bbe4b8acc338476fe0825769b41fb32b423c72John WiegleyStmtResult
309528bbe4b8acc338476fe0825769b41fb32b423c72John WiegleySema::ActOnSEHFinallyBlock(SourceLocation Loc,
309628bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                           Stmt *Block) {
309728bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  assert(Block);
309828bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
309928bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley}
3100ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor
3101ba0513de93d2fab6db5ab30b6927209fcc883078Douglas GregorStmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3102ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            bool IsIfExists,
3103ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            NestedNameSpecifierLoc QualifierLoc,
3104ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            DeclarationNameInfo NameInfo,
3105ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            Stmt *Nested)
3106ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor{
3107ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
31081093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier                                             QualifierLoc, NameInfo,
3109ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                             cast<CompoundStmt>(Nested));
3110ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor}
3111ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor
3112ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor
31131093f4928a4263d08b44d96e468a42515d8a28f3Chad RosierStmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3114ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            bool IsIfExists,
31151093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier                                            CXXScopeSpec &SS,
3116ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            UnqualifiedId &Name,
3117ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            Stmt *Nested) {
31181093f4928a4263d08b44d96e468a42515d8a28f3Chad Rosier  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3119ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                    SS.getWithLocInContext(Context),
3120ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                    GetNameFromUnqualifiedId(Name),
3121ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                    Nested);
3122ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor}
31236afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31246afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. SirajRecordDecl*
31258c045ace381972f41d385b0a661ccf172834f459Ben LangmuirSema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
31268c045ace381972f41d385b0a661ccf172834f459Ben Langmuir                                   unsigned NumParams) {
31276afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  DeclContext *DC = CurContext;
31286afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
31296afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    DC = DC->getParent();
31306afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31316afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  RecordDecl *RD = 0;
31326afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  if (getLangOpts().CPlusPlus)
31336afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
31346afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  else
31356afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
31366afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31376afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  DC->addDecl(RD);
31386afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  RD->setImplicit();
31396afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  RD->startDefinition();
31406afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31418c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  CD = CapturedDecl::Create(Context, CurContext, NumParams);
31426afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  DC->addDecl(CD);
31436afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31448c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  // Build the context parameter
31458c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  assert(NumParams > 0 && "CapturedStmt requires context parameter");
31468c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  DC = CapturedDecl::castToDeclContext(CD);
31478c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  IdentifierInfo *VarName = &Context.Idents.get("__context");
31488c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
31498c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  ImplicitParamDecl *Param
31508c045ace381972f41d385b0a661ccf172834f459Ben Langmuir    = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
31518c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  DC->addDecl(Param);
31528c045ace381972f41d385b0a661ccf172834f459Ben Langmuir
31538c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  CD->setContextParam(Param);
31548c045ace381972f41d385b0a661ccf172834f459Ben Langmuir
31556afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  return RD;
31566afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj}
31576afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31586afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Sirajstatic void buildCapturedStmtCaptureList(
31596afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    SmallVectorImpl<CapturedStmt::Capture> &Captures,
31606afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    SmallVectorImpl<Expr *> &CaptureInits,
31616afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    ArrayRef<CapturingScopeInfo::Capture> Candidates) {
31626afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31636afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
31646afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
31656afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31666afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    if (Cap->isThisCapture()) {
31676afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj      Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
31686afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj                                               CapturedStmt::VCK_This));
31690d8e9646bc000bab521ce52ed294209a92298cefRichard Smith      CaptureInits.push_back(Cap->getInitExpr());
31706afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj      continue;
31716afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    }
31726afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31736afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    assert(Cap->isReferenceCapture() &&
31746afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj           "non-reference capture not yet implemented");
31756afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31766afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
31776afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj                                             CapturedStmt::VCK_ByRef,
31786afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj                                             Cap->getVariable()));
31790d8e9646bc000bab521ce52ed294209a92298cefRichard Smith    CaptureInits.push_back(Cap->getInitExpr());
31806afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  }
31816afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj}
31826afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31836afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Sirajvoid Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
31849fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan                                    CapturedRegionKind Kind,
31859fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan                                    unsigned NumParams) {
31866afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  CapturedDecl *CD = 0;
31878c045ace381972f41d385b0a661ccf172834f459Ben Langmuir  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
31886afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31896afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  // Enter the capturing scope for this captured region.
31906afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  PushCapturedRegionScope(CurScope, CD, RD, Kind);
31916afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31926afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  if (CurScope)
31936afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    PushDeclContext(CurScope, CD);
31946afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  else
31956afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    CurContext = CD;
31966afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
31976afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  PushExpressionEvaluationContext(PotentiallyEvaluated);
31986afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj}
31996afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32009fd6b8f5a73788f288edd01fa99d434d1e6588adWei Panvoid Sema::ActOnCapturedRegionError() {
32016afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  DiscardCleanupsInEvaluationContext();
32026afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  PopExpressionEvaluationContext();
32036afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32046afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
32056afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  RecordDecl *Record = RSI->TheRecordDecl;
32066afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  Record->setInvalidDecl();
32076afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32086afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  SmallVector<Decl*, 4> Fields;
32096afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  for (RecordDecl::field_iterator I = Record->field_begin(),
32106afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj                                  E = Record->field_end(); I != E; ++I)
32116afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj    Fields.push_back(*I);
32126afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
32136afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj              SourceLocation(), SourceLocation(), /*AttributeList=*/0);
32146afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32159fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan  PopDeclContext();
32166afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  PopFunctionScopeInfo();
32176afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj}
32186afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32196afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. SirajStmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
32206afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
32216afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32226afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  SmallVector<CapturedStmt::Capture, 4> Captures;
32236afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  SmallVector<Expr *, 4> CaptureInits;
32246afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
32256afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32266afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  CapturedDecl *CD = RSI->TheCapturedDecl;
32276afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  RecordDecl *RD = RSI->TheRecordDecl;
32286afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32299fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan  CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
32309fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan                                           RSI->CapRegionKind, Captures,
32316afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj                                           CaptureInits, CD, RD);
32326afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32336afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  CD->setBody(Res->getCapturedStmt());
32346afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  RD->completeDefinition();
32356afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32369fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan  DiscardCleanupsInEvaluationContext();
32379fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan  PopExpressionEvaluationContext();
32389fd6b8f5a73788f288edd01fa99d434d1e6588adWei Pan
32396afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  PopDeclContext();
32406afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  PopFunctionScopeInfo();
32416afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj
32426afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  return Owned(Res);
32436afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj}
3244