blob: 85728619880cf4e4bbbbe868557ad5ba67c17a22 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall1cd76e82011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000022#include "clang/AST/StmtCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/AST/StmtObjC.h"
John McCall209acbd2010-04-06 22:24:14 +000024#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
Richard Smith41956372013-01-14 22:39:08 +000038StmtResult Sema::ActOnExprStmt(ExprResult FE) {
39 if (FE.isInvalid())
40 return StmtError();
41
42 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43 /*DiscardedValue*/ true);
44 if (FE.isInvalid())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000045 return StmtError();
46
Chris Lattner834a72a2008-07-25 23:18:17 +000047 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48 // void expression for its side effects. Conversion to void allows any
49 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000050
Chris Lattner834a72a2008-07-25 23:18:17 +000051 // Same thing in for stmt first clause (when expr) and third clause.
Richard Smith41956372013-01-14 22:39:08 +000052 return Owned(static_cast<Stmt*>(FE.take()));
Reid Spencer5f016e22007-07-11 17:01:13 +000053}
54
55
John McCallb760f112013-03-22 02:10:40 +000056StmtResult Sema::ActOnExprStmtError() {
57 DiscardCleanupsInEvaluationContext();
58 return StmtError();
59}
60
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000061StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000062 bool HasLeadingEmptyMacro) {
63 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000064}
65
Chris Lattner337e5502011-02-18 01:27:55 +000066StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000068 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner20401692009-04-12 20:13:14 +000070 // If we have an invalid decl, just return an error.
71 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner24e1e702009-03-04 04:23:07 +000073 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000074}
75
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000076void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
77 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Wei Pan55c7d022013-05-03 21:07:45 +000078
Douglas Gregor12849d02013-04-08 20:52:24 +000079 // If we don't have a declaration, or we have an invalid declaration,
80 // just return.
81 if (DG.isNull() || !DG.isSingleDecl())
82 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000083
Douglas Gregor12849d02013-04-08 20:52:24 +000084 Decl *decl = DG.getSingleDecl();
85 if (!decl || decl->isInvalidDecl())
86 return;
87
88 // Only variable declarations are permitted.
89 VarDecl *var = dyn_cast<VarDecl>(decl);
90 if (!var) {
91 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
92 decl->setInvalidDecl();
93 return;
94 }
John McCallf85e1932011-06-15 23:02:42 +000095
John McCall7acddac2011-06-17 06:42:21 +000096 // foreach variables are never actually initialized in the way that
97 // the parser came up with.
98 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000099
John McCall7acddac2011-06-17 06:42:21 +0000100 // In ARC, we don't need to retain the iteration variable of a fast
101 // enumeration loop. Rather than actually trying to catch that
102 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +0000103 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +0000104 QualType type = var->getType();
105
106 // Only do this if we inferred the lifetime. Inferred lifetime
107 // will show up as a local qualifier because explicit lifetime
108 // should have shown up as an AttributedType instead.
109 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
110 // Add 'const' and mark the variable as pseudo-strong.
111 var->setType(type.withConst());
112 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +0000113 }
114 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +0000115}
116
Chandler Carruthec8058f2011-08-17 09:34:37 +0000117/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118///
119/// Adding a cast to void (or other expression wrappers) will prevent the
120/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000121static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000123 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000124
125 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
126 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000127 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000128
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000129 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000130 IsNotEqual = Op->getOpcode() == BO_NE;
131 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000132 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
133 if (Op->getOperator() != OO_EqualEqual &&
134 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000135 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000136
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
139 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000140 } else {
141 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000142 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000143 }
144
145 // Suppress warnings when the operator, suspicious as it may be, comes from
146 // a macro expansion.
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +0000147 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthec8058f2011-08-17 09:34:37 +0000148 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000149
Chandler Carruthec8058f2011-08-17 09:34:37 +0000150 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000151 << (unsigned)IsNotEqual << E->getSourceRange();
152
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000153 // If the LHS is a plausible entity to assign to, provide a fixit hint to
154 // correct common typos.
155 if (CanAssign) {
156 if (IsNotEqual)
157 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
158 << FixItHint::CreateReplacement(Loc, "|=");
159 else
160 S.Diag(Loc, diag::note_equality_comparison_to_assign)
161 << FixItHint::CreateReplacement(Loc, "=");
162 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000163
164 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000165}
166
Anders Carlsson636463e2009-07-30 22:17:18 +0000167void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000168 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
169 return DiagnoseUnusedExprResult(Label->getSubStmt());
170
Anders Carlsson75443112009-07-30 22:39:03 +0000171 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000172 if (!E)
173 return;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000174 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000175 // In most cases, we don't want to warn if the expression is written in a
176 // macro body, or if the macro comes from a system header. If the offending
177 // expression is a call to a function with the warn_unused_result attribute,
178 // we warn no matter the location. Because of the order in which the various
179 // checks need to happen, we factor out the macro-related test here.
180 bool ShouldSuppress =
181 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
182 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson636463e2009-07-30 22:17:18 +0000183
Eli Friedmana6115062012-05-24 00:47:05 +0000184 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000185 SourceLocation Loc;
186 SourceRange R1, R2;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000187 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000188 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Chris Lattner06b3a062012-08-31 22:39:21 +0000190 // If this is a GNU statement expression expanded from a macro, it is probably
191 // unused because it is a function-like macro that can be used as either an
192 // expression or statement. Don't warn, because it is almost certainly a
193 // false positive.
194 if (isa<StmtExpr>(E) && Loc.isMacroID())
195 return;
196
Chris Lattner419cfb32009-08-16 16:57:27 +0000197 // Okay, we have an unused result. Depending on what the base expression is,
198 // we might want to make a more specific diagnostic. Check for one of these
199 // cases now.
200 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000201 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000202 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000203 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
204 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000205
Chandler Carruthec8058f2011-08-17 09:34:37 +0000206 if (DiagnoseUnusedComparison(*this, E))
207 return;
208
Eli Friedmana6115062012-05-24 00:47:05 +0000209 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000210 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000211 if (E->getType()->isVoidType())
212 return;
213
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000214 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000215 // a more specific message to make it clear what is happening. If the call
216 // is written in a macro body, only warn if it has the warn_unused_result
217 // attribute.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000218 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000219 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000220 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000221 return;
222 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000223 if (ShouldSuppress)
224 return;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000225 if (FD->getAttr<PureAttr>()) {
226 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
227 return;
228 }
229 if (FD->getAttr<ConstAttr>()) {
230 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
231 return;
232 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000233 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000234 } else if (ShouldSuppress)
235 return;
236
237 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000238 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000239 Diag(Loc, diag::err_arc_unused_init_message) << R1;
240 return;
241 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000242 const ObjCMethodDecl *MD = ME->getMethodDecl();
243 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000244 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000245 return;
246 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000247 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
248 const Expr *Source = POE->getSyntacticForm();
249 if (isa<ObjCSubscriptRefExpr>(Source))
250 DiagID = diag::warn_unused_container_subscript_expr;
251 else
252 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000253 } else if (const CXXFunctionalCastExpr *FC
254 = dyn_cast<CXXFunctionalCastExpr>(E)) {
255 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
256 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
257 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000258 }
John McCall209acbd2010-04-06 22:24:14 +0000259 // Diagnose "(void*) blah" as a typo for "(void) blah".
260 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
261 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
262 QualType T = TI->getType();
263
264 // We really do want to use the non-canonical type here.
265 if (T == Context.VoidPtrTy) {
David Blaikie39e6ab42013-02-18 22:06:02 +0000266 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall209acbd2010-04-06 22:24:14 +0000267
268 Diag(Loc, diag::warn_unused_voidptr)
269 << FixItHint::CreateRemoval(TL.getStarLoc());
270 return;
271 }
272 }
273
Eli Friedmana6115062012-05-24 00:47:05 +0000274 if (E->isGLValue() && E->getType().isVolatileQualified()) {
275 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
276 return;
277 }
278
Ted Kremenek351ba912011-02-23 01:52:04 +0000279 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000280}
281
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000282void Sema::ActOnStartOfCompoundStmt() {
283 PushCompoundScope();
284}
285
286void Sema::ActOnFinishOfCompoundStmt() {
287 PopCompoundScope();
288}
289
290sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
291 return getCurFunction()->CompoundScopes.back();
292}
293
John McCall60d7b3a2010-08-24 06:29:42 +0000294StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000295Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000296 MultiStmtArg elts, bool isStmtExpr) {
297 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000298 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000299 // If we're in C89 mode, check that we don't have any decls after stmts. If
300 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000301 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000302 // Note that __extension__ can be around a decl.
303 unsigned i = 0;
304 // Skip over all declarations.
305 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
306 /*empty*/;
307
308 // We found the end of the list or a statement. Scan for another declstmt.
309 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
310 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000312 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000313 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000314 Diag(D->getLocation(), diag::ext_mixed_decls_code);
315 }
316 }
Chris Lattner98414c12007-08-31 21:49:55 +0000317 // Warn about unused expressions in statements.
318 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000319 // Ignore statements that are last in a statement expression.
320 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000321 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Anders Carlsson636463e2009-07-30 22:17:18 +0000323 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000324 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000325
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000326 // Check for suspicious empty body (null statement) in `for' and `while'
327 // statements. Don't do anything for template instantiations, this just adds
328 // noise.
329 if (NumElts != 0 && !CurrentInstantiationScope &&
330 getCurCompoundScope().HasEmptyLoopBodies) {
331 for (unsigned i = 0; i != NumElts - 1; ++i)
332 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
333 }
334
Nico Weberd36aa352012-12-29 20:03:39 +0000335 return Owned(new (Context) CompoundStmt(Context,
336 llvm::makeArrayRef(Elts, NumElts),
337 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000338}
339
John McCall60d7b3a2010-08-24 06:29:42 +0000340StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000341Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
342 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000343 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000344 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000345
John McCall781472f2010-08-25 08:40:02 +0000346 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000347 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000348 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000349 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000350
Richard Smith80ad52f2013-01-02 11:42:31 +0000351 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000352 // C99 6.8.4.2p3: The expression shall be an integer constant.
353 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000354 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
355 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
356 if (!LHSVal)
357 return StmtError();
358 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000359
360 // GCC extension: The expression shall be an integer constant.
361
Richard Smith282e7e62012-02-04 09:53:13 +0000362 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
363 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
364 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000365 }
366 }
Ben Langmuira0152d42013-04-29 13:07:42 +0000367
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000368 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
369 getLangOpts().CPlusPlus11).take();
370 if (RHSVal)
371 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
372 getLangOpts().CPlusPlus11).take();
Richard Smith8ef7b202012-01-18 23:55:52 +0000373
Douglas Gregordbb26db2009-05-15 23:57:33 +0000374 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
375 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000376 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000377 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378}
379
Chris Lattner24e1e702009-03-04 04:23:07 +0000380/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000381void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000382 DiagnoseUnusedExprResult(SubStmt);
383
Chris Lattner24e1e702009-03-04 04:23:07 +0000384 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000385 CS->setSubStmt(SubStmt);
386}
387
John McCall60d7b3a2010-08-24 06:29:42 +0000388StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000389Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000390 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000391 DiagnoseUnusedExprResult(SubStmt);
392
John McCall781472f2010-08-25 08:40:02 +0000393 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000394 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000395 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000396 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000397
Douglas Gregordbb26db2009-05-15 23:57:33 +0000398 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000399 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000400 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000401}
402
John McCall60d7b3a2010-08-24 06:29:42 +0000403StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000404Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
405 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000406 // If the label was multiply defined, reject it now.
407 if (TheDecl->getStmt()) {
408 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
409 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000410 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 }
Sebastian Redlde307472009-01-11 00:38:46 +0000412
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000413 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000414 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
415 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000416 if (!TheDecl->isGnuLocal()) {
417 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000418 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000419 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000420 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000421}
422
Richard Smith534986f2012-04-14 00:33:13 +0000423StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000424 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000425 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000426 // Fill in the declaration and return it.
427 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000428 return Owned(LS);
429}
430
John McCall60d7b3a2010-08-24 06:29:42 +0000431StmtResult
John McCalld226f652010-08-21 09:40:31 +0000432Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000433 Stmt *thenStmt, SourceLocation ElseLoc,
434 Stmt *elseStmt) {
Argyrios Kyrtzidis820b23d2013-02-15 18:34:13 +0000435 // If the condition was invalid, discard the if statement. We could recover
436 // better by replacing it with a valid expr, but don't do that yet.
437 if (!CondVal.get() && !CondVar) {
438 getCurFunction()->setHasDroppedStmt();
439 return StmtError();
440 }
441
John McCall60d7b3a2010-08-24 06:29:42 +0000442 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000444 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000445 if (CondVar) {
446 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000447 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000448 if (CondResult.isInvalid())
449 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000450 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000451 Expr *ConditionExpr = CondResult.takeAs<Expr>();
452 if (!ConditionExpr)
453 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454
Anders Carlsson75443112009-07-30 22:39:03 +0000455 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000456
John McCall9ae2f072010-08-23 23:25:46 +0000457 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000458 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
459 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000460 }
461
Anders Carlsson75443112009-07-30 22:39:03 +0000462 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000463
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000464 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000465 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000466}
467
Chris Lattnerf4021e72007-08-23 05:46:52 +0000468/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
469/// the specified width and sign. If an overflow occurs, detect it and emit
470/// the specified diagnostic.
471void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
472 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000473 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000474 unsigned DiagID) {
475 // Perform a conversion to the promoted condition type if needed.
476 if (NewWidth > Val.getBitWidth()) {
477 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000478 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000479 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000480
481 // If the input was signed and negative and the output is
482 // unsigned, don't bother to warn: this is implementation-defined
483 // behavior.
484 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000485 } else if (NewWidth < Val.getBitWidth()) {
486 // If this is a truncation, check for overflow.
487 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000488 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000489 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000490 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000491 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000492 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000493 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Chris Lattnerf4021e72007-08-23 05:46:52 +0000495 // Regardless of whether a diagnostic was emitted, really do the
496 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000497 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000498 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000499 } else if (NewSign != Val.isSigned()) {
500 // Convert the sign to match the sign of the condition. This can cause
501 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000502 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000503 // behavior.
504 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000505 llvm::APSInt OldVal(Val);
506 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000507 }
508}
509
Chris Lattner0471f5b2007-08-23 18:29:20 +0000510namespace {
511 struct CaseCompareFunctor {
512 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
513 const llvm::APSInt &RHS) {
514 return LHS.first < RHS;
515 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000516 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
517 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
518 return LHS.first < RHS.first;
519 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000520 bool operator()(const llvm::APSInt &LHS,
521 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
522 return LHS < RHS.first;
523 }
524 };
525}
526
Chris Lattner764a7ce2007-09-21 18:15:22 +0000527/// CmpCaseVals - Comparison predicate for sorting case values.
528///
529static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
530 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
531 if (lhs.first < rhs.first)
532 return true;
533
534 if (lhs.first == rhs.first &&
535 lhs.second->getCaseLoc().getRawEncoding()
536 < rhs.second->getCaseLoc().getRawEncoding())
537 return true;
538 return false;
539}
540
Douglas Gregorba915af2010-02-08 22:24:16 +0000541/// CmpEnumVals - Comparison predicate for sorting enumeration values.
542///
543static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
544 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
545{
546 return lhs.first < rhs.first;
547}
548
549/// EqEnumVals - Comparison preficate for uniqing enumeration values.
550///
551static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
552 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
553{
554 return lhs.first == rhs.first;
555}
556
Chris Lattner5f048812009-10-16 16:45:22 +0000557/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
558/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000559static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
560 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
561 expr = cleanups->getSubExpr();
562 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
563 if (impcast->getCastKind() != CK_IntegralCast) break;
564 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000565 }
566 return expr->getType();
567}
568
John McCall60d7b3a2010-08-24 06:29:42 +0000569StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000571 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000572 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000573
Douglas Gregor586596f2010-05-06 17:25:47 +0000574 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000575 if (CondVar) {
576 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000577 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
578 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000579 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580
John McCall9ae2f072010-08-23 23:25:46 +0000581 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
John McCall9ae2f072010-08-23 23:25:46 +0000584 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000585 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
Douglas Gregorab41fe92012-05-04 22:38:52 +0000587 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
588 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000589
Douglas Gregorab41fe92012-05-04 22:38:52 +0000590 public:
591 SwitchConvertDiagnoser(Expr *Cond)
Richard Smith097e0a22013-05-21 19:05:48 +0000592 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
593 Cond(Cond) {}
Chad Rosier8e1e0542012-06-20 18:51:04 +0000594
Richard Smith097e0a22013-05-21 19:05:48 +0000595 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
596 QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000597 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
598 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000599
Richard Smith097e0a22013-05-21 19:05:48 +0000600 virtual SemaDiagnosticBuilder diagnoseIncomplete(
601 Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000602 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
603 << T << Cond->getSourceRange();
604 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000605
Richard Smith097e0a22013-05-21 19:05:48 +0000606 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
607 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000608 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
609 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000610
Richard Smith097e0a22013-05-21 19:05:48 +0000611 virtual SemaDiagnosticBuilder noteExplicitConv(
612 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000613 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
614 << ConvTy->isEnumeralType() << ConvTy;
615 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000616
Richard Smith097e0a22013-05-21 19:05:48 +0000617 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
618 QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000619 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
620 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000621
Richard Smith097e0a22013-05-21 19:05:48 +0000622 virtual SemaDiagnosticBuilder noteAmbiguous(
623 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000624 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
625 << ConvTy->isEnumeralType() << ConvTy;
626 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000627
Richard Smith097e0a22013-05-21 19:05:48 +0000628 virtual SemaDiagnosticBuilder diagnoseConversion(
629 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
630 llvm_unreachable("conversion functions are permitted");
Douglas Gregorab41fe92012-05-04 22:38:52 +0000631 }
632 } SwitchDiagnoser(Cond);
633
Richard Smith097e0a22013-05-21 19:05:48 +0000634 CondResult =
635 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCall9ae2f072010-08-23 23:25:46 +0000636 if (CondResult.isInvalid()) return StmtError();
637 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000638
John McCalla8e0cd82011-08-06 07:30:58 +0000639 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
640 CondResult = UsualUnaryConversions(Cond);
641 if (CondResult.isInvalid()) return StmtError();
642 Cond = CondResult.take();
643
John McCalld226f652010-08-21 09:40:31 +0000644 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000645 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000646 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000647 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000648 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000649 }
John McCallb60a77e2010-08-01 00:26:45 +0000650
John McCall781472f2010-08-25 08:40:02 +0000651 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
John McCall9ae2f072010-08-23 23:25:46 +0000653 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000654 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000655 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000656}
657
Gabor Greif28164ab2010-10-01 22:05:14 +0000658static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
659 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000660 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000661 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000662 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000663 Val.setIsSigned(IsSigned);
664}
665
John McCall60d7b3a2010-08-24 06:29:42 +0000666StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000667Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
668 Stmt *BodyStmt) {
669 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000670 assert(SS == getCurFunction()->SwitchStack.back() &&
671 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000672
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000673 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000674 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000675
Chris Lattnerf4021e72007-08-23 05:46:52 +0000676 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000677 if (!CondExpr) return StmtError();
678
679 QualType CondType = CondExpr->getType();
680
John McCall0fb97082010-05-18 03:19:21 +0000681 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000682 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000683 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000684
Chris Lattner5f048812009-10-16 16:45:22 +0000685 // C++ 6.4.2.p2:
686 // Integral promotions are performed (on the switch condition).
687 //
688 // A case value unrepresentable by the original switch condition
689 // type (before the promotion) doesn't make sense, even when it can
690 // be represented by the promoted type. Therefore we need to find
691 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000692 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000693 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000695 // appropriate type now, just return an error.
696 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000697 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000698
Chris Lattner2b334bb2010-04-16 23:34:13 +0000699 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000700 // switch(bool_expr) {...} is often a programmer error, e.g.
701 // switch(n && mask) { ... } // Doh - should be "n & mask".
702 // One can always use an if statement instead of switch(bool_expr).
703 Diag(SwitchLoc, diag::warn_bool_switch_condition)
704 << CondExpr->getSourceRange();
705 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000706 }
Sebastian Redlde307472009-01-11 00:38:46 +0000707
Chris Lattnerf4021e72007-08-23 05:46:52 +0000708 // Get the bitwidth of the switched-on value before promotions. We must
709 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000710 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000711 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000712 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000713 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000714 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000715 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattnerf4021e72007-08-23 05:46:52 +0000717 // Accumulate all of the case values in a vector so that we can sort them
718 // and detect duplicates. This vector contains the APInt for the case after
719 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000720 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000721 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattnerf4021e72007-08-23 05:46:52 +0000723 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000724 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
725 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Chris Lattnerf4021e72007-08-23 05:46:52 +0000727 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000729 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Douglas Gregordbb26db2009-05-15 23:57:33 +0000731 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000732 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000734 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000735 if (TheDefaultStmt) {
736 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000737 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000738
Chris Lattnerf4021e72007-08-23 05:46:52 +0000739 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000740 // we'll return a valid AST. This requires recursing down the AST and
741 // finding it, not something we are set up to do right now. For now,
742 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000743 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000744 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000745 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattnerf4021e72007-08-23 05:46:52 +0000747 } else {
748 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner1e0a3902008-01-16 19:17:22 +0000750 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000751
752 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
753 HasDependentValue = true;
754 break;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Richard Smith8ef7b202012-01-18 23:55:52 +0000757 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Richard Smith80ad52f2013-01-02 11:42:31 +0000759 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000760 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
761 // constant expression of the promoted type of the switch condition.
762 ExprResult ConvLo =
763 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
764 if (ConvLo.isInvalid()) {
765 CaseListIsErroneous = true;
766 continue;
767 }
768 Lo = ConvLo.take();
769 } else {
770 // We already verified that the expression has a i-c-e value (C99
771 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000772 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000773
774 // If the LHS is not the same type as the condition, insert an implicit
775 // cast.
776 Lo = DefaultLvalueConversion(Lo).take();
777 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
778 }
779
780 // Convert the value to the same width/sign as the condition had prior to
781 // integral promotions.
782 //
783 // FIXME: This causes us to reject valid code:
784 // switch ((char)c) { case 256: case 0: return 0; }
785 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000786 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000787 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000788 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000789
Chris Lattner1e0a3902008-01-16 19:17:22 +0000790 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000792 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000793 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000794 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000795 CS->getRHS()->isValueDependent()) {
796 HasDependentValue = true;
797 break;
798 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000799 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000800 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000801 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000802 }
803 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000804
805 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000806 // If we don't have a default statement, check whether the
807 // condition is constant.
808 llvm::APSInt ConstantCondValue;
809 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000810 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000811 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000812 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
813 Expr::SE_AllowSideEffects);
814 assert(!HasConstantCond ||
815 (ConstantCondValue.getBitWidth() == CondWidth &&
816 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000817 }
Richard Smith80d4b552011-12-28 19:48:30 +0000818 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000819
Douglas Gregordbb26db2009-05-15 23:57:33 +0000820 // Sort all the scalar case values so we can easily detect duplicates.
821 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
822
823 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000824 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
825 if (ShouldCheckConstantCond &&
826 CaseVals[i].first == ConstantCondValue)
827 ShouldCheckConstantCond = false;
828
829 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000830 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000831 // First, determine if either case value has a name
832 StringRef PrevString, CurrString;
833 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
834 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
835 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
836 PrevString = DeclRef->getDecl()->getName();
837 }
838 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
839 CurrString = DeclRef->getDecl()->getName();
840 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000841 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000842 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000843
844 if (PrevString == CurrString)
845 Diag(CaseVals[i].second->getLHS()->getLocStart(),
846 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000847 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000848 else
849 Diag(CaseVals[i].second->getLHS()->getLocStart(),
850 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000851 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
852 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000853 CaseValStr;
854
John McCall0fb97082010-05-18 03:19:21 +0000855 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000856 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000857 // FIXME: We really want to remove the bogus case stmt from the
858 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000859 CaseListIsErroneous = true;
860 }
861 }
862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregordbb26db2009-05-15 23:57:33 +0000864 // Detect duplicate case ranges, which usually don't exist at all in
865 // the first place.
866 if (!CaseRanges.empty()) {
867 // Sort all the case ranges by their low value so we can easily detect
868 // overlaps between ranges.
869 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregordbb26db2009-05-15 23:57:33 +0000871 // Scan the ranges, computing the high values and removing empty ranges.
872 std::vector<llvm::APSInt> HiVals;
873 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000874 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000875 CaseStmt *CR = CaseRanges[i].second;
876 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000877 llvm::APSInt HiVal;
878
Richard Smith80ad52f2013-01-02 11:42:31 +0000879 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000880 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
881 // constant expression of the promoted type of the switch condition.
882 ExprResult ConvHi =
883 CheckConvertedConstantExpression(Hi, CondType, HiVal,
884 CCEK_CaseValue);
885 if (ConvHi.isInvalid()) {
886 CaseListIsErroneous = true;
887 continue;
888 }
889 Hi = ConvHi.take();
890 } else {
891 HiVal = Hi->EvaluateKnownConstInt(Context);
892
893 // If the RHS is not the same type as the condition, insert an
894 // implicit cast.
895 Hi = DefaultLvalueConversion(Hi).take();
896 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
897 }
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Douglas Gregordbb26db2009-05-15 23:57:33 +0000899 // Convert the value to the same width/sign as the condition.
900 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000901 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000902 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Douglas Gregordbb26db2009-05-15 23:57:33 +0000904 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregordbb26db2009-05-15 23:57:33 +0000906 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000907 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000908 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
909 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000910 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000911 CaseRanges.erase(CaseRanges.begin()+i);
912 --i, --e;
913 continue;
914 }
John McCall0fb97082010-05-18 03:19:21 +0000915
916 if (ShouldCheckConstantCond &&
917 LoVal <= ConstantCondValue &&
918 ConstantCondValue <= HiVal)
919 ShouldCheckConstantCond = false;
920
Douglas Gregordbb26db2009-05-15 23:57:33 +0000921 HiVals.push_back(HiVal);
922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Douglas Gregordbb26db2009-05-15 23:57:33 +0000924 // Rescan the ranges, looking for overlap with singleton values and other
925 // ranges. Since the range list is sorted, we only need to compare case
926 // ranges with their neighbors.
927 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
928 llvm::APSInt &CRLo = CaseRanges[i].first;
929 llvm::APSInt &CRHi = HiVals[i];
930 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregordbb26db2009-05-15 23:57:33 +0000932 // Check to see whether the case range overlaps with any
933 // singleton cases.
934 CaseStmt *OverlapStmt = 0;
935 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregordbb26db2009-05-15 23:57:33 +0000937 // Find the smallest value >= the lower bound. If I is in the
938 // case range, then we have overlap.
939 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
940 CaseVals.end(), CRLo,
941 CaseCompareFunctor());
942 if (I != CaseVals.end() && I->first < CRHi) {
943 OverlapVal = I->first; // Found overlap with scalar.
944 OverlapStmt = I->second;
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Douglas Gregordbb26db2009-05-15 23:57:33 +0000947 // Find the smallest value bigger than the upper bound.
948 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
949 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
950 OverlapVal = (I-1)->first; // Found overlap with scalar.
951 OverlapStmt = (I-1)->second;
952 }
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Douglas Gregordbb26db2009-05-15 23:57:33 +0000954 // Check to see if this case stmt overlaps with the subsequent
955 // case range.
956 if (i && CRLo <= HiVals[i-1]) {
957 OverlapVal = HiVals[i-1]; // Found overlap with range.
958 OverlapStmt = CaseRanges[i-1].second;
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregordbb26db2009-05-15 23:57:33 +0000961 if (OverlapStmt) {
962 // If we have a duplicate, report it.
963 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
964 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000965 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000966 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000967 // FIXME: We really want to remove the bogus case stmt from the
968 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000969 CaseListIsErroneous = true;
970 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000971 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000972 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000973
John McCall0fb97082010-05-18 03:19:21 +0000974 // Complain if we have a constant condition and we didn't find a match.
975 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
976 // TODO: it would be nice if we printed enums as enums, chars as
977 // chars, etc.
978 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
979 << ConstantCondValue.toString(10)
980 << CondExpr->getSourceRange();
981 }
982
983 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000984 // values. We only issue a warning if there is not 'default:', but
985 // we still do the analysis to preserve this information in the AST
986 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000987 //
Chris Lattnerce784612010-09-16 17:09:42 +0000988 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000989
Douglas Gregorba915af2010-02-08 22:24:16 +0000990 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000991 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000992 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000993 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000994 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000995 EnumValsTy EnumVals;
996
John McCall0fb97082010-05-18 03:19:21 +0000997 // Gather all enum values, set their type and sort them,
998 // allowing easier comparison with CaseVals.
999 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +00001000 EDI != ED->enumerator_end(); ++EDI) {
1001 llvm::APSInt Val = EDI->getInitVal();
1002 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +00001003 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +00001004 }
1005 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +00001006 EnumValsTy::iterator EIend =
1007 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +00001008
1009 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +00001010 EnumValsTy::const_iterator EI = EnumVals.begin();
1011 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1012 CI != CaseVals.end(); CI++) {
1013 while (EI != EIend && EI->first < CI->first)
1014 EI++;
1015 if (EI == EIend || EI->first > CI->first)
1016 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001017 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +00001018 }
1019 // See which of case ranges aren't in enum
1020 EI = EnumVals.begin();
1021 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1022 RI != CaseRanges.end() && EI != EIend; RI++) {
1023 while (EI != EIend && EI->first < RI->first)
1024 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001025
David Blaikie93667502012-01-22 02:31:55 +00001026 if (EI == EIend || EI->first != RI->first) {
1027 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001028 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001029 }
David Blaikie93667502012-01-22 02:31:55 +00001030
Chad Rosier1093f492012-08-10 17:56:09 +00001031 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001032 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1033 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1034 while (EI != EIend && EI->first < Hi)
1035 EI++;
1036 if (EI == EIend || EI->first != Hi)
1037 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001038 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
Ted Kremenek559fb552010-09-09 00:05:53 +00001041 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001042 CaseValsTy::const_iterator CI = CaseVals.begin();
1043 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001044 bool hasCasesNotInSwitch = false;
1045
Chris Lattner5f9e2722011-07-23 10:55:15 +00001046 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001047
David Blaikie93667502012-01-22 02:31:55 +00001048 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001049 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001050 llvm::APSInt CIVal;
1051 while (CI != CaseVals.end() && CI->first < EI->first)
1052 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Douglas Gregorba915af2010-02-08 22:24:16 +00001054 if (CI != CaseVals.end() && CI->first == EI->first)
1055 continue;
1056
Ted Kremenek559fb552010-09-09 00:05:53 +00001057 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001058 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001059 llvm::APSInt Hi =
1060 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001061 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001062 if (EI->first <= Hi)
1063 break;
1064 }
1065
Ted Kremenek559fb552010-09-09 00:05:53 +00001066 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001067 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001068 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001069 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001070 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001071
David Blaikie585d7792012-01-23 04:46:12 +00001072 if (TheDefaultStmt && UnhandledNames.empty())
1073 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001074
Chris Lattnerce784612010-09-16 17:09:42 +00001075 // Produce a nice diagnostic if multiple values aren't handled.
1076 switch (UnhandledNames.size()) {
1077 case 0: break;
1078 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001079 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001080 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001081 << UnhandledNames[0];
1082 break;
1083 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001084 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001085 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001086 << UnhandledNames[0] << UnhandledNames[1];
1087 break;
1088 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001089 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1090 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001091 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1092 break;
1093 default:
David Blaikie585d7792012-01-23 04:46:12 +00001094 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1095 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001096 << (unsigned)UnhandledNames.size()
1097 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1098 break;
1099 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001100
1101 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001102 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001103 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001104 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001105
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001106 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1107 diag::warn_empty_switch_body);
1108
Mike Stump390b4cc2009-05-16 07:39:55 +00001109 // FIXME: If the case list was broken is some way, we don't have a good system
1110 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001111 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001112 return StmtError();
1113
Sebastian Redlde307472009-01-11 00:38:46 +00001114 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115}
1116
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001117void
1118Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1119 Expr *SrcExpr) {
Joey Gouly48a1e812013-06-06 13:48:00 +00001120 if (Diags.getDiagnosticLevel(diag::warn_not_in_enum_assignment,
1121 SrcExpr->getExprLoc()) ==
1122 DiagnosticsEngine::Ignored)
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001123 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001124
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001125 if (const EnumType *ET = DstType->getAs<EnumType>())
1126 if (!Context.hasSameType(SrcType, DstType) &&
1127 SrcType->isIntegerType()) {
1128 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1129 SrcExpr->isIntegerConstantExpr(Context)) {
1130 // Get the bitwidth of the enum value before promotions.
Joey Gouly48a1e812013-06-06 13:48:00 +00001131 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001132 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1133
1134 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly48a1e812013-06-06 13:48:00 +00001135 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001136 const EnumDecl *ED = ET->getDecl();
Joey Gouly48a1e812013-06-06 13:48:00 +00001137 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1138 EnumValsTy;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001139 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001140
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001141 // Gather all enum values, set their type and sort them,
1142 // allowing easier comparison with rhs constant.
1143 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1144 EDI != ED->enumerator_end(); ++EDI) {
1145 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly48a1e812013-06-06 13:48:00 +00001146 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001147 EnumVals.push_back(std::make_pair(Val, *EDI));
1148 }
1149 if (EnumVals.empty())
1150 return;
1151 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1152 EnumValsTy::iterator EIend =
Joey Gouly48a1e812013-06-06 13:48:00 +00001153 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001154
Joey Gouly48a1e812013-06-06 13:48:00 +00001155 // See which values aren't in the enum.
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001156 EnumValsTy::const_iterator EI = EnumVals.begin();
1157 while (EI != EIend && EI->first < RhsVal)
1158 EI++;
1159 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly48a1e812013-06-06 13:48:00 +00001160 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001161 << DstType;
1162 }
1163 }
1164 }
1165}
1166
John McCall60d7b3a2010-08-24 06:29:42 +00001167StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001168Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001169 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001170 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171
Douglas Gregor5656e142009-11-24 21:15:44 +00001172 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001173 if (CondVar) {
1174 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001175 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001176 if (CondResult.isInvalid())
1177 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001178 }
John McCall9ae2f072010-08-23 23:25:46 +00001179 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001180 if (!ConditionExpr)
1181 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001182
John McCall9ae2f072010-08-23 23:25:46 +00001183 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001185 if (isa<NullStmt>(Body))
1186 getCurCompoundScope().setHasEmptyLoopBodies();
1187
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001188 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001189 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001190}
1191
John McCall60d7b3a2010-08-24 06:29:42 +00001192StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001193Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001194 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001195 Expr *Cond, SourceLocation CondRParen) {
1196 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001197
John Wiegley429bb272011-04-08 18:41:53 +00001198 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001199 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001200 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001201 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001202
Richard Smith41956372013-01-14 22:39:08 +00001203 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001204 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001205 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001206 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001207
John McCall9ae2f072010-08-23 23:25:46 +00001208 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001209
John McCall9ae2f072010-08-23 23:25:46 +00001210 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001211}
1212
Richard Trieu694e7962012-04-30 18:01:30 +00001213namespace {
1214 // This visitor will traverse a conditional statement and store all
1215 // the evaluated decls into a vector. Simple is set to true if none
1216 // of the excluded constructs are used.
1217 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1218 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001219 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001220 bool Simple;
Richard Trieu923cada2013-05-31 22:46:45 +00001221 public:
1222 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001223
Richard Trieu923cada2013-05-31 22:46:45 +00001224 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1225 SmallVector<SourceRange, 10> &Ranges) :
1226 Inherited(S.Context),
1227 Decls(Decls),
1228 Ranges(Ranges),
1229 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001230
Richard Trieu923cada2013-05-31 22:46:45 +00001231 bool isSimple() { return Simple; }
Richard Trieu694e7962012-04-30 18:01:30 +00001232
Richard Trieu923cada2013-05-31 22:46:45 +00001233 // Replaces the method in EvaluatedExprVisitor.
1234 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001235 Simple = false;
Richard Trieu923cada2013-05-31 22:46:45 +00001236 }
1237
1238 // Any Stmt not whitelisted will cause the condition to be marked complex.
1239 void VisitStmt(Stmt *S) {
1240 Simple = false;
1241 }
1242
1243 void VisitBinaryOperator(BinaryOperator *E) {
1244 Visit(E->getLHS());
1245 Visit(E->getRHS());
1246 }
1247
1248 void VisitCastExpr(CastExpr *E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001249 Visit(E->getSubExpr());
Richard Trieu923cada2013-05-31 22:46:45 +00001250 }
Richard Trieu694e7962012-04-30 18:01:30 +00001251
Richard Trieu923cada2013-05-31 22:46:45 +00001252 void VisitUnaryOperator(UnaryOperator *E) {
1253 // Skip checking conditionals with derefernces.
1254 if (E->getOpcode() == UO_Deref)
1255 Simple = false;
1256 else
1257 Visit(E->getSubExpr());
1258 }
Richard Trieu694e7962012-04-30 18:01:30 +00001259
Richard Trieu923cada2013-05-31 22:46:45 +00001260 void VisitConditionalOperator(ConditionalOperator *E) {
1261 Visit(E->getCond());
1262 Visit(E->getTrueExpr());
1263 Visit(E->getFalseExpr());
1264 }
Richard Trieu694e7962012-04-30 18:01:30 +00001265
Richard Trieu923cada2013-05-31 22:46:45 +00001266 void VisitParenExpr(ParenExpr *E) {
1267 Visit(E->getSubExpr());
1268 }
Richard Trieu694e7962012-04-30 18:01:30 +00001269
Richard Trieu923cada2013-05-31 22:46:45 +00001270 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1271 Visit(E->getOpaqueValue()->getSourceExpr());
1272 Visit(E->getFalseExpr());
1273 }
Richard Trieu694e7962012-04-30 18:01:30 +00001274
Richard Trieu923cada2013-05-31 22:46:45 +00001275 void VisitIntegerLiteral(IntegerLiteral *E) { }
1276 void VisitFloatingLiteral(FloatingLiteral *E) { }
1277 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1278 void VisitCharacterLiteral(CharacterLiteral *E) { }
1279 void VisitGNUNullExpr(GNUNullExpr *E) { }
1280 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu694e7962012-04-30 18:01:30 +00001281
Richard Trieu923cada2013-05-31 22:46:45 +00001282 void VisitDeclRefExpr(DeclRefExpr *E) {
1283 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1284 if (!VD) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001285
Richard Trieu923cada2013-05-31 22:46:45 +00001286 Ranges.push_back(E->getSourceRange());
1287
1288 Decls.insert(VD);
1289 }
Richard Trieu694e7962012-04-30 18:01:30 +00001290
1291 }; // end class DeclExtractor
1292
1293 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001294 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001295 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1296 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1297 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001298
Richard Trieu923cada2013-05-31 22:46:45 +00001299 public:
1300 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001301
Richard Trieu923cada2013-05-31 22:46:45 +00001302 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1303 Stmt *Statement) :
1304 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1305 if (!Statement) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001306
Richard Trieu923cada2013-05-31 22:46:45 +00001307 Visit(Statement);
Richard Trieu694e7962012-04-30 18:01:30 +00001308 }
1309
Richard Trieu923cada2013-05-31 22:46:45 +00001310 void VisitReturnStmt(ReturnStmt *S) {
1311 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001312 }
1313
Richard Trieu923cada2013-05-31 22:46:45 +00001314 void VisitBreakStmt(BreakStmt *S) {
1315 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001316 }
1317
Richard Trieu923cada2013-05-31 22:46:45 +00001318 void VisitGotoStmt(GotoStmt *S) {
1319 FoundDecl = true;
1320 }
Richard Trieu694e7962012-04-30 18:01:30 +00001321
Richard Trieu923cada2013-05-31 22:46:45 +00001322 void VisitCastExpr(CastExpr *E) {
1323 if (E->getCastKind() == CK_LValueToRValue)
1324 CheckLValueToRValueCast(E->getSubExpr());
1325 else
1326 Visit(E->getSubExpr());
1327 }
Richard Trieu694e7962012-04-30 18:01:30 +00001328
Richard Trieu923cada2013-05-31 22:46:45 +00001329 void CheckLValueToRValueCast(Expr *E) {
1330 E = E->IgnoreParenImpCasts();
1331
1332 if (isa<DeclRefExpr>(E)) {
1333 return;
1334 }
1335
1336 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1337 Visit(CO->getCond());
1338 CheckLValueToRValueCast(CO->getTrueExpr());
1339 CheckLValueToRValueCast(CO->getFalseExpr());
1340 return;
1341 }
1342
1343 if (BinaryConditionalOperator *BCO =
1344 dyn_cast<BinaryConditionalOperator>(E)) {
1345 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1346 CheckLValueToRValueCast(BCO->getFalseExpr());
1347 return;
1348 }
1349
1350 Visit(E);
1351 }
1352
1353 void VisitDeclRefExpr(DeclRefExpr *E) {
1354 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1355 if (Decls.count(VD))
1356 FoundDecl = true;
1357 }
1358
1359 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu694e7962012-04-30 18:01:30 +00001360
1361 }; // end class DeclMatcher
1362
1363 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1364 Expr *Third, Stmt *Body) {
1365 // Condition is empty
1366 if (!Second) return;
1367
1368 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1369 Second->getLocStart())
1370 == DiagnosticsEngine::Ignored)
1371 return;
1372
1373 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1374 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001375 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001376 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001377 DE.Visit(Second);
1378
1379 // Don't analyze complex conditionals.
1380 if (!DE.isSimple()) return;
1381
1382 // No decls found.
1383 if (Decls.size() == 0) return;
1384
Richard Trieu90875992012-05-04 03:01:54 +00001385 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001386 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1387 E = Decls.end();
1388 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001389 if ((*I)->getType().isVolatileQualified() ||
1390 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001391
1392 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1393 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1394 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1395 return;
1396
1397 // Load decl names into diagnostic.
1398 if (Decls.size() > 4)
1399 PDiag << 0;
1400 else {
1401 PDiag << Decls.size();
1402 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1403 E = Decls.end();
1404 I != E; ++I)
1405 PDiag << (*I)->getDeclName();
1406 }
1407
1408 // Load SourceRanges into diagnostic if there is room.
1409 // Otherwise, load the SourceRange of the conditional expression.
1410 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper09d19ef2013-07-04 03:08:24 +00001411 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001412 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001413 I != E; ++I)
1414 PDiag << *I;
1415 else
1416 PDiag << Second->getSourceRange();
1417
1418 S.Diag(Ranges.begin()->getBegin(), PDiag);
1419 }
1420
1421} // end namespace
1422
John McCall60d7b3a2010-08-24 06:29:42 +00001423StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001424Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001425 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001426 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001427 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001428 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001429 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001430 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1431 // declare identifiers for objects having storage class 'auto' or
1432 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001433 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1434 DI!=DE; ++DI) {
1435 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001436 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001437 VD = 0;
Douglas Gregor12849d02013-04-08 20:52:24 +00001438 if (VD == 0) {
1439 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1440 (*DI)->setInvalidDecl();
1441 }
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001442 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001443 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001445
Richard Trieu694e7962012-04-30 18:01:30 +00001446 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1447
John McCall60d7b3a2010-08-24 06:29:42 +00001448 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001449 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001450 if (secondVar) {
1451 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001452 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001453 if (SecondResult.isInvalid())
1454 return StmtError();
1455 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001457 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001458
Anders Carlsson3af708f2009-08-01 01:39:59 +00001459 DiagnoseUnusedExprResult(First);
1460 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001461 DiagnoseUnusedExprResult(Body);
1462
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001463 if (isa<NullStmt>(Body))
1464 getCurCompoundScope().setHasEmptyLoopBodies();
1465
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466 return Owned(new (Context) ForStmt(Context, First,
1467 SecondResult.take(), ConditionVar,
1468 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001469 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001470}
1471
John McCallf6a16482010-12-04 03:47:34 +00001472/// In an Objective C collection iteration statement:
1473/// for (x in y)
1474/// x can be an arbitrary l-value expression. Bind it up as a
1475/// full-expression.
1476StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001477 // Reduce placeholder expressions here. Note that this rejects the
1478 // use of pseudo-object l-values in this position.
1479 ExprResult result = CheckPlaceholderExpr(E);
1480 if (result.isInvalid()) return StmtError();
1481 E = result.take();
1482
Richard Smith41956372013-01-14 22:39:08 +00001483 ExprResult FullExpr = ActOnFinishFullExpr(E);
1484 if (FullExpr.isInvalid())
1485 return StmtError();
1486 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001487}
1488
John McCall990567c2011-07-27 01:07:15 +00001489ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001490Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1491 if (!collection)
1492 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001493
John McCall990567c2011-07-27 01:07:15 +00001494 // Bail out early if we've got a type-dependent expression.
1495 if (collection->isTypeDependent()) return Owned(collection);
1496
1497 // Perform normal l-value conversion.
1498 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1499 if (result.isInvalid())
1500 return ExprError();
1501 collection = result.take();
1502
1503 // The operand needs to have object-pointer type.
1504 // TODO: should we do a contextual conversion?
1505 const ObjCObjectPointerType *pointerType =
1506 collection->getType()->getAs<ObjCObjectPointerType>();
1507 if (!pointerType)
1508 return Diag(forLoc, diag::err_collection_expr_type)
1509 << collection->getType() << collection->getSourceRange();
1510
1511 // Check that the operand provides
1512 // - countByEnumeratingWithState:objects:count:
1513 const ObjCObjectType *objectType = pointerType->getObjectType();
1514 ObjCInterfaceDecl *iface = objectType->getInterface();
1515
1516 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001517 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001518 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001519 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001520 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001521 ? diag::err_arc_collection_forward
1522 : 0,
1523 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001524 // Otherwise, if we have any useful type information, check that
1525 // the type declares the appropriate method.
1526 } else if (iface || !objectType->qual_empty()) {
1527 IdentifierInfo *selectorIdents[] = {
1528 &Context.Idents.get("countByEnumeratingWithState"),
1529 &Context.Idents.get("objects"),
1530 &Context.Idents.get("count")
1531 };
1532 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1533
1534 ObjCMethodDecl *method = 0;
1535
1536 // If there's an interface, look in both the public and private APIs.
1537 if (iface) {
1538 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001539 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001540 }
1541
1542 // Also check protocol qualifiers.
1543 if (!method)
1544 method = LookupMethodInQualifiedType(selector, pointerType,
1545 /*instance*/ true);
1546
1547 // If we didn't find it anywhere, give up.
1548 if (!method) {
1549 Diag(forLoc, diag::warn_collection_expr_type)
1550 << collection->getType() << selector << collection->getSourceRange();
1551 }
1552
1553 // TODO: check for an incompatible signature?
1554 }
1555
1556 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001557 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001558}
1559
John McCall60d7b3a2010-08-24 06:29:42 +00001560StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001561Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001562 Stmt *First, Expr *collection,
1563 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001564
1565 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001566 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001567
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001568 if (First) {
1569 QualType FirstType;
1570 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001571 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001572 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1573 diag::err_toomany_element_decls));
1574
Douglas Gregor12849d02013-04-08 20:52:24 +00001575 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1576 if (!D || D->isInvalidDecl())
1577 return StmtError();
1578
John McCallf85e1932011-06-15 23:02:42 +00001579 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001580 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1581 // declare identifiers for objects having storage class 'auto' or
1582 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001583 if (!D->hasLocalStorage())
1584 return StmtError(Diag(D->getLocation(),
Douglas Gregor12849d02013-04-08 20:52:24 +00001585 diag::err_non_local_variable_decl_in_for));
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001586
1587 // If the type contained 'auto', deduce the 'auto' to 'id'.
1588 if (FirstType->getContainedAutoType()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001589 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1590 VK_RValue);
1591 Expr *DeducedInit = &OpaqueId;
Richard Smith9b131752013-04-30 21:23:01 +00001592 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1593 DAR_Failed)
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001594 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith9b131752013-04-30 21:23:01 +00001595 if (FirstType.isNull()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001596 D->setInvalidDecl();
1597 return StmtError();
1598 }
1599
Richard Smith9b131752013-04-30 21:23:01 +00001600 D->setType(FirstType);
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001601
1602 if (ActiveTemplateInstantiations.empty()) {
Richard Smith9b131752013-04-30 21:23:01 +00001603 SourceLocation Loc =
1604 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001605 Diag(Loc, diag::warn_auto_var_is_id)
1606 << D->getDeclName();
1607 }
1608 }
1609
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001610 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001611 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001612 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001613 return StmtError(Diag(First->getLocStart(),
1614 diag::err_selector_element_not_lvalue)
1615 << First->getSourceRange());
1616
Mike Stump1eb44332009-09-09 15:08:12 +00001617 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001618 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001619 if (!FirstType->isDependentType() &&
1620 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001621 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001622 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1623 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001624 }
Chad Rosier1093f492012-08-10 17:56:09 +00001625
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001626 if (CollectionExprResult.isInvalid())
1627 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001628
Richard Smith41956372013-01-14 22:39:08 +00001629 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1630 if (CollectionExprResult.isInvalid())
1631 return StmtError();
1632
Chad Rosier1093f492012-08-10 17:56:09 +00001633 return Owned(new (Context) ObjCForCollectionStmt(First,
1634 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001635 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001636}
Reid Spencer5f016e22007-07-11 17:01:13 +00001637
Richard Smithad762fc2011-04-14 22:09:26 +00001638/// Finish building a variable declaration for a for-range statement.
1639/// \return true if an error occurs.
1640static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith9b131752013-04-30 21:23:01 +00001641 SourceLocation Loc, int DiagID) {
Richard Smithad762fc2011-04-14 22:09:26 +00001642 // Deduce the type for the iterator variable now rather than leaving it to
1643 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith9b131752013-04-30 21:23:01 +00001644 QualType InitType;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001645 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith9b131752013-04-30 21:23:01 +00001646 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001647 Sema::DAR_Failed)
Richard Smith9b131752013-04-30 21:23:01 +00001648 SemaRef.Diag(Loc, DiagID) << Init->getType();
1649 if (InitType.isNull()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001650 Decl->setInvalidDecl();
1651 return true;
1652 }
Richard Smith9b131752013-04-30 21:23:01 +00001653 Decl->setType(InitType);
Richard Smithad762fc2011-04-14 22:09:26 +00001654
John McCallf85e1932011-06-15 23:02:42 +00001655 // In ARC, infer lifetime.
1656 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1657 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001658 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001659 SemaRef.inferObjCARCLifetime(Decl))
1660 Decl->setInvalidDecl();
1661
Richard Smithad762fc2011-04-14 22:09:26 +00001662 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1663 /*TypeMayContainAuto=*/false);
1664 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001665 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001666 return false;
1667}
1668
Sam Panzere1715b62012-08-21 00:52:01 +00001669namespace {
1670
Richard Smithad762fc2011-04-14 22:09:26 +00001671/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001672/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001673/// nor from the diagnostics produced when analysing the implicit expressions
1674/// required in a for-range statement.
1675void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001676 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001677 CallExpr *CE = dyn_cast<CallExpr>(E);
1678 if (!CE)
1679 return;
1680 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1681 if (!D)
1682 return;
1683 SourceLocation Loc = D->getLocation();
1684
1685 std::string Description;
1686 bool IsTemplate = false;
1687 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1688 Description = SemaRef.getTemplateArgumentBindingsText(
1689 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1690 IsTemplate = true;
1691 }
1692
1693 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1694 << BEF << IsTemplate << Description << E->getType();
1695}
1696
Sam Panzere1715b62012-08-21 00:52:01 +00001697/// Build a variable declaration for a for-range statement.
1698VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1699 QualType Type, const char *Name) {
1700 DeclContext *DC = SemaRef.CurContext;
1701 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1702 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1703 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001704 TInfo, SC_None);
Sam Panzere1715b62012-08-21 00:52:01 +00001705 Decl->setImplicit();
1706 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001707}
1708
1709}
1710
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001711static bool ObjCEnumerationCollection(Expr *Collection) {
1712 return !Collection->isTypeDependent()
1713 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1714}
1715
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001716/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001717///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001718/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001719/// A range-based for statement is equivalent to
1720///
1721/// {
1722/// auto && __range = range-init;
1723/// for ( auto __begin = begin-expr,
1724/// __end = end-expr;
1725/// __begin != __end;
1726/// ++__begin ) {
1727/// for-range-declaration = *__begin;
1728/// statement
1729/// }
1730/// }
1731///
1732/// The body of the loop is not available yet, since it cannot be analysed until
1733/// we have determined the type of the for-range-declaration.
1734StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001735Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001736 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001737 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001738 if (!First || !Range)
1739 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001740
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001741 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001742 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001743
1744 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1745 assert(DS && "first part of for range not a decl stmt");
1746
1747 if (!DS->isSingleDecl()) {
1748 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1749 return StmtError();
1750 }
1751 if (DS->getSingleDecl()->isInvalidDecl())
1752 return StmtError();
1753
1754 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1755 return StmtError();
1756
1757 // Build auto && __range = range-init
1758 SourceLocation RangeLoc = Range->getLocStart();
1759 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1760 Context.getAutoRRefDeductType(),
1761 "__range");
1762 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1763 diag::err_for_range_deduction_failure))
1764 return StmtError();
1765
1766 // Claim the type doesn't contain auto: we've already done the checking.
1767 DeclGroupPtrTy RangeGroup =
Rafael Espindola4549d7f2013-07-09 12:05:01 +00001768 BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1769 /*TypeMayContainAuto=*/ false);
Richard Smithad762fc2011-04-14 22:09:26 +00001770 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1771 if (RangeDecl.isInvalid())
1772 return StmtError();
1773
1774 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1775 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001776 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001777}
1778
1779/// \brief Create the initialization, compare, and increment steps for
1780/// the range-based for loop expression.
1781/// This function does not handle array-based for loops,
1782/// which are created in Sema::BuildCXXForRangeStmt.
1783///
1784/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1785/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1786/// CandidateSet and BEF are set and some non-success value is returned on
1787/// failure.
1788static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1789 Expr *BeginRange, Expr *EndRange,
1790 QualType RangeType,
1791 VarDecl *BeginVar,
1792 VarDecl *EndVar,
1793 SourceLocation ColonLoc,
1794 OverloadCandidateSet *CandidateSet,
1795 ExprResult *BeginExpr,
1796 ExprResult *EndExpr,
1797 Sema::BeginEndFunction *BEF) {
1798 DeclarationNameInfo BeginNameInfo(
1799 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1800 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1801 ColonLoc);
1802
1803 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1804 Sema::LookupMemberName);
1805 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1806
1807 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1808 // - if _RangeT is a class type, the unqualified-ids begin and end are
1809 // looked up in the scope of class _RangeT as if by class member access
1810 // lookup (3.4.5), and if either (or both) finds at least one
1811 // declaration, begin-expr and end-expr are __range.begin() and
1812 // __range.end(), respectively;
1813 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1814 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1815
1816 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1817 SourceLocation RangeLoc = BeginVar->getLocation();
1818 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1819
1820 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1821 << RangeLoc << BeginRange->getType() << *BEF;
1822 return Sema::FRS_DiagnosticIssued;
1823 }
1824 } else {
1825 // - otherwise, begin-expr and end-expr are begin(__range) and
1826 // end(__range), respectively, where begin and end are looked up with
1827 // argument-dependent lookup (3.4.2). For the purposes of this name
1828 // lookup, namespace std is an associated namespace.
1829
1830 }
1831
1832 *BEF = Sema::BEF_begin;
1833 Sema::ForRangeStatus RangeStatus =
1834 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1835 Sema::BEF_begin, BeginNameInfo,
1836 BeginMemberLookup, CandidateSet,
1837 BeginRange, BeginExpr);
1838
1839 if (RangeStatus != Sema::FRS_Success)
1840 return RangeStatus;
1841 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1842 diag::err_for_range_iter_deduction_failure)) {
1843 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1844 return Sema::FRS_DiagnosticIssued;
1845 }
1846
1847 *BEF = Sema::BEF_end;
1848 RangeStatus =
1849 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1850 Sema::BEF_end, EndNameInfo,
1851 EndMemberLookup, CandidateSet,
1852 EndRange, EndExpr);
1853 if (RangeStatus != Sema::FRS_Success)
1854 return RangeStatus;
1855 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1856 diag::err_for_range_iter_deduction_failure)) {
1857 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1858 return Sema::FRS_DiagnosticIssued;
1859 }
1860 return Sema::FRS_Success;
1861}
1862
1863/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001864/// If the attempt fails, this function will return a valid, null StmtResult
1865/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001866static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1867 SourceLocation ForLoc,
1868 Stmt *LoopVarDecl,
1869 SourceLocation ColonLoc,
1870 Expr *Range,
1871 SourceLocation RangeLoc,
1872 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001873 // Determine whether we can rebuild the for-range statement with a
1874 // dereferenced range expression.
1875 ExprResult AdjustedRange;
1876 {
1877 Sema::SFINAETrap Trap(SemaRef);
1878
1879 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1880 if (AdjustedRange.isInvalid())
1881 return StmtResult();
1882
1883 StmtResult SR =
1884 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1885 AdjustedRange.get(), RParenLoc,
1886 Sema::BFRK_Check);
1887 if (SR.isInvalid())
1888 return StmtResult();
1889 }
1890
1891 // The attempt to dereference worked well enough that it could produce a valid
1892 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1893 // case there are any other (non-fatal) problems with it.
1894 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1895 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1896 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1897 AdjustedRange.get(), RParenLoc,
1898 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001899}
1900
Richard Smith8b533d92012-09-20 21:52:32 +00001901/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001902StmtResult
1903Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1904 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1905 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001906 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001907 Scope *S = getCurScope();
1908
1909 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1910 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1911 QualType RangeVarType = RangeVar->getType();
1912
1913 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1914 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1915
1916 StmtResult BeginEndDecl = BeginEnd;
1917 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1918
Richard Smithdc7a4f52013-04-30 13:56:41 +00001919 if (RangeVarType->isDependentType()) {
1920 // The range is implicitly used as a placeholder when it is dependent.
1921 RangeVar->setUsed();
1922
1923 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
1924 // them in properly when we instantiate the loop.
1925 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
1926 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
1927 } else if (!BeginEndDecl.get()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001928 SourceLocation RangeLoc = RangeVar->getLocation();
1929
Ted Kremeneke50b0152011-10-10 22:36:28 +00001930 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1931
1932 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1933 VK_LValue, ColonLoc);
1934 if (BeginRangeRef.isInvalid())
1935 return StmtError();
1936
1937 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1938 VK_LValue, ColonLoc);
1939 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001940 return StmtError();
1941
1942 QualType AutoType = Context.getAutoDeductType();
1943 Expr *Range = RangeVar->getInit();
1944 if (!Range)
1945 return StmtError();
1946 QualType RangeType = Range->getType();
1947
1948 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001949 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001950 return StmtError();
1951
1952 // Build auto __begin = begin-expr, __end = end-expr.
1953 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1954 "__begin");
1955 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1956 "__end");
1957
1958 // Build begin-expr and end-expr and attach to __begin and __end variables.
1959 ExprResult BeginExpr, EndExpr;
1960 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1961 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1962 // __range + __bound, respectively, where __bound is the array bound. If
1963 // _RangeT is an array of unknown size or an array of incomplete type,
1964 // the program is ill-formed;
1965
1966 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001967 BeginExpr = BeginRangeRef;
1968 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001969 diag::err_for_range_iter_deduction_failure)) {
1970 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1971 return StmtError();
1972 }
1973
1974 // Find the array bound.
1975 ExprResult BoundExpr;
1976 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1977 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001978 Context.getPointerDiffType(),
1979 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001980 else if (const VariableArrayType *VAT =
1981 dyn_cast<VariableArrayType>(UnqAT))
Richard Smith39b0e262013-04-20 23:28:26 +00001982 // FIXME: Need to build an OpaqueValueExpr for this rather than
1983 // recomputing it!
Richard Smithad762fc2011-04-14 22:09:26 +00001984 BoundExpr = VAT->getSizeExpr();
1985 else {
1986 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1987 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001988 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001989 }
1990
1991 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001992 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001993 BoundExpr.get());
1994 if (EndExpr.isInvalid())
1995 return StmtError();
1996 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1997 diag::err_for_range_iter_deduction_failure)) {
1998 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1999 return StmtError();
2000 }
2001 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00002002 OverloadCandidateSet CandidateSet(RangeLoc);
2003 Sema::BeginEndFunction BEFFailure;
2004 ForRangeStatus RangeStatus =
2005 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2006 EndRangeRef.get(), RangeType,
2007 BeginVar, EndVar, ColonLoc, &CandidateSet,
2008 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00002009
Sam Panzere1715b62012-08-21 00:52:01 +00002010 // If building the range failed, try dereferencing the range expression
2011 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00002012 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00002013 BEFFailure == BEF_begin) {
2014 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2015 LoopVarDecl, ColonLoc,
2016 Range, RangeLoc,
2017 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00002018 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00002019 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00002020 }
2021
Sam Panzere1715b62012-08-21 00:52:01 +00002022 // Otherwise, emit diagnostics if we haven't already.
2023 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00002024 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00002025 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2026 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00002027 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00002028 }
2029 // Return an error if no fix was discovered.
2030 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00002031 return StmtError();
2032 }
2033
Sam Panzere1715b62012-08-21 00:52:01 +00002034 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2035 "invalid range expression in for loop");
2036
2037 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00002038 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2039 if (!Context.hasSameType(BeginType, EndType)) {
2040 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2041 << BeginType << EndType;
2042 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2043 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2044 }
2045
2046 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2047 // Claim the type doesn't contain auto: we've already done the checking.
2048 DeclGroupPtrTy BeginEndGroup =
Rafael Espindola4549d7f2013-07-09 12:05:01 +00002049 BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>(BeginEndDecls, 2),
2050 /*TypeMayContainAuto=*/ false);
Richard Smithad762fc2011-04-14 22:09:26 +00002051 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2052
Ted Kremeneke50b0152011-10-10 22:36:28 +00002053 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2054 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00002055 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002056 if (BeginRef.isInvalid())
2057 return StmtError();
2058
Richard Smithad762fc2011-04-14 22:09:26 +00002059 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2060 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002061 if (EndRef.isInvalid())
2062 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00002063
2064 // Build and check __begin != __end expression.
2065 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2066 BeginRef.get(), EndRef.get());
2067 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2068 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2069 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002070 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2071 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002072 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2073 if (!Context.hasSameType(BeginType, EndType))
2074 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2075 return StmtError();
2076 }
2077
2078 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002079 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2080 VK_LValue, ColonLoc);
2081 if (BeginRef.isInvalid())
2082 return StmtError();
2083
Richard Smithad762fc2011-04-14 22:09:26 +00002084 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2085 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2086 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002087 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2088 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002089 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2090 return StmtError();
2091 }
2092
2093 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002094 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2095 VK_LValue, ColonLoc);
2096 if (BeginRef.isInvalid())
2097 return StmtError();
2098
Richard Smithad762fc2011-04-14 22:09:26 +00002099 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2100 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002101 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2102 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002103 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2104 return StmtError();
2105 }
2106
Richard Smith8b533d92012-09-20 21:52:32 +00002107 // Attach *__begin as initializer for VD. Don't touch it if we're just
2108 // trying to determine whether this would be a valid range.
2109 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002110 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2111 /*TypeMayContainAuto=*/true);
2112 if (LoopVar->isInvalidDecl())
2113 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2114 }
2115 }
2116
Richard Smith8b533d92012-09-20 21:52:32 +00002117 // Don't bother to actually allocate the result if we're just trying to
2118 // determine whether it would be valid.
2119 if (Kind == BFRK_Check)
2120 return StmtResult();
2121
Richard Smithad762fc2011-04-14 22:09:26 +00002122 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2123 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2124 NotEqExpr.take(), IncrExpr.take(),
2125 LoopVarDS, /*Body=*/0, ForLoc,
2126 ColonLoc, RParenLoc));
2127}
2128
Chad Rosier1093f492012-08-10 17:56:09 +00002129/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002130/// statement.
2131StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2132 if (!S || !B)
2133 return StmtError();
2134 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002135
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002136 ForStmt->setBody(B);
2137 return S;
2138}
2139
Richard Smithad762fc2011-04-14 22:09:26 +00002140/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2141/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2142/// body cannot be performed until after the type of the range variable is
2143/// determined.
2144StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2145 if (!S || !B)
2146 return StmtError();
2147
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002148 if (isa<ObjCForCollectionStmt>(S))
2149 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002150
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002151 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2152 ForStmt->setBody(B);
2153
2154 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2155 diag::warn_empty_range_based_for_body);
2156
Richard Smithad762fc2011-04-14 22:09:26 +00002157 return S;
2158}
2159
Chris Lattner57ad3782011-02-17 20:34:02 +00002160StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2161 SourceLocation LabelLoc,
2162 LabelDecl *TheDecl) {
2163 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002164 TheDecl->setUsed();
2165 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002166}
2167
John McCall60d7b3a2010-08-24 06:29:42 +00002168StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002169Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002170 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002171 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002172 if (!E->isTypeDependent()) {
2173 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002174 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002175 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002176 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002177 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2178 if (ExprRes.isInvalid())
2179 return StmtError();
2180 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002181 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002182 return StmtError();
2183 }
John McCallb60a77e2010-08-01 00:26:45 +00002184
Richard Smith41956372013-01-14 22:39:08 +00002185 ExprResult ExprRes = ActOnFinishFullExpr(E);
2186 if (ExprRes.isInvalid())
2187 return StmtError();
2188 E = ExprRes.take();
2189
John McCall781472f2010-08-25 08:40:02 +00002190 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002191
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002192 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002193}
2194
John McCall60d7b3a2010-08-24 06:29:42 +00002195StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002196Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002197 Scope *S = CurScope->getContinueParent();
2198 if (!S) {
2199 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002200 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002202
Ted Kremenek8189cde2009-02-07 01:47:29 +00002203 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002204}
2205
John McCall60d7b3a2010-08-24 06:29:42 +00002206StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002207Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 Scope *S = CurScope->getBreakParent();
2209 if (!S) {
2210 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002211 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002213
Ted Kremenek8189cde2009-02-07 01:47:29 +00002214 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002215}
2216
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002217/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002218/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002219///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002220/// \param ReturnType If we're determining the copy elision candidate for
2221/// a return statement, this is the return type of the function. If we're
2222/// determining the copy elision candidate for a throw expression, this will
2223/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002224///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002225/// \param E The expression being returned from the function or block, or
2226/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002227///
Douglas Gregor4926d832011-05-20 15:00:53 +00002228/// \param AllowFunctionParameter Whether we allow function parameters to
2229/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2230/// we re-use this logic to determine whether we should try to move as part of
2231/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002232///
2233/// \returns The NRVO candidate variable, if the return statement may use the
2234/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002235const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2236 Expr *E,
2237 bool AllowFunctionParameter) {
2238 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002239 // - in a return statement in a function with ...
2240 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002241 if (!ReturnType.isNull()) {
2242 if (!ReturnType->isRecordType())
2243 return 0;
2244 // ... the same cv-unqualified type as the function return type ...
2245 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2246 return 0;
2247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002248
2249 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002250 // (other than a function or catch-clause parameter)) ...
2251 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002252 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002253 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002254 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2255 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002256 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
John McCall1cd76e82011-11-11 03:57:31 +00002258 // ...object (other than a function or catch-clause parameter)...
2259 if (VD->getKind() != Decl::Var &&
2260 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2261 return 0;
2262 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263
John McCall1cd76e82011-11-11 03:57:31 +00002264 // ...automatic...
2265 if (!VD->hasLocalStorage()) return 0;
2266
2267 // ...non-volatile...
2268 if (VD->getType().isVolatileQualified()) return 0;
2269 if (VD->getType()->isReferenceType()) return 0;
2270
2271 // __block variables can't be allocated in a way that permits NRVO.
2272 if (VD->hasAttr<BlocksAttr>()) return 0;
2273
2274 // Variables with higher required alignment than their type's ABI
2275 // alignment cannot use NRVO.
2276 if (VD->hasAttr<AlignedAttr>() &&
2277 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2278 return 0;
2279
2280 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002281}
2282
Douglas Gregor07f402c2011-01-21 21:08:57 +00002283/// \brief Perform the initialization of a potentially-movable value, which
2284/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002285///
2286/// This routine implements C++0x [class.copy]p33, which attempts to treat
2287/// returned lvalues as rvalues in certain cases (to prefer move construction),
2288/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002289ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002290Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2291 const VarDecl *NRVOCandidate,
2292 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002293 Expr *Value,
2294 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002295 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002296 // When the criteria for elision of a copy operation are met or would
2297 // be met save for the fact that the source object is a function
2298 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002299 // overload resolution to select the constructor for the copy is first
2300 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002301 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002302 if (AllowNRVO &&
2303 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002304 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002305 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002306
Douglas Gregorcc15f012011-01-21 19:38:21 +00002307 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002308 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002309 = InitializationKind::CreateCopy(Value->getLocStart(),
2310 Value->getLocStart());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002311 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002312
2313 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002314 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002315 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002316 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002317 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002318 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2319 StepEnd = Seq.step_end();
2320 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002321 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002322 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002323
2324 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002325 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002326
Douglas Gregorcc15f012011-01-21 19:38:21 +00002327 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002328 = Constructor->getParamDecl(0)->getType()
2329 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330
Douglas Gregorcc15f012011-01-21 19:38:21 +00002331 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002332 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002333 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2334 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002335 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002336
Douglas Gregorcc15f012011-01-21 19:38:21 +00002337 // Promote "AsRvalue" to the heap, since we now need this
2338 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002339 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002340 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341
Douglas Gregorcc15f012011-01-21 19:38:21 +00002342 // Complete type-checking the initialization of the return type
2343 // using the constructor we found.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002344 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorcc15f012011-01-21 19:38:21 +00002345 }
2346 }
2347 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002348
Douglas Gregorcc15f012011-01-21 19:38:21 +00002349 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002350 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002351 // (again) now with the return value expression as written.
2352 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002353 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002354
Douglas Gregorcc15f012011-01-21 19:38:21 +00002355 return Res;
2356}
2357
Eli Friedman84b007f2012-01-26 03:00:14 +00002358/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2359/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002360///
John McCall60d7b3a2010-08-24 06:29:42 +00002361StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002362Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2363 // If this is the first return we've seen, infer the return type.
Richard Smithf45c2992013-05-12 03:09:35 +00002364 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman84b007f2012-01-26 03:00:14 +00002365 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002366 QualType FnRetType = CurCap->ReturnType;
2367
2368 // For blocks/lambdas with implicit return types, we check each return
2369 // statement individually, and deduce the common return type when the block
2370 // or lambda is completed.
Richard Smithf45c2992013-05-12 03:09:35 +00002371 if (AutoType *AT =
2372 FnRetType.isNull() ? 0 : FnRetType->getContainedAutoType()) {
2373 // In C++1y, the return type may involve 'auto'.
2374 FunctionDecl *FD = cast<LambdaScopeInfo>(CurCap)->CallOperator;
2375 if (CurContext->isDependentContext()) {
2376 // C++1y [dcl.spec.auto]p12:
2377 // Return type deduction [...] occurs when the definition is
2378 // instantiated even if the function body contains a return
2379 // statement with a non-type-dependent operand.
2380 CurCap->ReturnType = FnRetType = Context.DependentTy;
2381 } else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2382 FD->setInvalidDecl();
2383 return StmtError();
2384 } else
2385 CurCap->ReturnType = FnRetType = FD->getResultType();
2386 } else if (CurCap->HasImplicitReturnType) {
2387 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregora0c2b212012-02-09 18:40:39 +00002388 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002389 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2390 if (Result.isInvalid())
2391 return StmtError();
2392 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002393
Richard Smithf45c2992013-05-12 03:09:35 +00002394 if (!CurContext->isDependentContext())
Jordan Rose7dd900e2012-07-02 21:19:23 +00002395 FnRetType = RetValExp->getType();
2396 else
2397 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002398 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002399 if (RetValExp) {
2400 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2401 // initializer list, because it is not an expression (even
2402 // though we represent it as one). We still deduce 'void'.
2403 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2404 << RetValExp->getSourceRange();
2405 }
2406
Jordan Rose7dd900e2012-07-02 21:19:23 +00002407 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002408 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002409
2410 // Although we'll properly infer the type of the block once it's completed,
2411 // make sure we provide a return type now for better error recovery.
2412 if (CurCap->ReturnType.isNull())
2413 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002414 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002415 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002416
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002417 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002418 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2419 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2420 return StmtError();
2421 }
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00002422 } else if (CapturedRegionScopeInfo *CurRegion =
2423 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2424 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2425 return StmtError();
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002426 } else {
2427 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2428 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2429 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2430 return StmtError();
2431 }
2432 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002433
Steve Naroff4eb206b2008-09-03 18:15:37 +00002434 // Otherwise, verify that this result type matches the previous one. We are
2435 // pickier with blocks than for normal functions because we don't have GCC
2436 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002437 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002438 if (FnRetType->isDependentType()) {
2439 // Delay processing for now. TODO: there are lots of dependent
2440 // types we can conclusively prove aren't void.
2441 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002442 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002443 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002444 (RetValExp->isTypeDependent() ||
2445 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002446 if (!getLangOpts().CPlusPlus &&
2447 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002448 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002449 else {
2450 Diag(ReturnLoc, diag::err_return_block_has_expr);
2451 RetValExp = 0;
2452 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002453 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002454 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002455 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2456 } else if (!RetValExp->isTypeDependent()) {
2457 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002458
John McCall0a7efe12011-08-17 22:09:46 +00002459 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2460 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2461 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002462
John McCall0a7efe12011-08-17 22:09:46 +00002463 // In C++ the return statement is handled via a copy initialization.
2464 // the C version of which boils down to CheckSingleAssignmentConstraints.
2465 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2466 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2467 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002468 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002469 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2470 FnRetType, RetValExp);
2471 if (Res.isInvalid()) {
2472 // FIXME: Cleanup temporaries here, anyway?
2473 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002474 }
John McCall0a7efe12011-08-17 22:09:46 +00002475 RetValExp = Res.take();
2476 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002477 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002478
John McCalld963c372011-08-17 21:34:14 +00002479 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002480 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2481 if (ER.isInvalid())
2482 return StmtError();
2483 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002484 }
John McCall0a7efe12011-08-17 22:09:46 +00002485 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2486 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002487
Jordan Rose7dd900e2012-07-02 21:19:23 +00002488 // If we need to check for the named return value optimization,
2489 // or if we need to infer the return type,
2490 // save the return statement in our scope for later processing.
2491 if (CurCap->HasImplicitReturnType ||
2492 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2493 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002494 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002495
Douglas Gregor5077c382010-05-15 06:01:05 +00002496 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002497}
Reid Spencer5f016e22007-07-11 17:01:13 +00002498
Richard Smith60e141e2013-05-04 07:00:32 +00002499/// Deduce the return type for a function from a returned expression, per
2500/// C++1y [dcl.spec.auto]p6.
2501bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2502 SourceLocation ReturnLoc,
2503 Expr *&RetExpr,
2504 AutoType *AT) {
2505 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2506 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
2507 QualType Deduced;
2508
2509 if (RetExpr) {
2510 // If the deduction is for a return statement and the initializer is
2511 // a braced-init-list, the program is ill-formed.
2512 if (isa<InitListExpr>(RetExpr)) {
2513 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2514 return true;
2515 }
2516
2517 // Otherwise, [...] deduce a value for U using the rules of template
2518 // argument deduction.
2519 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2520
2521 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2522 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2523 << OrigResultType.getType() << RetExpr->getType();
2524
2525 if (DAR != DAR_Succeeded)
2526 return true;
2527 } else {
2528 // In the case of a return with no operand, the initializer is considered
2529 // to be void().
2530 //
2531 // Deduction here can only succeed if the return type is exactly 'cv auto'
2532 // or 'decltype(auto)', so just check for that case directly.
2533 if (!OrigResultType.getType()->getAs<AutoType>()) {
2534 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2535 << OrigResultType.getType();
2536 return true;
2537 }
2538 // We always deduce U = void in this case.
2539 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2540 if (Deduced.isNull())
2541 return true;
2542 }
2543
2544 // If a function with a declared return type that contains a placeholder type
2545 // has multiple return statements, the return type is deduced for each return
2546 // statement. [...] if the type deduced is not the same in each deduction,
2547 // the program is ill-formed.
2548 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2549 AutoType *NewAT = Deduced->getContainedAutoType();
2550 if (!Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2551 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2552 << (AT->isDecltypeAuto() ? 1 : 0)
2553 << NewAT->getDeducedType() << AT->getDeducedType();
2554 return true;
2555 }
2556 } else if (!FD->isInvalidDecl()) {
2557 // Update all declarations of the function to have the deduced return type.
2558 Context.adjustDeducedFunctionResultType(FD, Deduced);
2559 }
2560
2561 return false;
2562}
2563
John McCall60d7b3a2010-08-24 06:29:42 +00002564StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002565Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002566 // Check for unexpanded parameter packs.
2567 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2568 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002569
Eli Friedman84b007f2012-01-26 03:00:14 +00002570 if (isa<CapturingScopeInfo>(getCurFunction()))
2571 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002572
Chris Lattner371f2582008-12-04 23:50:19 +00002573 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002574 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002575 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002576 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002577 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002578 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002579 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002580 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002581 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002582 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2583 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002584 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002585 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002586 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2587 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002588 }
2589 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002590 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Richard Smith60e141e2013-05-04 07:00:32 +00002592 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2593 // deduction.
2594 bool HasDependentReturnType = FnRetType->isDependentType();
2595 if (getLangOpts().CPlusPlus1y) {
2596 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2597 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2598 if (CurContext->isDependentContext())
2599 HasDependentReturnType = true;
2600 else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2601 FD->setInvalidDecl();
2602 return StmtError();
2603 } else {
2604 FnRetType = FD->getResultType();
2605 }
2606 }
2607 }
2608
Douglas Gregor5077c382010-05-15 06:01:05 +00002609 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002610 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002611 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002612 if (isa<InitListExpr>(RetValExp)) {
2613 // We simply never allow init lists as the return value of void
2614 // functions. This is compatible because this was never allowed before,
2615 // so there's no legacy code to deal with.
2616 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2617 int FunctionKind = 0;
2618 if (isa<ObjCMethodDecl>(CurDecl))
2619 FunctionKind = 1;
2620 else if (isa<CXXConstructorDecl>(CurDecl))
2621 FunctionKind = 2;
2622 else if (isa<CXXDestructorDecl>(CurDecl))
2623 FunctionKind = 3;
2624
2625 Diag(ReturnLoc, diag::err_return_init_list)
2626 << CurDecl->getDeclName() << FunctionKind
2627 << RetValExp->getSourceRange();
2628
2629 // Drop the expression.
2630 RetValExp = 0;
2631 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002632 // C99 6.8.6.4p1 (ext_ since GCC warns)
2633 unsigned D = diag::ext_return_has_expr;
2634 if (RetValExp->getType()->isVoidType())
2635 D = diag::ext_return_has_void_expr;
2636 else {
2637 ExprResult Result = Owned(RetValExp);
2638 Result = IgnoredValueConversions(Result.take());
2639 if (Result.isInvalid())
2640 return StmtError();
2641 RetValExp = Result.take();
2642 RetValExp = ImpCastExprToType(RetValExp,
2643 Context.VoidTy, CK_ToVoid).take();
2644 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002645
Nick Lewycky8d794612011-06-01 07:44:31 +00002646 // return (some void expression); is legal in C++.
2647 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002648 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002649 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002650
2651 int FunctionKind = 0;
2652 if (isa<ObjCMethodDecl>(CurDecl))
2653 FunctionKind = 1;
2654 else if (isa<CXXConstructorDecl>(CurDecl))
2655 FunctionKind = 2;
2656 else if (isa<CXXDestructorDecl>(CurDecl))
2657 FunctionKind = 3;
2658
Nick Lewycky8d794612011-06-01 07:44:31 +00002659 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002660 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002661 << RetValExp->getSourceRange();
2662 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002663 }
Mike Stump1eb44332009-09-09 15:08:12 +00002664
Sebastian Redl33deb352012-02-22 10:50:08 +00002665 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002666 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2667 if (ER.isInvalid())
2668 return StmtError();
2669 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002672
Douglas Gregor5077c382010-05-15 06:01:05 +00002673 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
Richard Smith60e141e2013-05-04 07:00:32 +00002674 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002675 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2676 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002677 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002678
2679 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002680 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002681 else
Chris Lattner08631c52008-11-23 21:45:46 +00002682 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002683 Result = new (Context) ReturnStmt(ReturnLoc);
2684 } else {
Richard Smith60e141e2013-05-04 07:00:32 +00002685 assert(RetValExp || HasDependentReturnType);
Douglas Gregor5077c382010-05-15 06:01:05 +00002686 const VarDecl *NRVOCandidate = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00002687 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor5077c382010-05-15 06:01:05 +00002688 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002689
John McCall7cca8212013-03-19 07:04:25 +00002690 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
Eli Friedman38ac2432012-03-30 01:13:43 +00002691
Douglas Gregor5077c382010-05-15 06:01:05 +00002692 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2693 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2694 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002695
John McCall856d3792011-06-16 23:24:51 +00002696 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002697 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002698 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall7cca8212013-03-19 07:04:25 +00002700 RetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002701 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall7cca8212013-03-19 07:04:25 +00002703 RetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002704 if (Res.isInvalid()) {
John McCall7cca8212013-03-19 07:04:25 +00002705 // FIXME: Clean up temporaries here anyway?
Douglas Gregor5077c382010-05-15 06:01:05 +00002706 return StmtError();
2707 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002708 RetValExp = Res.takeAs<Expr>();
John McCall7cca8212013-03-19 07:04:25 +00002709
2710 // If we have a related result type, we need to implicitly
2711 // convert back to the formal result type. We can't pretend to
2712 // initialize the result again --- we might end double-retaining
2713 // --- so instead we initialize a notional temporary; this can
2714 // lead to less-than-great diagnostics, but this stage is much
2715 // less likely to fail than the previous stage.
2716 if (!RelatedRetType.isNull()) {
2717 Entity = InitializedEntity::InitializeTemporary(FnRetType);
2718 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2719 if (Res.isInvalid()) {
2720 // FIXME: Clean up temporaries here anyway?
2721 return StmtError();
2722 }
2723 RetValExp = Res.takeAs<Expr>();
2724 }
2725
2726 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002728
John McCallb4eb64d2010-10-08 02:01:28 +00002729 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002730 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2731 if (ER.isInvalid())
2732 return StmtError();
2733 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002734 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002735 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002737
2738 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002739 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002740 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002741 !CurContext->isDependentContext())
2742 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002743
Douglas Gregor5077c382010-05-15 06:01:05 +00002744 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002745}
2746
John McCall60d7b3a2010-08-24 06:29:42 +00002747StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002748Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002749 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002750 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002751 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002752 if (Var && Var->isInvalidDecl())
2753 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002754
John McCall9ae2f072010-08-23 23:25:46 +00002755 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002756}
2757
John McCall60d7b3a2010-08-24 06:29:42 +00002758StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002759Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2760 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002761}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002762
John McCall60d7b3a2010-08-24 06:29:42 +00002763StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002764Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002765 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002766 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002767 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2768
John McCall781472f2010-08-25 08:40:02 +00002769 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002770 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002771 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002772 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002773 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002774 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002775}
2776
John McCalld1376ee2012-05-08 21:41:25 +00002777StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002778 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002779 ExprResult Result = DefaultLvalueConversion(Throw);
2780 if (Result.isInvalid())
2781 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002782
Richard Smith41956372013-01-14 22:39:08 +00002783 Result = ActOnFinishFullExpr(Result.take());
2784 if (Result.isInvalid())
2785 return StmtError();
2786 Throw = Result.take();
2787
Douglas Gregord1377b22010-04-22 21:44:01 +00002788 QualType ThrowType = Throw->getType();
2789 // Make sure the expression type is an ObjC pointer or "void *".
2790 if (!ThrowType->isDependentType() &&
2791 !ThrowType->isObjCObjectPointerType()) {
2792 const PointerType *PT = ThrowType->getAs<PointerType>();
2793 if (!PT || !PT->getPointeeType()->isVoidType())
2794 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2795 << Throw->getType() << Throw->getSourceRange());
2796 }
2797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002798
John McCall9ae2f072010-08-23 23:25:46 +00002799 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002800}
2801
John McCall60d7b3a2010-08-24 06:29:42 +00002802StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002803Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002804 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002805 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002806 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2807
John McCall9ae2f072010-08-23 23:25:46 +00002808 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002809 // @throw without an expression designates a rethrow (which much occur
2810 // in the context of an @catch clause).
2811 Scope *AtCatchParent = CurScope;
2812 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2813 AtCatchParent = AtCatchParent->getParent();
2814 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002815 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816 }
John McCall9ae2f072010-08-23 23:25:46 +00002817 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002818}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002819
John McCall07524032011-07-27 21:50:02 +00002820ExprResult
2821Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2822 ExprResult result = DefaultLvalueConversion(operand);
2823 if (result.isInvalid())
2824 return ExprError();
2825 operand = result.take();
2826
2827 // Make sure the expression type is an ObjC pointer or "void *".
2828 QualType type = operand->getType();
2829 if (!type->isDependentType() &&
2830 !type->isObjCObjectPointerType()) {
2831 const PointerType *pointerType = type->getAs<PointerType>();
2832 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2833 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2834 << type << operand->getSourceRange();
2835 }
2836
2837 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002838 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002839}
2840
John McCall60d7b3a2010-08-24 06:29:42 +00002841StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002842Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2843 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002844 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002845 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002846 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002847}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002848
2849/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2850/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002851StmtResult
John McCalld226f652010-08-21 09:40:31 +00002852Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002853 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002854 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002855 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002856 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002857 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002858}
Sebastian Redl8351da02008-12-22 21:35:02 +00002859
John McCallf85e1932011-06-15 23:02:42 +00002860StmtResult
2861Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2862 getCurFunction()->setHasBranchProtectedScope();
2863 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2864}
2865
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002866namespace {
2867
Sebastian Redlc447aba2009-07-29 17:15:45 +00002868class TypeWithHandler {
2869 QualType t;
2870 CXXCatchStmt *stmt;
2871public:
2872 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2873 : t(type), stmt(statement) {}
2874
John McCall0953e762009-09-24 19:53:00 +00002875 // An arbitrary order is fine as long as it places identical
2876 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002877 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002878 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002879 return true;
John McCall0953e762009-09-24 19:53:00 +00002880 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002881 return false;
2882 else
2883 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2884 }
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Sebastian Redlc447aba2009-07-29 17:15:45 +00002886 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002887 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002888 }
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Sebastian Redlc447aba2009-07-29 17:15:45 +00002890 CXXCatchStmt *getCatchStmt() const { return stmt; }
2891 SourceLocation getTypeSpecStartLoc() const {
2892 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2893 }
2894};
2895
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002896}
2897
Sebastian Redl8351da02008-12-22 21:35:02 +00002898/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2899/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002900StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002901Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002902 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002903 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002904 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002905 !getSourceManager().isInSystemHeader(TryLoc))
2906 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002907
Sebastian Redl8351da02008-12-22 21:35:02 +00002908 unsigned NumHandlers = RawHandlers.size();
2909 assert(NumHandlers > 0 &&
2910 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002911 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002912
Chris Lattner5f9e2722011-07-23 10:55:15 +00002913 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002914
2915 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002916 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002917 if (!Handler->getExceptionDecl()) {
2918 if (i < NumHandlers - 1)
2919 return StmtError(Diag(Handler->getLocStart(),
2920 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Sebastian Redlc447aba2009-07-29 17:15:45 +00002922 continue;
2923 }
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Sebastian Redlc447aba2009-07-29 17:15:45 +00002925 const QualType CaughtType = Handler->getCaughtType();
2926 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2927 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002928 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002929
2930 // Detect handlers for the same type as an earlier one.
2931 if (NumHandlers > 1) {
2932 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Sebastian Redlc447aba2009-07-29 17:15:45 +00002934 TypeWithHandler prev = TypesWithHandlers[0];
2935 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2936 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Sebastian Redlc447aba2009-07-29 17:15:45 +00002938 if (curr == prev) {
2939 Diag(curr.getTypeSpecStartLoc(),
2940 diag::warn_exception_caught_by_earlier_handler)
2941 << curr.getCatchStmt()->getCaughtType().getAsString();
2942 Diag(prev.getTypeSpecStartLoc(),
2943 diag::note_previous_exception_handler)
2944 << prev.getCatchStmt()->getCaughtType().getAsString();
2945 }
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Sebastian Redlc447aba2009-07-29 17:15:45 +00002947 prev = curr;
2948 }
2949 }
Mike Stump1eb44332009-09-09 15:08:12 +00002950
John McCall781472f2010-08-25 08:40:02 +00002951 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002952
Sebastian Redl8351da02008-12-22 21:35:02 +00002953 // FIXME: We should detect handlers that cannot catch anything because an
2954 // earlier handler catches a superclass. Need to find a method that is not
2955 // quadratic for this.
2956 // Neither of these are explicitly forbidden, but every compiler detects them
2957 // and warns.
2958
John McCall9ae2f072010-08-23 23:25:46 +00002959 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002960 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002961}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002962
2963StmtResult
2964Sema::ActOnSEHTryBlock(bool IsCXXTry,
2965 SourceLocation TryLoc,
2966 Stmt *TryBlock,
2967 Stmt *Handler) {
2968 assert(TryBlock && Handler);
2969
2970 getCurFunction()->setHasBranchProtectedScope();
2971
2972 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2973}
2974
2975StmtResult
2976Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2977 Expr *FilterExpr,
2978 Stmt *Block) {
2979 assert(FilterExpr && Block);
2980
2981 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002982 return StmtError(Diag(FilterExpr->getExprLoc(),
2983 diag::err_filter_expression_integral)
2984 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002985 }
2986
2987 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2988}
2989
2990StmtResult
2991Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2992 Stmt *Block) {
2993 assert(Block);
2994 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2995}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002996
2997StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2998 bool IsIfExists,
2999 NestedNameSpecifierLoc QualifierLoc,
3000 DeclarationNameInfo NameInfo,
3001 Stmt *Nested)
3002{
3003 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003004 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003005 cast<CompoundStmt>(Nested));
3006}
3007
3008
Chad Rosier1093f492012-08-10 17:56:09 +00003009StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003010 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003011 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003012 UnqualifiedId &Name,
3013 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00003014 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003015 SS.getWithLocInContext(Context),
3016 GetNameFromUnqualifiedId(Name),
3017 Nested);
3018}
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003019
3020RecordDecl*
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003021Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3022 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003023 DeclContext *DC = CurContext;
3024 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3025 DC = DC->getParent();
3026
3027 RecordDecl *RD = 0;
3028 if (getLangOpts().CPlusPlus)
3029 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3030 else
3031 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3032
3033 DC->addDecl(RD);
3034 RD->setImplicit();
3035 RD->startDefinition();
3036
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003037 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003038 DC->addDecl(CD);
3039
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003040 // Build the context parameter
3041 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3042 DC = CapturedDecl::castToDeclContext(CD);
3043 IdentifierInfo *VarName = &Context.Idents.get("__context");
3044 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3045 ImplicitParamDecl *Param
3046 = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
3047 DC->addDecl(Param);
3048
3049 CD->setContextParam(Param);
3050
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003051 return RD;
3052}
3053
3054static void buildCapturedStmtCaptureList(
3055 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3056 SmallVectorImpl<Expr *> &CaptureInits,
3057 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3058
3059 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3060 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3061
3062 if (Cap->isThisCapture()) {
3063 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3064 CapturedStmt::VCK_This));
Richard Smith0d8e9642013-05-16 06:20:58 +00003065 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003066 continue;
3067 }
3068
3069 assert(Cap->isReferenceCapture() &&
3070 "non-reference capture not yet implemented");
3071
3072 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3073 CapturedStmt::VCK_ByRef,
3074 Cap->getVariable()));
Richard Smith0d8e9642013-05-16 06:20:58 +00003075 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003076 }
3077}
3078
3079void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003080 CapturedRegionKind Kind,
3081 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003082 CapturedDecl *CD = 0;
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003083 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003084
3085 // Enter the capturing scope for this captured region.
3086 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3087
3088 if (CurScope)
3089 PushDeclContext(CurScope, CD);
3090 else
3091 CurContext = CD;
3092
3093 PushExpressionEvaluationContext(PotentiallyEvaluated);
3094}
3095
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003096void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003097 DiscardCleanupsInEvaluationContext();
3098 PopExpressionEvaluationContext();
3099
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003100 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3101 RecordDecl *Record = RSI->TheRecordDecl;
3102 Record->setInvalidDecl();
3103
3104 SmallVector<Decl*, 4> Fields;
3105 for (RecordDecl::field_iterator I = Record->field_begin(),
3106 E = Record->field_end(); I != E; ++I)
3107 Fields.push_back(*I);
3108 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3109 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3110
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003111 PopDeclContext();
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003112 PopFunctionScopeInfo();
3113}
3114
3115StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3116 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3117
3118 SmallVector<CapturedStmt::Capture, 4> Captures;
3119 SmallVector<Expr *, 4> CaptureInits;
3120 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3121
3122 CapturedDecl *CD = RSI->TheCapturedDecl;
3123 RecordDecl *RD = RSI->TheRecordDecl;
3124
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003125 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3126 RSI->CapRegionKind, Captures,
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003127 CaptureInits, CD, RD);
3128
3129 CD->setBody(Res->getCapturedStmt());
3130 RD->completeDefinition();
3131
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003132 DiscardCleanupsInEvaluationContext();
3133 PopExpressionEvaluationContext();
3134
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003135 PopDeclContext();
3136 PopFunctionScopeInfo();
3137
3138 return Owned(Res);
3139}