blob: 136a5e169d923bb0d4ca369cc1e091a5595a55bb [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) {
Serge Pavlov18062392013-08-27 13:15:56 +000068 DeclGroupRef DG = dg.get();
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) {
Serge Pavlov18062392013-08-27 13:15:56 +000077 DeclGroupRef DG = dg.get();
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
Robert Wilhelmc895f4d2013-08-19 20:51:20 +0000294StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
295 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
296 const unsigned NumElts = Elts.size();
297
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000298 // If we're in C89 mode, check that we don't have any decls after stmts. If
299 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000300 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000301 // Note that __extension__ can be around a decl.
302 unsigned i = 0;
303 // Skip over all declarations.
304 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
305 /*empty*/;
306
307 // We found the end of the list or a statement. Scan for another declstmt.
308 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
309 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000311 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000312 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000313 Diag(D->getLocation(), diag::ext_mixed_decls_code);
314 }
315 }
Chris Lattner98414c12007-08-31 21:49:55 +0000316 // Warn about unused expressions in statements.
317 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000318 // Ignore statements that are last in a statement expression.
319 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000320 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Anders Carlsson636463e2009-07-30 22:17:18 +0000322 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000323 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000324
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000325 // Check for suspicious empty body (null statement) in `for' and `while'
326 // statements. Don't do anything for template instantiations, this just adds
327 // noise.
328 if (NumElts != 0 && !CurrentInstantiationScope &&
329 getCurCompoundScope().HasEmptyLoopBodies) {
330 for (unsigned i = 0; i != NumElts - 1; ++i)
331 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
332 }
333
Robert Wilhelmc895f4d2013-08-19 20:51:20 +0000334 return Owned(new (Context) CompoundStmt(Context, Elts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000335}
336
John McCall60d7b3a2010-08-24 06:29:42 +0000337StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000338Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
339 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000340 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000341 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000342
John McCall781472f2010-08-25 08:40:02 +0000343 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000344 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000345 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000346 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000347
Richard Smith80ad52f2013-01-02 11:42:31 +0000348 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000349 // C99 6.8.4.2p3: The expression shall be an integer constant.
350 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000351 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
352 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
353 if (!LHSVal)
354 return StmtError();
355 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000356
357 // GCC extension: The expression shall be an integer constant.
358
Richard Smith282e7e62012-02-04 09:53:13 +0000359 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
360 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
361 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000362 }
363 }
Ben Langmuira0152d42013-04-29 13:07:42 +0000364
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000365 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
366 getLangOpts().CPlusPlus11).take();
367 if (RHSVal)
368 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
369 getLangOpts().CPlusPlus11).take();
Richard Smith8ef7b202012-01-18 23:55:52 +0000370
Douglas Gregordbb26db2009-05-15 23:57:33 +0000371 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
372 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000373 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000374 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000375}
376
Chris Lattner24e1e702009-03-04 04:23:07 +0000377/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000378void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000379 DiagnoseUnusedExprResult(SubStmt);
380
Chris Lattner24e1e702009-03-04 04:23:07 +0000381 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000382 CS->setSubStmt(SubStmt);
383}
384
John McCall60d7b3a2010-08-24 06:29:42 +0000385StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000386Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000387 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000388 DiagnoseUnusedExprResult(SubStmt);
389
John McCall781472f2010-08-25 08:40:02 +0000390 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000391 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000392 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000393 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000394
Douglas Gregordbb26db2009-05-15 23:57:33 +0000395 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000396 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000397 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398}
399
John McCall60d7b3a2010-08-24 06:29:42 +0000400StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000401Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
402 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000403 // If the label was multiply defined, reject it now.
404 if (TheDecl->getStmt()) {
405 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
406 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000407 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 }
Sebastian Redlde307472009-01-11 00:38:46 +0000409
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000410 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000411 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
412 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000413 if (!TheDecl->isGnuLocal()) {
414 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000415 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000416 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000417 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000418}
419
Richard Smith534986f2012-04-14 00:33:13 +0000420StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000421 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000422 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000423 // Fill in the declaration and return it.
424 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000425 return Owned(LS);
426}
427
John McCall60d7b3a2010-08-24 06:29:42 +0000428StmtResult
John McCalld226f652010-08-21 09:40:31 +0000429Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000430 Stmt *thenStmt, SourceLocation ElseLoc,
431 Stmt *elseStmt) {
Argyrios Kyrtzidis820b23d2013-02-15 18:34:13 +0000432 // If the condition was invalid, discard the if statement. We could recover
433 // better by replacing it with a valid expr, but don't do that yet.
434 if (!CondVal.get() && !CondVar) {
435 getCurFunction()->setHasDroppedStmt();
436 return StmtError();
437 }
438
John McCall60d7b3a2010-08-24 06:29:42 +0000439 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000441 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000442 if (CondVar) {
443 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000444 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000445 if (CondResult.isInvalid())
446 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000447 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000448 Expr *ConditionExpr = CondResult.takeAs<Expr>();
449 if (!ConditionExpr)
450 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451
Anders Carlsson75443112009-07-30 22:39:03 +0000452 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000453
John McCall9ae2f072010-08-23 23:25:46 +0000454 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000455 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
456 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000457 }
458
Anders Carlsson75443112009-07-30 22:39:03 +0000459 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000461 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000462 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000463}
464
Chris Lattnerf4021e72007-08-23 05:46:52 +0000465/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
466/// the specified width and sign. If an overflow occurs, detect it and emit
467/// the specified diagnostic.
468void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
469 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000470 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000471 unsigned DiagID) {
472 // Perform a conversion to the promoted condition type if needed.
473 if (NewWidth > Val.getBitWidth()) {
474 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000475 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000476 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000477
478 // If the input was signed and negative and the output is
479 // unsigned, don't bother to warn: this is implementation-defined
480 // behavior.
481 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000482 } else if (NewWidth < Val.getBitWidth()) {
483 // If this is a truncation, check for overflow.
484 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000485 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000486 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000487 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000488 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000489 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000490 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Chris Lattnerf4021e72007-08-23 05:46:52 +0000492 // Regardless of whether a diagnostic was emitted, really do the
493 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000494 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000495 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000496 } else if (NewSign != Val.isSigned()) {
497 // Convert the sign to match the sign of the condition. This can cause
498 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000499 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000500 // behavior.
501 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000502 llvm::APSInt OldVal(Val);
503 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000504 }
505}
506
Chris Lattner0471f5b2007-08-23 18:29:20 +0000507namespace {
508 struct CaseCompareFunctor {
509 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
510 const llvm::APSInt &RHS) {
511 return LHS.first < RHS;
512 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000513 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
514 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
515 return LHS.first < RHS.first;
516 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000517 bool operator()(const llvm::APSInt &LHS,
518 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
519 return LHS < RHS.first;
520 }
521 };
522}
523
Chris Lattner764a7ce2007-09-21 18:15:22 +0000524/// CmpCaseVals - Comparison predicate for sorting case values.
525///
526static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
527 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
528 if (lhs.first < rhs.first)
529 return true;
530
531 if (lhs.first == rhs.first &&
532 lhs.second->getCaseLoc().getRawEncoding()
533 < rhs.second->getCaseLoc().getRawEncoding())
534 return true;
535 return false;
536}
537
Douglas Gregorba915af2010-02-08 22:24:16 +0000538/// CmpEnumVals - Comparison predicate for sorting enumeration values.
539///
540static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
541 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
542{
543 return lhs.first < rhs.first;
544}
545
546/// EqEnumVals - Comparison preficate for uniqing enumeration values.
547///
548static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
549 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
550{
551 return lhs.first == rhs.first;
552}
553
Chris Lattner5f048812009-10-16 16:45:22 +0000554/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
555/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000556static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
557 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
558 expr = cleanups->getSubExpr();
559 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
560 if (impcast->getCastKind() != CK_IntegralCast) break;
561 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000562 }
563 return expr->getType();
564}
565
John McCall60d7b3a2010-08-24 06:29:42 +0000566StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000568 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000569 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000570
Douglas Gregor586596f2010-05-06 17:25:47 +0000571 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000572 if (CondVar) {
573 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000574 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
575 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000576 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577
John McCall9ae2f072010-08-23 23:25:46 +0000578 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000579 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580
John McCall9ae2f072010-08-23 23:25:46 +0000581 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000582 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
Douglas Gregorab41fe92012-05-04 22:38:52 +0000584 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
585 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000586
Douglas Gregorab41fe92012-05-04 22:38:52 +0000587 public:
588 SwitchConvertDiagnoser(Expr *Cond)
Richard Smith097e0a22013-05-21 19:05:48 +0000589 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
590 Cond(Cond) {}
Chad Rosier8e1e0542012-06-20 18:51:04 +0000591
Richard Smith097e0a22013-05-21 19:05:48 +0000592 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
593 QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000594 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
595 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000596
Richard Smith097e0a22013-05-21 19:05:48 +0000597 virtual SemaDiagnosticBuilder diagnoseIncomplete(
598 Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000599 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
600 << T << Cond->getSourceRange();
601 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000602
Richard Smith097e0a22013-05-21 19:05:48 +0000603 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
604 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000605 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
606 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000607
Richard Smith097e0a22013-05-21 19:05:48 +0000608 virtual SemaDiagnosticBuilder noteExplicitConv(
609 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000610 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
611 << ConvTy->isEnumeralType() << ConvTy;
612 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000613
Richard Smith097e0a22013-05-21 19:05:48 +0000614 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
615 QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000616 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
617 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000618
Richard Smith097e0a22013-05-21 19:05:48 +0000619 virtual SemaDiagnosticBuilder noteAmbiguous(
620 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000621 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
622 << ConvTy->isEnumeralType() << ConvTy;
623 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000624
Richard Smith097e0a22013-05-21 19:05:48 +0000625 virtual SemaDiagnosticBuilder diagnoseConversion(
626 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
627 llvm_unreachable("conversion functions are permitted");
Douglas Gregorab41fe92012-05-04 22:38:52 +0000628 }
629 } SwitchDiagnoser(Cond);
630
Richard Smith097e0a22013-05-21 19:05:48 +0000631 CondResult =
632 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCall9ae2f072010-08-23 23:25:46 +0000633 if (CondResult.isInvalid()) return StmtError();
634 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000635
John McCalla8e0cd82011-08-06 07:30:58 +0000636 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
637 CondResult = UsualUnaryConversions(Cond);
638 if (CondResult.isInvalid()) return StmtError();
639 Cond = CondResult.take();
640
John McCalld226f652010-08-21 09:40:31 +0000641 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000642 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000643 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000644 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000645 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000646 }
John McCallb60a77e2010-08-01 00:26:45 +0000647
John McCall781472f2010-08-25 08:40:02 +0000648 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000649
John McCall9ae2f072010-08-23 23:25:46 +0000650 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000651 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000652 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000653}
654
Gabor Greif28164ab2010-10-01 22:05:14 +0000655static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
656 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000657 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000658 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000659 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000660 Val.setIsSigned(IsSigned);
661}
662
John McCall60d7b3a2010-08-24 06:29:42 +0000663StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000664Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
665 Stmt *BodyStmt) {
666 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000667 assert(SS == getCurFunction()->SwitchStack.back() &&
668 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000669
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000670 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000671 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000672
Chris Lattnerf4021e72007-08-23 05:46:52 +0000673 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000674 if (!CondExpr) return StmtError();
675
676 QualType CondType = CondExpr->getType();
677
John McCall0fb97082010-05-18 03:19:21 +0000678 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000679 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000680 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000681
Chris Lattner5f048812009-10-16 16:45:22 +0000682 // C++ 6.4.2.p2:
683 // Integral promotions are performed (on the switch condition).
684 //
685 // A case value unrepresentable by the original switch condition
686 // type (before the promotion) doesn't make sense, even when it can
687 // be represented by the promoted type. Therefore we need to find
688 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000689 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000690 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000692 // appropriate type now, just return an error.
693 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000694 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000695
Chris Lattner2b334bb2010-04-16 23:34:13 +0000696 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000697 // switch(bool_expr) {...} is often a programmer error, e.g.
698 // switch(n && mask) { ... } // Doh - should be "n & mask".
699 // One can always use an if statement instead of switch(bool_expr).
700 Diag(SwitchLoc, diag::warn_bool_switch_condition)
701 << CondExpr->getSourceRange();
702 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000703 }
Sebastian Redlde307472009-01-11 00:38:46 +0000704
Chris Lattnerf4021e72007-08-23 05:46:52 +0000705 // Get the bitwidth of the switched-on value before promotions. We must
706 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000707 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000708 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000709 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000710 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000711 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000712 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattnerf4021e72007-08-23 05:46:52 +0000714 // Accumulate all of the case values in a vector so that we can sort them
715 // and detect duplicates. This vector contains the APInt for the case after
716 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000717 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000718 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Chris Lattnerf4021e72007-08-23 05:46:52 +0000720 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000721 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
722 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattnerf4021e72007-08-23 05:46:52 +0000724 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000726 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Douglas Gregordbb26db2009-05-15 23:57:33 +0000728 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000729 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000731 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000732 if (TheDefaultStmt) {
733 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000734 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000735
Chris Lattnerf4021e72007-08-23 05:46:52 +0000736 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000737 // we'll return a valid AST. This requires recursing down the AST and
738 // finding it, not something we are set up to do right now. For now,
739 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000740 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000741 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000742 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattnerf4021e72007-08-23 05:46:52 +0000744 } else {
745 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattner1e0a3902008-01-16 19:17:22 +0000747 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000748
749 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
750 HasDependentValue = true;
751 break;
752 }
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Richard Smith8ef7b202012-01-18 23:55:52 +0000754 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Richard Smith80ad52f2013-01-02 11:42:31 +0000756 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000757 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
758 // constant expression of the promoted type of the switch condition.
759 ExprResult ConvLo =
760 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
761 if (ConvLo.isInvalid()) {
762 CaseListIsErroneous = true;
763 continue;
764 }
765 Lo = ConvLo.take();
766 } else {
767 // We already verified that the expression has a i-c-e value (C99
768 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000769 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000770
771 // If the LHS is not the same type as the condition, insert an implicit
772 // cast.
773 Lo = DefaultLvalueConversion(Lo).take();
774 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
775 }
776
777 // Convert the value to the same width/sign as the condition had prior to
778 // integral promotions.
779 //
780 // FIXME: This causes us to reject valid code:
781 // switch ((char)c) { case 256: case 0: return 0; }
782 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000783 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000784 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000785 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000786
Chris Lattner1e0a3902008-01-16 19:17:22 +0000787 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000789 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000790 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000791 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000792 CS->getRHS()->isValueDependent()) {
793 HasDependentValue = true;
794 break;
795 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000796 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000797 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000798 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000799 }
800 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000801
802 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000803 // If we don't have a default statement, check whether the
804 // condition is constant.
805 llvm::APSInt ConstantCondValue;
806 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000807 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000808 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000809 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
810 Expr::SE_AllowSideEffects);
811 assert(!HasConstantCond ||
812 (ConstantCondValue.getBitWidth() == CondWidth &&
813 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000814 }
Richard Smith80d4b552011-12-28 19:48:30 +0000815 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000816
Douglas Gregordbb26db2009-05-15 23:57:33 +0000817 // Sort all the scalar case values so we can easily detect duplicates.
818 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
819
820 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000821 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
822 if (ShouldCheckConstantCond &&
823 CaseVals[i].first == ConstantCondValue)
824 ShouldCheckConstantCond = false;
825
826 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000827 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000828 // First, determine if either case value has a name
829 StringRef PrevString, CurrString;
830 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
831 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
832 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
833 PrevString = DeclRef->getDecl()->getName();
834 }
835 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
836 CurrString = DeclRef->getDecl()->getName();
837 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000838 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000839 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000840
841 if (PrevString == CurrString)
842 Diag(CaseVals[i].second->getLHS()->getLocStart(),
843 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000844 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000845 else
846 Diag(CaseVals[i].second->getLHS()->getLocStart(),
847 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000848 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
849 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000850 CaseValStr;
851
John McCall0fb97082010-05-18 03:19:21 +0000852 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000853 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000854 // FIXME: We really want to remove the bogus case stmt from the
855 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000856 CaseListIsErroneous = true;
857 }
858 }
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregordbb26db2009-05-15 23:57:33 +0000861 // Detect duplicate case ranges, which usually don't exist at all in
862 // the first place.
863 if (!CaseRanges.empty()) {
864 // Sort all the case ranges by their low value so we can easily detect
865 // overlaps between ranges.
866 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Douglas Gregordbb26db2009-05-15 23:57:33 +0000868 // Scan the ranges, computing the high values and removing empty ranges.
869 std::vector<llvm::APSInt> HiVals;
870 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000871 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000872 CaseStmt *CR = CaseRanges[i].second;
873 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000874 llvm::APSInt HiVal;
875
Richard Smith80ad52f2013-01-02 11:42:31 +0000876 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000877 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
878 // constant expression of the promoted type of the switch condition.
879 ExprResult ConvHi =
880 CheckConvertedConstantExpression(Hi, CondType, HiVal,
881 CCEK_CaseValue);
882 if (ConvHi.isInvalid()) {
883 CaseListIsErroneous = true;
884 continue;
885 }
886 Hi = ConvHi.take();
887 } else {
888 HiVal = Hi->EvaluateKnownConstInt(Context);
889
890 // If the RHS is not the same type as the condition, insert an
891 // implicit cast.
892 Hi = DefaultLvalueConversion(Hi).take();
893 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Douglas Gregordbb26db2009-05-15 23:57:33 +0000896 // Convert the value to the same width/sign as the condition.
897 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000898 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000899 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregordbb26db2009-05-15 23:57:33 +0000901 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Douglas Gregordbb26db2009-05-15 23:57:33 +0000903 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000904 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000905 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
906 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000907 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000908 CaseRanges.erase(CaseRanges.begin()+i);
909 --i, --e;
910 continue;
911 }
John McCall0fb97082010-05-18 03:19:21 +0000912
913 if (ShouldCheckConstantCond &&
914 LoVal <= ConstantCondValue &&
915 ConstantCondValue <= HiVal)
916 ShouldCheckConstantCond = false;
917
Douglas Gregordbb26db2009-05-15 23:57:33 +0000918 HiVals.push_back(HiVal);
919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Douglas Gregordbb26db2009-05-15 23:57:33 +0000921 // Rescan the ranges, looking for overlap with singleton values and other
922 // ranges. Since the range list is sorted, we only need to compare case
923 // ranges with their neighbors.
924 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
925 llvm::APSInt &CRLo = CaseRanges[i].first;
926 llvm::APSInt &CRHi = HiVals[i];
927 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Douglas Gregordbb26db2009-05-15 23:57:33 +0000929 // Check to see whether the case range overlaps with any
930 // singleton cases.
931 CaseStmt *OverlapStmt = 0;
932 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Douglas Gregordbb26db2009-05-15 23:57:33 +0000934 // Find the smallest value >= the lower bound. If I is in the
935 // case range, then we have overlap.
936 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
937 CaseVals.end(), CRLo,
938 CaseCompareFunctor());
939 if (I != CaseVals.end() && I->first < CRHi) {
940 OverlapVal = I->first; // Found overlap with scalar.
941 OverlapStmt = I->second;
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregordbb26db2009-05-15 23:57:33 +0000944 // Find the smallest value bigger than the upper bound.
945 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
946 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
947 OverlapVal = (I-1)->first; // Found overlap with scalar.
948 OverlapStmt = (I-1)->second;
949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Douglas Gregordbb26db2009-05-15 23:57:33 +0000951 // Check to see if this case stmt overlaps with the subsequent
952 // case range.
953 if (i && CRLo <= HiVals[i-1]) {
954 OverlapVal = HiVals[i-1]; // Found overlap with range.
955 OverlapStmt = CaseRanges[i-1].second;
956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregordbb26db2009-05-15 23:57:33 +0000958 if (OverlapStmt) {
959 // If we have a duplicate, report it.
960 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
961 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000962 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000963 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000964 // FIXME: We really want to remove the bogus case stmt from the
965 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000966 CaseListIsErroneous = true;
967 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000968 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000969 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000970
John McCall0fb97082010-05-18 03:19:21 +0000971 // Complain if we have a constant condition and we didn't find a match.
972 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
973 // TODO: it would be nice if we printed enums as enums, chars as
974 // chars, etc.
975 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
976 << ConstantCondValue.toString(10)
977 << CondExpr->getSourceRange();
978 }
979
980 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000981 // values. We only issue a warning if there is not 'default:', but
982 // we still do the analysis to preserve this information in the AST
983 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000984 //
Chris Lattnerce784612010-09-16 17:09:42 +0000985 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000986
Douglas Gregorba915af2010-02-08 22:24:16 +0000987 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000988 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000989 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000990 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000991 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000992 EnumValsTy EnumVals;
993
John McCall0fb97082010-05-18 03:19:21 +0000994 // Gather all enum values, set their type and sort them,
995 // allowing easier comparison with CaseVals.
996 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000997 EDI != ED->enumerator_end(); ++EDI) {
998 llvm::APSInt Val = EDI->getInitVal();
999 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +00001000 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +00001001 }
1002 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +00001003 EnumValsTy::iterator EIend =
1004 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +00001005
1006 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +00001007 EnumValsTy::const_iterator EI = EnumVals.begin();
1008 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1009 CI != CaseVals.end(); CI++) {
1010 while (EI != EIend && EI->first < CI->first)
1011 EI++;
1012 if (EI == EIend || EI->first > CI->first)
1013 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001014 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +00001015 }
1016 // See which of case ranges aren't in enum
1017 EI = EnumVals.begin();
1018 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1019 RI != CaseRanges.end() && EI != EIend; RI++) {
1020 while (EI != EIend && EI->first < RI->first)
1021 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001022
David Blaikie93667502012-01-22 02:31:55 +00001023 if (EI == EIend || EI->first != RI->first) {
1024 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001025 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001026 }
David Blaikie93667502012-01-22 02:31:55 +00001027
Chad Rosier1093f492012-08-10 17:56:09 +00001028 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001029 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1030 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1031 while (EI != EIend && EI->first < Hi)
1032 EI++;
1033 if (EI == EIend || EI->first != Hi)
1034 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001035 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037
Ted Kremenek559fb552010-09-09 00:05:53 +00001038 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001039 CaseValsTy::const_iterator CI = CaseVals.begin();
1040 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001041 bool hasCasesNotInSwitch = false;
1042
Chris Lattner5f9e2722011-07-23 10:55:15 +00001043 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001044
David Blaikie93667502012-01-22 02:31:55 +00001045 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001046 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001047 llvm::APSInt CIVal;
1048 while (CI != CaseVals.end() && CI->first < EI->first)
1049 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001050
Douglas Gregorba915af2010-02-08 22:24:16 +00001051 if (CI != CaseVals.end() && CI->first == EI->first)
1052 continue;
1053
Ted Kremenek559fb552010-09-09 00:05:53 +00001054 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001055 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001056 llvm::APSInt Hi =
1057 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001058 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001059 if (EI->first <= Hi)
1060 break;
1061 }
1062
Ted Kremenek559fb552010-09-09 00:05:53 +00001063 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001064 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001065 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001066 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001067 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
David Blaikie585d7792012-01-23 04:46:12 +00001069 if (TheDefaultStmt && UnhandledNames.empty())
1070 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001071
Chris Lattnerce784612010-09-16 17:09:42 +00001072 // Produce a nice diagnostic if multiple values aren't handled.
1073 switch (UnhandledNames.size()) {
1074 case 0: break;
1075 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001076 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001077 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001078 << UnhandledNames[0];
1079 break;
1080 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001081 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001082 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001083 << UnhandledNames[0] << UnhandledNames[1];
1084 break;
1085 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001086 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1087 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001088 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1089 break;
1090 default:
David Blaikie585d7792012-01-23 04:46:12 +00001091 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1092 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001093 << (unsigned)UnhandledNames.size()
1094 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1095 break;
1096 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001097
1098 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001099 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001100 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001101 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001102
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001103 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1104 diag::warn_empty_switch_body);
1105
Mike Stump390b4cc2009-05-16 07:39:55 +00001106 // FIXME: If the case list was broken is some way, we don't have a good system
1107 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001108 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001109 return StmtError();
1110
Sebastian Redlde307472009-01-11 00:38:46 +00001111 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001112}
1113
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001114void
1115Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1116 Expr *SrcExpr) {
Joey Gouly48a1e812013-06-06 13:48:00 +00001117 if (Diags.getDiagnosticLevel(diag::warn_not_in_enum_assignment,
1118 SrcExpr->getExprLoc()) ==
1119 DiagnosticsEngine::Ignored)
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001120 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001121
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001122 if (const EnumType *ET = DstType->getAs<EnumType>())
1123 if (!Context.hasSameType(SrcType, DstType) &&
1124 SrcType->isIntegerType()) {
1125 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1126 SrcExpr->isIntegerConstantExpr(Context)) {
1127 // Get the bitwidth of the enum value before promotions.
Joey Gouly48a1e812013-06-06 13:48:00 +00001128 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001129 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1130
1131 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly48a1e812013-06-06 13:48:00 +00001132 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001133 const EnumDecl *ED = ET->getDecl();
Joey Gouly48a1e812013-06-06 13:48:00 +00001134 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1135 EnumValsTy;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001136 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001137
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001138 // Gather all enum values, set their type and sort them,
1139 // allowing easier comparison with rhs constant.
1140 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1141 EDI != ED->enumerator_end(); ++EDI) {
1142 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly48a1e812013-06-06 13:48:00 +00001143 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001144 EnumVals.push_back(std::make_pair(Val, *EDI));
1145 }
1146 if (EnumVals.empty())
1147 return;
1148 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1149 EnumValsTy::iterator EIend =
Joey Gouly48a1e812013-06-06 13:48:00 +00001150 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001151
Joey Gouly48a1e812013-06-06 13:48:00 +00001152 // See which values aren't in the enum.
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001153 EnumValsTy::const_iterator EI = EnumVals.begin();
1154 while (EI != EIend && EI->first < RhsVal)
1155 EI++;
1156 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly48a1e812013-06-06 13:48:00 +00001157 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001158 << DstType;
1159 }
1160 }
1161 }
1162}
1163
John McCall60d7b3a2010-08-24 06:29:42 +00001164StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001165Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001166 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001167 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001168
Douglas Gregor5656e142009-11-24 21:15:44 +00001169 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001170 if (CondVar) {
1171 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001172 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001173 if (CondResult.isInvalid())
1174 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001175 }
John McCall9ae2f072010-08-23 23:25:46 +00001176 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001177 if (!ConditionExpr)
1178 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001179
John McCall9ae2f072010-08-23 23:25:46 +00001180 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001182 if (isa<NullStmt>(Body))
1183 getCurCompoundScope().setHasEmptyLoopBodies();
1184
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001185 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001186 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001187}
1188
John McCall60d7b3a2010-08-24 06:29:42 +00001189StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001190Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001191 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001192 Expr *Cond, SourceLocation CondRParen) {
1193 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001194
John Wiegley429bb272011-04-08 18:41:53 +00001195 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001196 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001197 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001198 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001199
Richard Smith41956372013-01-14 22:39:08 +00001200 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001201 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001202 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001203 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204
John McCall9ae2f072010-08-23 23:25:46 +00001205 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001206
John McCall9ae2f072010-08-23 23:25:46 +00001207 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001208}
1209
Richard Trieu694e7962012-04-30 18:01:30 +00001210namespace {
1211 // This visitor will traverse a conditional statement and store all
1212 // the evaluated decls into a vector. Simple is set to true if none
1213 // of the excluded constructs are used.
1214 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1215 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Craig Topperad5b69d2013-07-14 16:47:36 +00001216 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001217 bool Simple;
Richard Trieu923cada2013-05-31 22:46:45 +00001218 public:
1219 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001220
Richard Trieu923cada2013-05-31 22:46:45 +00001221 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Craig Topperad5b69d2013-07-14 16:47:36 +00001222 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu923cada2013-05-31 22:46:45 +00001223 Inherited(S.Context),
1224 Decls(Decls),
1225 Ranges(Ranges),
1226 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001227
Richard Trieu923cada2013-05-31 22:46:45 +00001228 bool isSimple() { return Simple; }
Richard Trieu694e7962012-04-30 18:01:30 +00001229
Richard Trieu923cada2013-05-31 22:46:45 +00001230 // Replaces the method in EvaluatedExprVisitor.
1231 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001232 Simple = false;
Richard Trieu923cada2013-05-31 22:46:45 +00001233 }
1234
1235 // Any Stmt not whitelisted will cause the condition to be marked complex.
1236 void VisitStmt(Stmt *S) {
1237 Simple = false;
1238 }
1239
1240 void VisitBinaryOperator(BinaryOperator *E) {
1241 Visit(E->getLHS());
1242 Visit(E->getRHS());
1243 }
1244
1245 void VisitCastExpr(CastExpr *E) {
Richard Trieu694e7962012-04-30 18:01:30 +00001246 Visit(E->getSubExpr());
Richard Trieu923cada2013-05-31 22:46:45 +00001247 }
Richard Trieu694e7962012-04-30 18:01:30 +00001248
Richard Trieu923cada2013-05-31 22:46:45 +00001249 void VisitUnaryOperator(UnaryOperator *E) {
1250 // Skip checking conditionals with derefernces.
1251 if (E->getOpcode() == UO_Deref)
1252 Simple = false;
1253 else
1254 Visit(E->getSubExpr());
1255 }
Richard Trieu694e7962012-04-30 18:01:30 +00001256
Richard Trieu923cada2013-05-31 22:46:45 +00001257 void VisitConditionalOperator(ConditionalOperator *E) {
1258 Visit(E->getCond());
1259 Visit(E->getTrueExpr());
1260 Visit(E->getFalseExpr());
1261 }
Richard Trieu694e7962012-04-30 18:01:30 +00001262
Richard Trieu923cada2013-05-31 22:46:45 +00001263 void VisitParenExpr(ParenExpr *E) {
1264 Visit(E->getSubExpr());
1265 }
Richard Trieu694e7962012-04-30 18:01:30 +00001266
Richard Trieu923cada2013-05-31 22:46:45 +00001267 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1268 Visit(E->getOpaqueValue()->getSourceExpr());
1269 Visit(E->getFalseExpr());
1270 }
Richard Trieu694e7962012-04-30 18:01:30 +00001271
Richard Trieu923cada2013-05-31 22:46:45 +00001272 void VisitIntegerLiteral(IntegerLiteral *E) { }
1273 void VisitFloatingLiteral(FloatingLiteral *E) { }
1274 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1275 void VisitCharacterLiteral(CharacterLiteral *E) { }
1276 void VisitGNUNullExpr(GNUNullExpr *E) { }
1277 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu694e7962012-04-30 18:01:30 +00001278
Richard Trieu923cada2013-05-31 22:46:45 +00001279 void VisitDeclRefExpr(DeclRefExpr *E) {
1280 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1281 if (!VD) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001282
Richard Trieu923cada2013-05-31 22:46:45 +00001283 Ranges.push_back(E->getSourceRange());
1284
1285 Decls.insert(VD);
1286 }
Richard Trieu694e7962012-04-30 18:01:30 +00001287
1288 }; // end class DeclExtractor
1289
1290 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001291 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001292 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1293 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1294 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001295
Richard Trieu923cada2013-05-31 22:46:45 +00001296 public:
1297 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu694e7962012-04-30 18:01:30 +00001298
Richard Trieu923cada2013-05-31 22:46:45 +00001299 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1300 Stmt *Statement) :
1301 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1302 if (!Statement) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001303
Richard Trieu923cada2013-05-31 22:46:45 +00001304 Visit(Statement);
Richard Trieu694e7962012-04-30 18:01:30 +00001305 }
1306
Richard Trieu923cada2013-05-31 22:46:45 +00001307 void VisitReturnStmt(ReturnStmt *S) {
1308 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001309 }
1310
Richard Trieu923cada2013-05-31 22:46:45 +00001311 void VisitBreakStmt(BreakStmt *S) {
1312 FoundDecl = true;
Richard Trieu694e7962012-04-30 18:01:30 +00001313 }
1314
Richard Trieu923cada2013-05-31 22:46:45 +00001315 void VisitGotoStmt(GotoStmt *S) {
1316 FoundDecl = true;
1317 }
Richard Trieu694e7962012-04-30 18:01:30 +00001318
Richard Trieu923cada2013-05-31 22:46:45 +00001319 void VisitCastExpr(CastExpr *E) {
1320 if (E->getCastKind() == CK_LValueToRValue)
1321 CheckLValueToRValueCast(E->getSubExpr());
1322 else
1323 Visit(E->getSubExpr());
1324 }
Richard Trieu694e7962012-04-30 18:01:30 +00001325
Richard Trieu923cada2013-05-31 22:46:45 +00001326 void CheckLValueToRValueCast(Expr *E) {
1327 E = E->IgnoreParenImpCasts();
1328
1329 if (isa<DeclRefExpr>(E)) {
1330 return;
1331 }
1332
1333 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1334 Visit(CO->getCond());
1335 CheckLValueToRValueCast(CO->getTrueExpr());
1336 CheckLValueToRValueCast(CO->getFalseExpr());
1337 return;
1338 }
1339
1340 if (BinaryConditionalOperator *BCO =
1341 dyn_cast<BinaryConditionalOperator>(E)) {
1342 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1343 CheckLValueToRValueCast(BCO->getFalseExpr());
1344 return;
1345 }
1346
1347 Visit(E);
1348 }
1349
1350 void VisitDeclRefExpr(DeclRefExpr *E) {
1351 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1352 if (Decls.count(VD))
1353 FoundDecl = true;
1354 }
1355
1356 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu694e7962012-04-30 18:01:30 +00001357
1358 }; // end class DeclMatcher
1359
1360 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1361 Expr *Third, Stmt *Body) {
1362 // Condition is empty
1363 if (!Second) return;
1364
1365 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1366 Second->getLocStart())
1367 == DiagnosticsEngine::Ignored)
1368 return;
1369
1370 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1371 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001372 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001373 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001374 DE.Visit(Second);
1375
1376 // Don't analyze complex conditionals.
1377 if (!DE.isSimple()) return;
1378
1379 // No decls found.
1380 if (Decls.size() == 0) return;
1381
Richard Trieu90875992012-05-04 03:01:54 +00001382 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001383 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1384 E = Decls.end();
1385 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001386 if ((*I)->getType().isVolatileQualified() ||
1387 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001388
1389 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1390 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1391 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1392 return;
1393
1394 // Load decl names into diagnostic.
1395 if (Decls.size() > 4)
1396 PDiag << 0;
1397 else {
1398 PDiag << Decls.size();
1399 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1400 E = Decls.end();
1401 I != E; ++I)
1402 PDiag << (*I)->getDeclName();
1403 }
1404
1405 // Load SourceRanges into diagnostic if there is room.
1406 // Otherwise, load the SourceRange of the conditional expression.
1407 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper09d19ef2013-07-04 03:08:24 +00001408 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001409 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001410 I != E; ++I)
1411 PDiag << *I;
1412 else
1413 PDiag << Second->getSourceRange();
1414
1415 S.Diag(Ranges.begin()->getBegin(), PDiag);
1416 }
1417
Richard Trieuacdbbc72013-08-06 21:31:54 +00001418 // If Statement is an incemement or decrement, return true and sets the
1419 // variables Increment and DRE.
1420 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1421 DeclRefExpr *&DRE) {
1422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1423 switch (UO->getOpcode()) {
1424 default: return false;
1425 case UO_PostInc:
1426 case UO_PreInc:
1427 Increment = true;
1428 break;
1429 case UO_PostDec:
1430 case UO_PreDec:
1431 Increment = false;
1432 break;
1433 }
1434 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1435 return DRE;
1436 }
1437
1438 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1439 FunctionDecl *FD = Call->getDirectCallee();
1440 if (!FD || !FD->isOverloadedOperator()) return false;
1441 switch (FD->getOverloadedOperator()) {
1442 default: return false;
1443 case OO_PlusPlus:
1444 Increment = true;
1445 break;
1446 case OO_MinusMinus:
1447 Increment = false;
1448 break;
1449 }
1450 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1451 return DRE;
1452 }
1453
1454 return false;
1455 }
1456
1457 // A visitor to determine if a continue statement is a subexpression.
1458 class ContinueFinder : public EvaluatedExprVisitor<ContinueFinder> {
1459 bool Found;
1460 public:
1461 ContinueFinder(Sema &S, Stmt* Body) :
1462 Inherited(S.Context),
1463 Found(false) {
1464 Visit(Body);
1465 }
1466
1467 typedef EvaluatedExprVisitor<ContinueFinder> Inherited;
1468
1469 void VisitContinueStmt(ContinueStmt* E) {
1470 Found = true;
1471 }
1472
1473 bool ContinueFound() { return Found; }
1474
1475 }; // end class ContinueFinder
1476
1477 // Emit a warning when a loop increment/decrement appears twice per loop
1478 // iteration. The conditions which trigger this warning are:
1479 // 1) The last statement in the loop body and the third expression in the
1480 // for loop are both increment or both decrement of the same variable
1481 // 2) No continue statements in the loop body.
1482 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1483 // Return when there is nothing to check.
1484 if (!Body || !Third) return;
1485
1486 if (S.Diags.getDiagnosticLevel(diag::warn_redundant_loop_iteration,
1487 Third->getLocStart())
1488 == DiagnosticsEngine::Ignored)
1489 return;
1490
1491 // Get the last statement from the loop body.
1492 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1493 if (!CS || CS->body_empty()) return;
1494 Stmt *LastStmt = CS->body_back();
1495 if (!LastStmt) return;
1496
1497 bool LoopIncrement, LastIncrement;
1498 DeclRefExpr *LoopDRE, *LastDRE;
1499
1500 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1501 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1502
1503 // Check that the two statements are both increments or both decrements
1504 // on the same varaible.
1505 if (LoopIncrement != LastIncrement ||
1506 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1507
1508 if (ContinueFinder(S, Body).ContinueFound()) return;
1509
1510 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1511 << LastDRE->getDecl() << LastIncrement;
1512 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1513 << LoopIncrement;
1514 }
1515
Richard Trieu694e7962012-04-30 18:01:30 +00001516} // end namespace
1517
John McCall60d7b3a2010-08-24 06:29:42 +00001518StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001519Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001520 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001521 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001522 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001523 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001524 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001525 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1526 // declare identifiers for objects having storage class 'auto' or
1527 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001528 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1529 DI!=DE; ++DI) {
1530 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001531 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001532 VD = 0;
Douglas Gregor12849d02013-04-08 20:52:24 +00001533 if (VD == 0) {
1534 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1535 (*DI)->setInvalidDecl();
1536 }
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001537 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001538 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001540
Richard Trieu694e7962012-04-30 18:01:30 +00001541 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieuacdbbc72013-08-06 21:31:54 +00001542 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu694e7962012-04-30 18:01:30 +00001543
John McCall60d7b3a2010-08-24 06:29:42 +00001544 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001545 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001546 if (secondVar) {
1547 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001548 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001549 if (SecondResult.isInvalid())
1550 return StmtError();
1551 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001552
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001553 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001554
Anders Carlsson3af708f2009-08-01 01:39:59 +00001555 DiagnoseUnusedExprResult(First);
1556 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001557 DiagnoseUnusedExprResult(Body);
1558
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001559 if (isa<NullStmt>(Body))
1560 getCurCompoundScope().setHasEmptyLoopBodies();
1561
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001562 return Owned(new (Context) ForStmt(Context, First,
1563 SecondResult.take(), ConditionVar,
1564 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001565 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001566}
1567
John McCallf6a16482010-12-04 03:47:34 +00001568/// In an Objective C collection iteration statement:
1569/// for (x in y)
1570/// x can be an arbitrary l-value expression. Bind it up as a
1571/// full-expression.
1572StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001573 // Reduce placeholder expressions here. Note that this rejects the
1574 // use of pseudo-object l-values in this position.
1575 ExprResult result = CheckPlaceholderExpr(E);
1576 if (result.isInvalid()) return StmtError();
1577 E = result.take();
1578
Richard Smith41956372013-01-14 22:39:08 +00001579 ExprResult FullExpr = ActOnFinishFullExpr(E);
1580 if (FullExpr.isInvalid())
1581 return StmtError();
1582 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001583}
1584
John McCall990567c2011-07-27 01:07:15 +00001585ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001586Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1587 if (!collection)
1588 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001589
John McCall990567c2011-07-27 01:07:15 +00001590 // Bail out early if we've got a type-dependent expression.
1591 if (collection->isTypeDependent()) return Owned(collection);
1592
1593 // Perform normal l-value conversion.
1594 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1595 if (result.isInvalid())
1596 return ExprError();
1597 collection = result.take();
1598
1599 // The operand needs to have object-pointer type.
1600 // TODO: should we do a contextual conversion?
1601 const ObjCObjectPointerType *pointerType =
1602 collection->getType()->getAs<ObjCObjectPointerType>();
1603 if (!pointerType)
1604 return Diag(forLoc, diag::err_collection_expr_type)
1605 << collection->getType() << collection->getSourceRange();
1606
1607 // Check that the operand provides
1608 // - countByEnumeratingWithState:objects:count:
1609 const ObjCObjectType *objectType = pointerType->getObjectType();
1610 ObjCInterfaceDecl *iface = objectType->getInterface();
1611
1612 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001613 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001614 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001615 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001616 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001617 ? diag::err_arc_collection_forward
1618 : 0,
1619 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001620 // Otherwise, if we have any useful type information, check that
1621 // the type declares the appropriate method.
1622 } else if (iface || !objectType->qual_empty()) {
1623 IdentifierInfo *selectorIdents[] = {
1624 &Context.Idents.get("countByEnumeratingWithState"),
1625 &Context.Idents.get("objects"),
1626 &Context.Idents.get("count")
1627 };
1628 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1629
1630 ObjCMethodDecl *method = 0;
1631
1632 // If there's an interface, look in both the public and private APIs.
1633 if (iface) {
1634 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001635 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001636 }
1637
1638 // Also check protocol qualifiers.
1639 if (!method)
1640 method = LookupMethodInQualifiedType(selector, pointerType,
1641 /*instance*/ true);
1642
1643 // If we didn't find it anywhere, give up.
1644 if (!method) {
1645 Diag(forLoc, diag::warn_collection_expr_type)
1646 << collection->getType() << selector << collection->getSourceRange();
1647 }
1648
1649 // TODO: check for an incompatible signature?
1650 }
1651
1652 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001653 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001654}
1655
John McCall60d7b3a2010-08-24 06:29:42 +00001656StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001657Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001658 Stmt *First, Expr *collection,
1659 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001660
1661 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001662 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001663
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001664 if (First) {
1665 QualType FirstType;
1666 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001667 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001668 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1669 diag::err_toomany_element_decls));
1670
Douglas Gregor12849d02013-04-08 20:52:24 +00001671 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1672 if (!D || D->isInvalidDecl())
1673 return StmtError();
1674
John McCallf85e1932011-06-15 23:02:42 +00001675 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001676 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1677 // declare identifiers for objects having storage class 'auto' or
1678 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001679 if (!D->hasLocalStorage())
1680 return StmtError(Diag(D->getLocation(),
Douglas Gregor12849d02013-04-08 20:52:24 +00001681 diag::err_non_local_variable_decl_in_for));
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001682
1683 // If the type contained 'auto', deduce the 'auto' to 'id'.
1684 if (FirstType->getContainedAutoType()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001685 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1686 VK_RValue);
1687 Expr *DeducedInit = &OpaqueId;
Richard Smith9b131752013-04-30 21:23:01 +00001688 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1689 DAR_Failed)
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001690 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith9b131752013-04-30 21:23:01 +00001691 if (FirstType.isNull()) {
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001692 D->setInvalidDecl();
1693 return StmtError();
1694 }
1695
Richard Smith9b131752013-04-30 21:23:01 +00001696 D->setType(FirstType);
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001697
1698 if (ActiveTemplateInstantiations.empty()) {
Richard Smith9b131752013-04-30 21:23:01 +00001699 SourceLocation Loc =
1700 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001701 Diag(Loc, diag::warn_auto_var_is_id)
1702 << D->getDeclName();
1703 }
1704 }
1705
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001706 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001707 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001708 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001709 return StmtError(Diag(First->getLocStart(),
1710 diag::err_selector_element_not_lvalue)
1711 << First->getSourceRange());
1712
Mike Stump1eb44332009-09-09 15:08:12 +00001713 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001714 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001715 if (!FirstType->isDependentType() &&
1716 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001717 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001718 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1719 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001720 }
Chad Rosier1093f492012-08-10 17:56:09 +00001721
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001722 if (CollectionExprResult.isInvalid())
1723 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001724
Richard Smith41956372013-01-14 22:39:08 +00001725 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1726 if (CollectionExprResult.isInvalid())
1727 return StmtError();
1728
Chad Rosier1093f492012-08-10 17:56:09 +00001729 return Owned(new (Context) ObjCForCollectionStmt(First,
1730 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001731 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001732}
Reid Spencer5f016e22007-07-11 17:01:13 +00001733
Richard Smithad762fc2011-04-14 22:09:26 +00001734/// Finish building a variable declaration for a for-range statement.
1735/// \return true if an error occurs.
1736static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith9b131752013-04-30 21:23:01 +00001737 SourceLocation Loc, int DiagID) {
Richard Smithad762fc2011-04-14 22:09:26 +00001738 // Deduce the type for the iterator variable now rather than leaving it to
1739 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith9b131752013-04-30 21:23:01 +00001740 QualType InitType;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001741 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith9b131752013-04-30 21:23:01 +00001742 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001743 Sema::DAR_Failed)
Richard Smith9b131752013-04-30 21:23:01 +00001744 SemaRef.Diag(Loc, DiagID) << Init->getType();
1745 if (InitType.isNull()) {
Richard Smithad762fc2011-04-14 22:09:26 +00001746 Decl->setInvalidDecl();
1747 return true;
1748 }
Richard Smith9b131752013-04-30 21:23:01 +00001749 Decl->setType(InitType);
Richard Smithad762fc2011-04-14 22:09:26 +00001750
John McCallf85e1932011-06-15 23:02:42 +00001751 // In ARC, infer lifetime.
1752 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1753 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001754 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001755 SemaRef.inferObjCARCLifetime(Decl))
1756 Decl->setInvalidDecl();
1757
Richard Smithad762fc2011-04-14 22:09:26 +00001758 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1759 /*TypeMayContainAuto=*/false);
1760 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001761 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001762 return false;
1763}
1764
Sam Panzere1715b62012-08-21 00:52:01 +00001765namespace {
1766
Richard Smithad762fc2011-04-14 22:09:26 +00001767/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001768/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001769/// nor from the diagnostics produced when analysing the implicit expressions
1770/// required in a for-range statement.
1771void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001772 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001773 CallExpr *CE = dyn_cast<CallExpr>(E);
1774 if (!CE)
1775 return;
1776 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1777 if (!D)
1778 return;
1779 SourceLocation Loc = D->getLocation();
1780
1781 std::string Description;
1782 bool IsTemplate = false;
1783 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1784 Description = SemaRef.getTemplateArgumentBindingsText(
1785 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1786 IsTemplate = true;
1787 }
1788
1789 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1790 << BEF << IsTemplate << Description << E->getType();
1791}
1792
Sam Panzere1715b62012-08-21 00:52:01 +00001793/// Build a variable declaration for a for-range statement.
1794VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1795 QualType Type, const char *Name) {
1796 DeclContext *DC = SemaRef.CurContext;
1797 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1798 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1799 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001800 TInfo, SC_None);
Sam Panzere1715b62012-08-21 00:52:01 +00001801 Decl->setImplicit();
1802 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001803}
1804
1805}
1806
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001807static bool ObjCEnumerationCollection(Expr *Collection) {
1808 return !Collection->isTypeDependent()
1809 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1810}
1811
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001812/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001813///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001814/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001815/// A range-based for statement is equivalent to
1816///
1817/// {
1818/// auto && __range = range-init;
1819/// for ( auto __begin = begin-expr,
1820/// __end = end-expr;
1821/// __begin != __end;
1822/// ++__begin ) {
1823/// for-range-declaration = *__begin;
1824/// statement
1825/// }
1826/// }
1827///
1828/// The body of the loop is not available yet, since it cannot be analysed until
1829/// we have determined the type of the for-range-declaration.
1830StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001831Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001832 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001833 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith37aa0f72013-08-21 01:40:36 +00001834 if (!First)
Richard Smithad762fc2011-04-14 22:09:26 +00001835 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001836
Richard Smith37aa0f72013-08-21 01:40:36 +00001837 if (Range && ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001838 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001839
1840 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1841 assert(DS && "first part of for range not a decl stmt");
1842
1843 if (!DS->isSingleDecl()) {
1844 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1845 return StmtError();
1846 }
Richard Smithad762fc2011-04-14 22:09:26 +00001847
Richard Smith37aa0f72013-08-21 01:40:36 +00001848 Decl *LoopVar = DS->getSingleDecl();
1849 if (LoopVar->isInvalidDecl() || !Range ||
1850 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1851 LoopVar->setInvalidDecl();
Richard Smithad762fc2011-04-14 22:09:26 +00001852 return StmtError();
Richard Smith37aa0f72013-08-21 01:40:36 +00001853 }
Richard Smithad762fc2011-04-14 22:09:26 +00001854
1855 // Build auto && __range = range-init
1856 SourceLocation RangeLoc = Range->getLocStart();
1857 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1858 Context.getAutoRRefDeductType(),
1859 "__range");
1860 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith37aa0f72013-08-21 01:40:36 +00001861 diag::err_for_range_deduction_failure)) {
1862 LoopVar->setInvalidDecl();
Richard Smithad762fc2011-04-14 22:09:26 +00001863 return StmtError();
Richard Smith37aa0f72013-08-21 01:40:36 +00001864 }
Richard Smithad762fc2011-04-14 22:09:26 +00001865
1866 // Claim the type doesn't contain auto: we've already done the checking.
1867 DeclGroupPtrTy RangeGroup =
Rafael Espindola4549d7f2013-07-09 12:05:01 +00001868 BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1869 /*TypeMayContainAuto=*/ false);
Richard Smithad762fc2011-04-14 22:09:26 +00001870 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith37aa0f72013-08-21 01:40:36 +00001871 if (RangeDecl.isInvalid()) {
1872 LoopVar->setInvalidDecl();
Richard Smithad762fc2011-04-14 22:09:26 +00001873 return StmtError();
Richard Smith37aa0f72013-08-21 01:40:36 +00001874 }
Richard Smithad762fc2011-04-14 22:09:26 +00001875
1876 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1877 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001878 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001879}
1880
1881/// \brief Create the initialization, compare, and increment steps for
1882/// the range-based for loop expression.
1883/// This function does not handle array-based for loops,
1884/// which are created in Sema::BuildCXXForRangeStmt.
1885///
1886/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1887/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1888/// CandidateSet and BEF are set and some non-success value is returned on
1889/// failure.
1890static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1891 Expr *BeginRange, Expr *EndRange,
1892 QualType RangeType,
1893 VarDecl *BeginVar,
1894 VarDecl *EndVar,
1895 SourceLocation ColonLoc,
1896 OverloadCandidateSet *CandidateSet,
1897 ExprResult *BeginExpr,
1898 ExprResult *EndExpr,
1899 Sema::BeginEndFunction *BEF) {
1900 DeclarationNameInfo BeginNameInfo(
1901 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1902 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1903 ColonLoc);
1904
1905 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1906 Sema::LookupMemberName);
1907 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1908
1909 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1910 // - if _RangeT is a class type, the unqualified-ids begin and end are
1911 // looked up in the scope of class _RangeT as if by class member access
1912 // lookup (3.4.5), and if either (or both) finds at least one
1913 // declaration, begin-expr and end-expr are __range.begin() and
1914 // __range.end(), respectively;
1915 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1916 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1917
1918 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1919 SourceLocation RangeLoc = BeginVar->getLocation();
1920 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1921
1922 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1923 << RangeLoc << BeginRange->getType() << *BEF;
1924 return Sema::FRS_DiagnosticIssued;
1925 }
1926 } else {
1927 // - otherwise, begin-expr and end-expr are begin(__range) and
1928 // end(__range), respectively, where begin and end are looked up with
1929 // argument-dependent lookup (3.4.2). For the purposes of this name
1930 // lookup, namespace std is an associated namespace.
1931
1932 }
1933
1934 *BEF = Sema::BEF_begin;
1935 Sema::ForRangeStatus RangeStatus =
1936 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1937 Sema::BEF_begin, BeginNameInfo,
1938 BeginMemberLookup, CandidateSet,
1939 BeginRange, BeginExpr);
1940
1941 if (RangeStatus != Sema::FRS_Success)
1942 return RangeStatus;
1943 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1944 diag::err_for_range_iter_deduction_failure)) {
1945 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1946 return Sema::FRS_DiagnosticIssued;
1947 }
1948
1949 *BEF = Sema::BEF_end;
1950 RangeStatus =
1951 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1952 Sema::BEF_end, EndNameInfo,
1953 EndMemberLookup, CandidateSet,
1954 EndRange, EndExpr);
1955 if (RangeStatus != Sema::FRS_Success)
1956 return RangeStatus;
1957 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1958 diag::err_for_range_iter_deduction_failure)) {
1959 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1960 return Sema::FRS_DiagnosticIssued;
1961 }
1962 return Sema::FRS_Success;
1963}
1964
1965/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001966/// If the attempt fails, this function will return a valid, null StmtResult
1967/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001968static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1969 SourceLocation ForLoc,
1970 Stmt *LoopVarDecl,
1971 SourceLocation ColonLoc,
1972 Expr *Range,
1973 SourceLocation RangeLoc,
1974 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001975 // Determine whether we can rebuild the for-range statement with a
1976 // dereferenced range expression.
1977 ExprResult AdjustedRange;
1978 {
1979 Sema::SFINAETrap Trap(SemaRef);
1980
1981 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1982 if (AdjustedRange.isInvalid())
1983 return StmtResult();
1984
1985 StmtResult SR =
1986 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1987 AdjustedRange.get(), RParenLoc,
1988 Sema::BFRK_Check);
1989 if (SR.isInvalid())
1990 return StmtResult();
1991 }
1992
1993 // The attempt to dereference worked well enough that it could produce a valid
1994 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1995 // case there are any other (non-fatal) problems with it.
1996 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1997 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1998 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1999 AdjustedRange.get(), RParenLoc,
2000 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00002001}
2002
Richard Smith37aa0f72013-08-21 01:40:36 +00002003namespace {
2004/// RAII object to automatically invalidate a declaration if an error occurs.
2005struct InvalidateOnErrorScope {
2006 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2007 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2008 ~InvalidateOnErrorScope() {
2009 if (Enabled && Trap.hasErrorOccurred())
2010 D->setInvalidDecl();
2011 }
2012
2013 DiagnosticErrorTrap Trap;
2014 Decl *D;
2015 bool Enabled;
2016};
2017}
2018
Richard Smith8b533d92012-09-20 21:52:32 +00002019/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00002020StmtResult
2021Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2022 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2023 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00002024 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00002025 Scope *S = getCurScope();
2026
2027 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2028 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2029 QualType RangeVarType = RangeVar->getType();
2030
2031 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2032 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2033
Richard Smith37aa0f72013-08-21 01:40:36 +00002034 // If we hit any errors, mark the loop variable as invalid if its type
2035 // contains 'auto'.
2036 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2037 LoopVar->getType()->isUndeducedType());
2038
Richard Smithad762fc2011-04-14 22:09:26 +00002039 StmtResult BeginEndDecl = BeginEnd;
2040 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2041
Richard Smithdc7a4f52013-04-30 13:56:41 +00002042 if (RangeVarType->isDependentType()) {
2043 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman86164e82013-09-05 00:02:25 +00002044 RangeVar->markUsed(Context);
Richard Smithdc7a4f52013-04-30 13:56:41 +00002045
2046 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2047 // them in properly when we instantiate the loop.
2048 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2049 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2050 } else if (!BeginEndDecl.get()) {
Richard Smithad762fc2011-04-14 22:09:26 +00002051 SourceLocation RangeLoc = RangeVar->getLocation();
2052
Ted Kremeneke50b0152011-10-10 22:36:28 +00002053 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2054
2055 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2056 VK_LValue, ColonLoc);
2057 if (BeginRangeRef.isInvalid())
2058 return StmtError();
2059
2060 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2061 VK_LValue, ColonLoc);
2062 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00002063 return StmtError();
2064
2065 QualType AutoType = Context.getAutoDeductType();
2066 Expr *Range = RangeVar->getInit();
2067 if (!Range)
2068 return StmtError();
2069 QualType RangeType = Range->getType();
2070
2071 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00002072 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00002073 return StmtError();
2074
2075 // Build auto __begin = begin-expr, __end = end-expr.
2076 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2077 "__begin");
2078 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2079 "__end");
2080
2081 // Build begin-expr and end-expr and attach to __begin and __end variables.
2082 ExprResult BeginExpr, EndExpr;
2083 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2084 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2085 // __range + __bound, respectively, where __bound is the array bound. If
2086 // _RangeT is an array of unknown size or an array of incomplete type,
2087 // the program is ill-formed;
2088
2089 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002090 BeginExpr = BeginRangeRef;
2091 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00002092 diag::err_for_range_iter_deduction_failure)) {
2093 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2094 return StmtError();
2095 }
2096
2097 // Find the array bound.
2098 ExprResult BoundExpr;
2099 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2100 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00002101 Context.getPointerDiffType(),
2102 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00002103 else if (const VariableArrayType *VAT =
2104 dyn_cast<VariableArrayType>(UnqAT))
Richard Smith39b0e262013-04-20 23:28:26 +00002105 // FIXME: Need to build an OpaqueValueExpr for this rather than
2106 // recomputing it!
Richard Smithad762fc2011-04-14 22:09:26 +00002107 BoundExpr = VAT->getSizeExpr();
2108 else {
2109 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2110 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00002111 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00002112 }
2113
2114 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002115 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00002116 BoundExpr.get());
2117 if (EndExpr.isInvalid())
2118 return StmtError();
2119 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2120 diag::err_for_range_iter_deduction_failure)) {
2121 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2122 return StmtError();
2123 }
2124 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00002125 OverloadCandidateSet CandidateSet(RangeLoc);
2126 Sema::BeginEndFunction BEFFailure;
2127 ForRangeStatus RangeStatus =
2128 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2129 EndRangeRef.get(), RangeType,
2130 BeginVar, EndVar, ColonLoc, &CandidateSet,
2131 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00002132
Sam Panzere1715b62012-08-21 00:52:01 +00002133 // If building the range failed, try dereferencing the range expression
2134 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00002135 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00002136 BEFFailure == BEF_begin) {
2137 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2138 LoopVarDecl, ColonLoc,
2139 Range, RangeLoc,
2140 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00002141 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00002142 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00002143 }
2144
Sam Panzere1715b62012-08-21 00:52:01 +00002145 // Otherwise, emit diagnostics if we haven't already.
2146 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00002147 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00002148 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2149 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00002150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00002151 }
2152 // Return an error if no fix was discovered.
2153 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00002154 return StmtError();
2155 }
2156
Sam Panzere1715b62012-08-21 00:52:01 +00002157 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2158 "invalid range expression in for loop");
2159
2160 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00002161 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2162 if (!Context.hasSameType(BeginType, EndType)) {
2163 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2164 << BeginType << EndType;
2165 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2166 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2167 }
2168
2169 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2170 // Claim the type doesn't contain auto: we've already done the checking.
2171 DeclGroupPtrTy BeginEndGroup =
Rafael Espindola4549d7f2013-07-09 12:05:01 +00002172 BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *>(BeginEndDecls, 2),
2173 /*TypeMayContainAuto=*/ false);
Richard Smithad762fc2011-04-14 22:09:26 +00002174 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2175
Ted Kremeneke50b0152011-10-10 22:36:28 +00002176 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2177 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00002178 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002179 if (BeginRef.isInvalid())
2180 return StmtError();
2181
Richard Smithad762fc2011-04-14 22:09:26 +00002182 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2183 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002184 if (EndRef.isInvalid())
2185 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00002186
2187 // Build and check __begin != __end expression.
2188 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2189 BeginRef.get(), EndRef.get());
2190 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2191 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2192 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002193 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2194 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002195 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2196 if (!Context.hasSameType(BeginType, EndType))
2197 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2198 return StmtError();
2199 }
2200
2201 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002202 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2203 VK_LValue, ColonLoc);
2204 if (BeginRef.isInvalid())
2205 return StmtError();
2206
Richard Smithad762fc2011-04-14 22:09:26 +00002207 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2208 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2209 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002210 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2211 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002212 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2213 return StmtError();
2214 }
2215
2216 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002217 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2218 VK_LValue, ColonLoc);
2219 if (BeginRef.isInvalid())
2220 return StmtError();
2221
Richard Smithad762fc2011-04-14 22:09:26 +00002222 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2223 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002224 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2225 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002226 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2227 return StmtError();
2228 }
2229
Richard Smith8b533d92012-09-20 21:52:32 +00002230 // Attach *__begin as initializer for VD. Don't touch it if we're just
2231 // trying to determine whether this would be a valid range.
2232 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002233 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2234 /*TypeMayContainAuto=*/true);
2235 if (LoopVar->isInvalidDecl())
2236 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2237 }
2238 }
2239
Richard Smith8b533d92012-09-20 21:52:32 +00002240 // Don't bother to actually allocate the result if we're just trying to
2241 // determine whether it would be valid.
2242 if (Kind == BFRK_Check)
2243 return StmtResult();
2244
Richard Smithad762fc2011-04-14 22:09:26 +00002245 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2246 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2247 NotEqExpr.take(), IncrExpr.take(),
2248 LoopVarDS, /*Body=*/0, ForLoc,
2249 ColonLoc, RParenLoc));
2250}
2251
Chad Rosier1093f492012-08-10 17:56:09 +00002252/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002253/// statement.
2254StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2255 if (!S || !B)
2256 return StmtError();
2257 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002258
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002259 ForStmt->setBody(B);
2260 return S;
2261}
2262
Richard Smithad762fc2011-04-14 22:09:26 +00002263/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2264/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2265/// body cannot be performed until after the type of the range variable is
2266/// determined.
2267StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2268 if (!S || !B)
2269 return StmtError();
2270
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002271 if (isa<ObjCForCollectionStmt>(S))
2272 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002273
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002274 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2275 ForStmt->setBody(B);
2276
2277 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2278 diag::warn_empty_range_based_for_body);
2279
Richard Smithad762fc2011-04-14 22:09:26 +00002280 return S;
2281}
2282
Chris Lattner57ad3782011-02-17 20:34:02 +00002283StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2284 SourceLocation LabelLoc,
2285 LabelDecl *TheDecl) {
2286 getCurFunction()->setHasBranchIntoScope();
Eli Friedman86164e82013-09-05 00:02:25 +00002287 TheDecl->markUsed(Context);
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002288 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002289}
2290
John McCall60d7b3a2010-08-24 06:29:42 +00002291StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002292Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002293 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002294 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002295 if (!E->isTypeDependent()) {
2296 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002297 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002298 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002299 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002300 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2301 if (ExprRes.isInvalid())
2302 return StmtError();
2303 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002304 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002305 return StmtError();
2306 }
John McCallb60a77e2010-08-01 00:26:45 +00002307
Richard Smith41956372013-01-14 22:39:08 +00002308 ExprResult ExprRes = ActOnFinishFullExpr(E);
2309 if (ExprRes.isInvalid())
2310 return StmtError();
2311 E = ExprRes.take();
2312
John McCall781472f2010-08-25 08:40:02 +00002313 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002314
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002315 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002316}
2317
John McCall60d7b3a2010-08-24 06:29:42 +00002318StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002319Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 Scope *S = CurScope->getContinueParent();
2321 if (!S) {
2322 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002323 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002325
Ted Kremenek8189cde2009-02-07 01:47:29 +00002326 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002327}
2328
John McCall60d7b3a2010-08-24 06:29:42 +00002329StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002330Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 Scope *S = CurScope->getBreakParent();
2332 if (!S) {
2333 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002334 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002336
Ted Kremenek8189cde2009-02-07 01:47:29 +00002337 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002338}
2339
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002340/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002341/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002342///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002343/// \param ReturnType If we're determining the copy elision candidate for
2344/// a return statement, this is the return type of the function. If we're
2345/// determining the copy elision candidate for a throw expression, this will
2346/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002347///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002348/// \param E The expression being returned from the function or block, or
2349/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002350///
Douglas Gregor4926d832011-05-20 15:00:53 +00002351/// \param AllowFunctionParameter Whether we allow function parameters to
2352/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2353/// we re-use this logic to determine whether we should try to move as part of
2354/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002355///
2356/// \returns The NRVO candidate variable, if the return statement may use the
2357/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002358const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2359 Expr *E,
2360 bool AllowFunctionParameter) {
2361 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002362 // - in a return statement in a function with ...
2363 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002364 if (!ReturnType.isNull()) {
2365 if (!ReturnType->isRecordType())
2366 return 0;
2367 // ... the same cv-unqualified type as the function return type ...
2368 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2369 return 0;
2370 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002371
2372 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002373 // (other than a function or catch-clause parameter)) ...
2374 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002375 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002376 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002377 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2378 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002379 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002380
John McCall1cd76e82011-11-11 03:57:31 +00002381 // ...object (other than a function or catch-clause parameter)...
2382 if (VD->getKind() != Decl::Var &&
2383 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2384 return 0;
2385 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002386
John McCall1cd76e82011-11-11 03:57:31 +00002387 // ...automatic...
2388 if (!VD->hasLocalStorage()) return 0;
2389
2390 // ...non-volatile...
2391 if (VD->getType().isVolatileQualified()) return 0;
2392 if (VD->getType()->isReferenceType()) return 0;
2393
2394 // __block variables can't be allocated in a way that permits NRVO.
2395 if (VD->hasAttr<BlocksAttr>()) return 0;
2396
2397 // Variables with higher required alignment than their type's ABI
2398 // alignment cannot use NRVO.
2399 if (VD->hasAttr<AlignedAttr>() &&
2400 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2401 return 0;
2402
2403 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002404}
2405
Douglas Gregor07f402c2011-01-21 21:08:57 +00002406/// \brief Perform the initialization of a potentially-movable value, which
2407/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002408///
2409/// This routine implements C++0x [class.copy]p33, which attempts to treat
2410/// returned lvalues as rvalues in certain cases (to prefer move construction),
2411/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002412ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002413Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2414 const VarDecl *NRVOCandidate,
2415 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002416 Expr *Value,
2417 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002418 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002419 // When the criteria for elision of a copy operation are met or would
2420 // be met save for the fact that the source object is a function
2421 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002422 // overload resolution to select the constructor for the copy is first
2423 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002424 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002425 if (AllowNRVO &&
2426 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002427 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002428 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002429
Douglas Gregorcc15f012011-01-21 19:38:21 +00002430 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002431 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002432 = InitializationKind::CreateCopy(Value->getLocStart(),
2433 Value->getLocStart());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002434 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002435
2436 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002437 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002438 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002439 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002440 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002441 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2442 StepEnd = Seq.step_end();
2443 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002444 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002445 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002446
2447 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002448 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002449
Douglas Gregorcc15f012011-01-21 19:38:21 +00002450 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002451 = Constructor->getParamDecl(0)->getType()
2452 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002453
Douglas Gregorcc15f012011-01-21 19:38:21 +00002454 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002455 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002456 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2457 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002458 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002459
Douglas Gregorcc15f012011-01-21 19:38:21 +00002460 // Promote "AsRvalue" to the heap, since we now need this
2461 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002462 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002463 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002464
Douglas Gregorcc15f012011-01-21 19:38:21 +00002465 // Complete type-checking the initialization of the return type
2466 // using the constructor we found.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002467 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorcc15f012011-01-21 19:38:21 +00002468 }
2469 }
2470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
Douglas Gregorcc15f012011-01-21 19:38:21 +00002472 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002473 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002474 // (again) now with the return value expression as written.
2475 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002476 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477
Douglas Gregorcc15f012011-01-21 19:38:21 +00002478 return Res;
2479}
2480
Richard Smith41d09582013-09-25 05:02:54 +00002481/// \brief Determine whether the declared return type of the specified function
2482/// contains 'auto'.
2483static bool hasDeducedReturnType(FunctionDecl *FD) {
2484 const FunctionProtoType *FPT =
2485 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2486 return FPT->getResultType()->isUndeducedType();
2487}
2488
Eli Friedman84b007f2012-01-26 03:00:14 +00002489/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2490/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002491///
John McCall60d7b3a2010-08-24 06:29:42 +00002492StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002493Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2494 // If this is the first return we've seen, infer the return type.
Richard Smithf45c2992013-05-12 03:09:35 +00002495 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman84b007f2012-01-26 03:00:14 +00002496 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002497 QualType FnRetType = CurCap->ReturnType;
Richard Smith41d09582013-09-25 05:02:54 +00002498 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek152b4e42013-08-22 12:12:24 +00002499
Richard Smith41d09582013-09-25 05:02:54 +00002500 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2501 // In C++1y, the return type may involve 'auto'.
2502 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2503 FunctionDecl *FD = CurLambda->CallOperator;
2504 if (CurCap->ReturnType.isNull())
2505 CurCap->ReturnType = FD->getResultType();
2506
2507 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2508 assert(AT && "lost auto type from lambda return type");
2509 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2510 FD->setInvalidDecl();
2511 return StmtError();
2512 }
2513 CurCap->ReturnType = FnRetType = FD->getResultType();
2514 } else if (CurCap->HasImplicitReturnType) {
2515 // For blocks/lambdas with implicit return types, we check each return
2516 // statement individually, and deduce the common return type when the block
2517 // or lambda is completed.
2518 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregora0c2b212012-02-09 18:40:39 +00002519 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002520 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2521 if (Result.isInvalid())
2522 return StmtError();
2523 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002524
Richard Smith41d09582013-09-25 05:02:54 +00002525 if (!CurContext->isDependentContext())
Manuel Klimek152b4e42013-08-22 12:12:24 +00002526 FnRetType = RetValExp->getType();
Richard Smith41d09582013-09-25 05:02:54 +00002527 else
Jordan Rose7dd900e2012-07-02 21:19:23 +00002528 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002529 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002530 if (RetValExp) {
2531 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2532 // initializer list, because it is not an expression (even
2533 // though we represent it as one). We still deduce 'void'.
2534 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2535 << RetValExp->getSourceRange();
2536 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00002537
Jordan Rose7dd900e2012-07-02 21:19:23 +00002538 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002539 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002540
2541 // Although we'll properly infer the type of the block once it's completed,
2542 // make sure we provide a return type now for better error recovery.
2543 if (CurCap->ReturnType.isNull())
2544 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002545 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002546 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002547
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002548 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002549 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2550 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2551 return StmtError();
2552 }
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00002553 } else if (CapturedRegionScopeInfo *CurRegion =
2554 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2555 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2556 return StmtError();
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002557 } else {
Richard Smith41d09582013-09-25 05:02:54 +00002558 assert(CurLambda && "unknown kind of captured scope");
2559 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2560 ->getNoReturnAttr()) {
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002561 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2562 return StmtError();
2563 }
2564 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002565
Steve Naroff4eb206b2008-09-03 18:15:37 +00002566 // Otherwise, verify that this result type matches the previous one. We are
2567 // pickier with blocks than for normal functions because we don't have GCC
2568 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002569 const VarDecl *NRVOCandidate = 0;
Manuel Klimek152b4e42013-08-22 12:12:24 +00002570 if (FnRetType->isDependentType()) {
John McCall0a7efe12011-08-17 22:09:46 +00002571 // Delay processing for now. TODO: there are lots of dependent
2572 // types we can conclusively prove aren't void.
2573 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002574 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002575 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002576 (RetValExp->isTypeDependent() ||
2577 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002578 if (!getLangOpts().CPlusPlus &&
2579 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002580 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002581 else {
2582 Diag(ReturnLoc, diag::err_return_block_has_expr);
2583 RetValExp = 0;
2584 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002585 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002586 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002587 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2588 } else if (!RetValExp->isTypeDependent()) {
2589 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002590
John McCall0a7efe12011-08-17 22:09:46 +00002591 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2592 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2593 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002594
John McCall0a7efe12011-08-17 22:09:46 +00002595 // In C++ the return statement is handled via a copy initialization.
2596 // the C version of which boils down to CheckSingleAssignmentConstraints.
2597 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2598 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2599 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002600 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002601 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2602 FnRetType, RetValExp);
2603 if (Res.isInvalid()) {
2604 // FIXME: Cleanup temporaries here, anyway?
2605 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002606 }
John McCall0a7efe12011-08-17 22:09:46 +00002607 RetValExp = Res.take();
2608 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002609 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002610
John McCalld963c372011-08-17 21:34:14 +00002611 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002612 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2613 if (ER.isInvalid())
2614 return StmtError();
2615 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002616 }
John McCall0a7efe12011-08-17 22:09:46 +00002617 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2618 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002619
Jordan Rose7dd900e2012-07-02 21:19:23 +00002620 // If we need to check for the named return value optimization,
2621 // or if we need to infer the return type,
2622 // save the return statement in our scope for later processing.
2623 if (CurCap->HasImplicitReturnType ||
2624 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2625 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002626 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002627
Douglas Gregor5077c382010-05-15 06:01:05 +00002628 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002629}
Manuel Klimek152b4e42013-08-22 12:12:24 +00002630
Richard Smith60e141e2013-05-04 07:00:32 +00002631/// Deduce the return type for a function from a returned expression, per
2632/// C++1y [dcl.spec.auto]p6.
2633bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2634 SourceLocation ReturnLoc,
2635 Expr *&RetExpr,
2636 AutoType *AT) {
2637 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2638 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
2639 QualType Deduced;
Manuel Klimek152b4e42013-08-22 12:12:24 +00002640
Richard Smith37e849a2013-08-14 20:16:31 +00002641 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2642 // If the deduction is for a return statement and the initializer is
2643 // a braced-init-list, the program is ill-formed.
Richard Smith41d09582013-09-25 05:02:54 +00002644 Diag(RetExpr->getExprLoc(),
2645 getCurLambda() ? diag::err_lambda_return_init_list
2646 : diag::err_auto_fn_return_init_list)
2647 << RetExpr->getSourceRange();
Richard Smith37e849a2013-08-14 20:16:31 +00002648 return true;
2649 }
2650
2651 if (FD->isDependentContext()) {
2652 // C++1y [dcl.spec.auto]p12:
2653 // Return type deduction [...] occurs when the definition is
2654 // instantiated even if the function body contains a return
2655 // statement with a non-type-dependent operand.
2656 assert(AT->isDeduced() && "should have deduced to dependent type");
2657 return false;
2658 } else if (RetExpr) {
Richard Smith60e141e2013-05-04 07:00:32 +00002659 // If the deduction is for a return statement and the initializer is
2660 // a braced-init-list, the program is ill-formed.
2661 if (isa<InitListExpr>(RetExpr)) {
2662 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2663 return true;
2664 }
2665
2666 // Otherwise, [...] deduce a value for U using the rules of template
2667 // argument deduction.
2668 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2669
2670 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2671 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2672 << OrigResultType.getType() << RetExpr->getType();
2673
2674 if (DAR != DAR_Succeeded)
2675 return true;
2676 } else {
2677 // In the case of a return with no operand, the initializer is considered
2678 // to be void().
2679 //
2680 // Deduction here can only succeed if the return type is exactly 'cv auto'
2681 // or 'decltype(auto)', so just check for that case directly.
2682 if (!OrigResultType.getType()->getAs<AutoType>()) {
2683 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2684 << OrigResultType.getType();
2685 return true;
2686 }
2687 // We always deduce U = void in this case.
2688 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2689 if (Deduced.isNull())
2690 return true;
2691 }
2692
2693 // If a function with a declared return type that contains a placeholder type
2694 // has multiple return statements, the return type is deduced for each return
2695 // statement. [...] if the type deduced is not the same in each deduction,
2696 // the program is ill-formed.
2697 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2698 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smith37e849a2013-08-14 20:16:31 +00002699 if (!FD->isDependentContext() &&
2700 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith41d09582013-09-25 05:02:54 +00002701 const LambdaScopeInfo *LambdaSI = getCurLambda();
2702 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2703 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2704 << NewAT->getDeducedType() << AT->getDeducedType()
2705 << true /*IsLambda*/;
2706 } else {
2707 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2708 << (AT->isDecltypeAuto() ? 1 : 0)
2709 << NewAT->getDeducedType() << AT->getDeducedType();
2710 }
Richard Smith60e141e2013-05-04 07:00:32 +00002711 return true;
2712 }
2713 } else if (!FD->isInvalidDecl()) {
2714 // Update all declarations of the function to have the deduced return type.
2715 Context.adjustDeducedFunctionResultType(FD, Deduced);
2716 }
2717
2718 return false;
2719}
2720
John McCall60d7b3a2010-08-24 06:29:42 +00002721StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002722Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002723 // Check for unexpanded parameter packs.
2724 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2725 return StmtError();
Manuel Klimek152b4e42013-08-22 12:12:24 +00002726
Eli Friedman84b007f2012-01-26 03:00:14 +00002727 if (isa<CapturingScopeInfo>(getCurFunction()))
2728 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek152b4e42013-08-22 12:12:24 +00002729
Chris Lattner371f2582008-12-04 23:50:19 +00002730 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002731 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002732 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002733 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002734 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002735 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002736 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002737 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002738 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002739 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2740 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002741 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002742 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002743 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2744 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002745 }
2746 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002747 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Richard Smith60e141e2013-05-04 07:00:32 +00002749 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2750 // deduction.
Richard Smith60e141e2013-05-04 07:00:32 +00002751 if (getLangOpts().CPlusPlus1y) {
2752 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2753 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smith37e849a2013-08-14 20:16:31 +00002754 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith60e141e2013-05-04 07:00:32 +00002755 FD->setInvalidDecl();
2756 return StmtError();
2757 } else {
2758 FnRetType = FD->getResultType();
2759 }
2760 }
2761 }
2762
Richard Smith37e849a2013-08-14 20:16:31 +00002763 bool HasDependentReturnType = FnRetType->isDependentType();
2764
Douglas Gregor5077c382010-05-15 06:01:05 +00002765 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002766 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002767 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002768 if (isa<InitListExpr>(RetValExp)) {
2769 // We simply never allow init lists as the return value of void
2770 // functions. This is compatible because this was never allowed before,
2771 // so there's no legacy code to deal with.
2772 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2773 int FunctionKind = 0;
2774 if (isa<ObjCMethodDecl>(CurDecl))
2775 FunctionKind = 1;
2776 else if (isa<CXXConstructorDecl>(CurDecl))
2777 FunctionKind = 2;
2778 else if (isa<CXXDestructorDecl>(CurDecl))
2779 FunctionKind = 3;
2780
2781 Diag(ReturnLoc, diag::err_return_init_list)
2782 << CurDecl->getDeclName() << FunctionKind
2783 << RetValExp->getSourceRange();
2784
2785 // Drop the expression.
2786 RetValExp = 0;
2787 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002788 // C99 6.8.6.4p1 (ext_ since GCC warns)
2789 unsigned D = diag::ext_return_has_expr;
2790 if (RetValExp->getType()->isVoidType())
2791 D = diag::ext_return_has_void_expr;
2792 else {
2793 ExprResult Result = Owned(RetValExp);
2794 Result = IgnoredValueConversions(Result.take());
2795 if (Result.isInvalid())
2796 return StmtError();
2797 RetValExp = Result.take();
2798 RetValExp = ImpCastExprToType(RetValExp,
2799 Context.VoidTy, CK_ToVoid).take();
2800 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002801
Nick Lewycky8d794612011-06-01 07:44:31 +00002802 // return (some void expression); is legal in C++.
2803 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002804 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002805 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002806
2807 int FunctionKind = 0;
2808 if (isa<ObjCMethodDecl>(CurDecl))
2809 FunctionKind = 1;
2810 else if (isa<CXXConstructorDecl>(CurDecl))
2811 FunctionKind = 2;
2812 else if (isa<CXXDestructorDecl>(CurDecl))
2813 FunctionKind = 3;
2814
Nick Lewycky8d794612011-06-01 07:44:31 +00002815 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002816 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002817 << RetValExp->getSourceRange();
2818 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002819 }
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Sebastian Redl33deb352012-02-22 10:50:08 +00002821 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002822 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2823 if (ER.isInvalid())
2824 return StmtError();
2825 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002826 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002828
Douglas Gregor5077c382010-05-15 06:01:05 +00002829 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
Richard Smith60e141e2013-05-04 07:00:32 +00002830 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002831 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2832 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002833 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002834
2835 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002836 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002837 else
Chris Lattner08631c52008-11-23 21:45:46 +00002838 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002839 Result = new (Context) ReturnStmt(ReturnLoc);
2840 } else {
Richard Smith60e141e2013-05-04 07:00:32 +00002841 assert(RetValExp || HasDependentReturnType);
Douglas Gregor5077c382010-05-15 06:01:05 +00002842 const VarDecl *NRVOCandidate = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00002843 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor5077c382010-05-15 06:01:05 +00002844 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002845
John McCall7cca8212013-03-19 07:04:25 +00002846 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
Eli Friedman38ac2432012-03-30 01:13:43 +00002847
Douglas Gregor5077c382010-05-15 06:01:05 +00002848 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2849 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2850 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002851
John McCall856d3792011-06-16 23:24:51 +00002852 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002853 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002854 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002855 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall7cca8212013-03-19 07:04:25 +00002856 RetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002857 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall7cca8212013-03-19 07:04:25 +00002859 RetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002860 if (Res.isInvalid()) {
John McCall7cca8212013-03-19 07:04:25 +00002861 // FIXME: Clean up temporaries here anyway?
Douglas Gregor5077c382010-05-15 06:01:05 +00002862 return StmtError();
2863 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002864 RetValExp = Res.takeAs<Expr>();
John McCall7cca8212013-03-19 07:04:25 +00002865
2866 // If we have a related result type, we need to implicitly
2867 // convert back to the formal result type. We can't pretend to
2868 // initialize the result again --- we might end double-retaining
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002869 // --- so instead we initialize a notional temporary.
John McCall7cca8212013-03-19 07:04:25 +00002870 if (!RelatedRetType.isNull()) {
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002871 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
2872 FnRetType);
John McCall7cca8212013-03-19 07:04:25 +00002873 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2874 if (Res.isInvalid()) {
2875 // FIXME: Clean up temporaries here anyway?
2876 return StmtError();
2877 }
2878 RetValExp = Res.takeAs<Expr>();
2879 }
2880
2881 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002882 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883
John McCallb4eb64d2010-10-08 02:01:28 +00002884 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002885 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2886 if (ER.isInvalid())
2887 return StmtError();
2888 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002889 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002890 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002891 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892
2893 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002894 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002895 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002896 !CurContext->isDependentContext())
2897 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002898
Douglas Gregor5077c382010-05-15 06:01:05 +00002899 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002900}
2901
John McCall60d7b3a2010-08-24 06:29:42 +00002902StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002903Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002904 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002905 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002906 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002907 if (Var && Var->isInvalidDecl())
2908 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002909
John McCall9ae2f072010-08-23 23:25:46 +00002910 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002911}
2912
John McCall60d7b3a2010-08-24 06:29:42 +00002913StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002914Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2915 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002916}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002917
John McCall60d7b3a2010-08-24 06:29:42 +00002918StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002920 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002921 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002922 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2923
John McCall781472f2010-08-25 08:40:02 +00002924 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002925 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002926 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002927 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002928 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002929 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002930}
2931
John McCalld1376ee2012-05-08 21:41:25 +00002932StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002933 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002934 ExprResult Result = DefaultLvalueConversion(Throw);
2935 if (Result.isInvalid())
2936 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002937
Richard Smith41956372013-01-14 22:39:08 +00002938 Result = ActOnFinishFullExpr(Result.take());
2939 if (Result.isInvalid())
2940 return StmtError();
2941 Throw = Result.take();
2942
Douglas Gregord1377b22010-04-22 21:44:01 +00002943 QualType ThrowType = Throw->getType();
2944 // Make sure the expression type is an ObjC pointer or "void *".
2945 if (!ThrowType->isDependentType() &&
2946 !ThrowType->isObjCObjectPointerType()) {
2947 const PointerType *PT = ThrowType->getAs<PointerType>();
2948 if (!PT || !PT->getPointeeType()->isVoidType())
2949 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2950 << Throw->getType() << Throw->getSourceRange());
2951 }
2952 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002953
John McCall9ae2f072010-08-23 23:25:46 +00002954 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002955}
2956
John McCall60d7b3a2010-08-24 06:29:42 +00002957StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002959 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002960 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002961 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2962
John McCall9ae2f072010-08-23 23:25:46 +00002963 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002964 // @throw without an expression designates a rethrow (which much occur
2965 // in the context of an @catch clause).
2966 Scope *AtCatchParent = CurScope;
2967 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2968 AtCatchParent = AtCatchParent->getParent();
2969 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002970 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002971 }
John McCall9ae2f072010-08-23 23:25:46 +00002972 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002973}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002974
John McCall07524032011-07-27 21:50:02 +00002975ExprResult
2976Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2977 ExprResult result = DefaultLvalueConversion(operand);
2978 if (result.isInvalid())
2979 return ExprError();
2980 operand = result.take();
2981
2982 // Make sure the expression type is an ObjC pointer or "void *".
2983 QualType type = operand->getType();
2984 if (!type->isDependentType() &&
2985 !type->isObjCObjectPointerType()) {
2986 const PointerType *pointerType = type->getAs<PointerType>();
2987 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2988 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2989 << type << operand->getSourceRange();
2990 }
2991
2992 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002993 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002994}
2995
John McCall60d7b3a2010-08-24 06:29:42 +00002996StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002997Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2998 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002999 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00003000 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00003001 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00003002}
Sebastian Redl4b07b292008-12-22 19:15:10 +00003003
3004/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3005/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00003006StmtResult
John McCalld226f652010-08-21 09:40:31 +00003007Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00003008 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003009 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003010 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00003011 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00003012 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003013}
Sebastian Redl8351da02008-12-22 21:35:02 +00003014
John McCallf85e1932011-06-15 23:02:42 +00003015StmtResult
3016Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3017 getCurFunction()->setHasBranchProtectedScope();
3018 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3019}
3020
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003021namespace {
3022
Sebastian Redlc447aba2009-07-29 17:15:45 +00003023class TypeWithHandler {
3024 QualType t;
3025 CXXCatchStmt *stmt;
3026public:
3027 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3028 : t(type), stmt(statement) {}
3029
John McCall0953e762009-09-24 19:53:00 +00003030 // An arbitrary order is fine as long as it places identical
3031 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00003032 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00003033 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003034 return true;
John McCall0953e762009-09-24 19:53:00 +00003035 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003036 return false;
3037 else
3038 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3039 }
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Sebastian Redlc447aba2009-07-29 17:15:45 +00003041 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00003042 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00003043 }
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Sebastian Redlc447aba2009-07-29 17:15:45 +00003045 CXXCatchStmt *getCatchStmt() const { return stmt; }
3046 SourceLocation getTypeSpecStartLoc() const {
3047 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3048 }
3049};
3050
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003051}
3052
Sebastian Redl8351da02008-12-22 21:35:02 +00003053/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3054/// handlers and creates a try statement from them.
Robert Wilhelm21adb0c2013-08-22 09:20:03 +00003055StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3056 ArrayRef<Stmt *> Handlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00003057 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00003058 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00003059 !getSourceManager().isInSystemHeader(TryLoc))
3060 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00003061
Robert Wilhelm21adb0c2013-08-22 09:20:03 +00003062 const unsigned NumHandlers = Handlers.size();
Sebastian Redl8351da02008-12-22 21:35:02 +00003063 assert(NumHandlers > 0 &&
3064 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl8351da02008-12-22 21:35:02 +00003065
Chris Lattner5f9e2722011-07-23 10:55:15 +00003066 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00003067
3068 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003069 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00003070 if (!Handler->getExceptionDecl()) {
3071 if (i < NumHandlers - 1)
3072 return StmtError(Diag(Handler->getLocStart(),
3073 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Sebastian Redlc447aba2009-07-29 17:15:45 +00003075 continue;
3076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Sebastian Redlc447aba2009-07-29 17:15:45 +00003078 const QualType CaughtType = Handler->getCaughtType();
3079 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3080 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00003081 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00003082
3083 // Detect handlers for the same type as an earlier one.
3084 if (NumHandlers > 1) {
3085 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Sebastian Redlc447aba2009-07-29 17:15:45 +00003087 TypeWithHandler prev = TypesWithHandlers[0];
3088 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3089 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00003090
Sebastian Redlc447aba2009-07-29 17:15:45 +00003091 if (curr == prev) {
3092 Diag(curr.getTypeSpecStartLoc(),
3093 diag::warn_exception_caught_by_earlier_handler)
3094 << curr.getCatchStmt()->getCaughtType().getAsString();
3095 Diag(prev.getTypeSpecStartLoc(),
3096 diag::note_previous_exception_handler)
3097 << prev.getCatchStmt()->getCaughtType().getAsString();
3098 }
Mike Stump1eb44332009-09-09 15:08:12 +00003099
Sebastian Redlc447aba2009-07-29 17:15:45 +00003100 prev = curr;
3101 }
3102 }
Mike Stump1eb44332009-09-09 15:08:12 +00003103
John McCall781472f2010-08-25 08:40:02 +00003104 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00003105
Sebastian Redl8351da02008-12-22 21:35:02 +00003106 // FIXME: We should detect handlers that cannot catch anything because an
3107 // earlier handler catches a superclass. Need to find a method that is not
3108 // quadratic for this.
3109 // Neither of these are explicitly forbidden, but every compiler detects them
3110 // and warns.
3111
Robert Wilhelm21adb0c2013-08-22 09:20:03 +00003112 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00003113}
John Wiegley28bbe4b2011-04-28 01:08:34 +00003114
3115StmtResult
3116Sema::ActOnSEHTryBlock(bool IsCXXTry,
3117 SourceLocation TryLoc,
3118 Stmt *TryBlock,
3119 Stmt *Handler) {
3120 assert(TryBlock && Handler);
3121
3122 getCurFunction()->setHasBranchProtectedScope();
3123
3124 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3125}
3126
3127StmtResult
3128Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3129 Expr *FilterExpr,
3130 Stmt *Block) {
3131 assert(FilterExpr && Block);
3132
3133 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00003134 return StmtError(Diag(FilterExpr->getExprLoc(),
3135 diag::err_filter_expression_integral)
3136 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00003137 }
3138
3139 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3140}
3141
3142StmtResult
3143Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3144 Stmt *Block) {
3145 assert(Block);
3146 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3147}
Douglas Gregorba0513d2011-10-25 01:33:02 +00003148
3149StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3150 bool IsIfExists,
3151 NestedNameSpecifierLoc QualifierLoc,
3152 DeclarationNameInfo NameInfo,
3153 Stmt *Nested)
3154{
3155 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003156 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003157 cast<CompoundStmt>(Nested));
3158}
3159
3160
Chad Rosier1093f492012-08-10 17:56:09 +00003161StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003162 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00003163 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003164 UnqualifiedId &Name,
3165 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00003166 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00003167 SS.getWithLocInContext(Context),
3168 GetNameFromUnqualifiedId(Name),
3169 Nested);
3170}
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003171
3172RecordDecl*
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003173Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3174 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003175 DeclContext *DC = CurContext;
3176 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3177 DC = DC->getParent();
3178
3179 RecordDecl *RD = 0;
3180 if (getLangOpts().CPlusPlus)
3181 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3182 else
3183 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3184
3185 DC->addDecl(RD);
3186 RD->setImplicit();
3187 RD->startDefinition();
3188
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003189 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003190 DC->addDecl(CD);
3191
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003192 // Build the context parameter
3193 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3194 DC = CapturedDecl::castToDeclContext(CD);
3195 IdentifierInfo *VarName = &Context.Idents.get("__context");
3196 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3197 ImplicitParamDecl *Param
3198 = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
3199 DC->addDecl(Param);
3200
3201 CD->setContextParam(Param);
3202
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003203 return RD;
3204}
3205
3206static void buildCapturedStmtCaptureList(
3207 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3208 SmallVectorImpl<Expr *> &CaptureInits,
3209 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3210
3211 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3212 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3213
3214 if (Cap->isThisCapture()) {
3215 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3216 CapturedStmt::VCK_This));
Richard Smith0d8e9642013-05-16 06:20:58 +00003217 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003218 continue;
3219 }
3220
3221 assert(Cap->isReferenceCapture() &&
3222 "non-reference capture not yet implemented");
3223
3224 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3225 CapturedStmt::VCK_ByRef,
3226 Cap->getVariable()));
Richard Smith0d8e9642013-05-16 06:20:58 +00003227 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003228 }
3229}
3230
3231void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003232 CapturedRegionKind Kind,
3233 unsigned NumParams) {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003234 CapturedDecl *CD = 0;
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003235 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003236
3237 // Enter the capturing scope for this captured region.
3238 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3239
3240 if (CurScope)
3241 PushDeclContext(CurScope, CD);
3242 else
3243 CurContext = CD;
3244
3245 PushExpressionEvaluationContext(PotentiallyEvaluated);
3246}
3247
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003248void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003249 DiscardCleanupsInEvaluationContext();
3250 PopExpressionEvaluationContext();
3251
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003252 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3253 RecordDecl *Record = RSI->TheRecordDecl;
3254 Record->setInvalidDecl();
3255
3256 SmallVector<Decl*, 4> Fields;
3257 for (RecordDecl::field_iterator I = Record->field_begin(),
3258 E = Record->field_end(); I != E; ++I)
3259 Fields.push_back(*I);
3260 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3261 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3262
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003263 PopDeclContext();
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003264 PopFunctionScopeInfo();
3265}
3266
3267StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3268 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3269
3270 SmallVector<CapturedStmt::Capture, 4> Captures;
3271 SmallVector<Expr *, 4> CaptureInits;
3272 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3273
3274 CapturedDecl *CD = RSI->TheCapturedDecl;
3275 RecordDecl *RD = RSI->TheRecordDecl;
3276
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003277 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3278 RSI->CapRegionKind, Captures,
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003279 CaptureInits, CD, RD);
3280
3281 CD->setBody(Res->getCapturedStmt());
3282 RD->completeDefinition();
3283
Wei Pan9fd6b8f2013-05-04 03:59:06 +00003284 DiscardCleanupsInEvaluationContext();
3285 PopExpressionEvaluationContext();
3286
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003287 PopDeclContext();
3288 PopFunctionScopeInfo();
3289
3290 return Owned(Res);
3291}