blob: a2daa18d45b290bc46dfbe78955c27de0ee89a29 [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"
Anders Carlsson6fa90862007-11-25 00:25:21 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000038
Richard Smith41956372013-01-14 22:39:08 +000039StmtResult Sema::ActOnExprStmt(ExprResult FE) {
40 if (FE.isInvalid())
41 return StmtError();
42
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
45 if (FE.isInvalid())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000046 return StmtError();
47
Chris Lattner834a72a2008-07-25 23:18:17 +000048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000051
Chris Lattner834a72a2008-07-25 23:18:17 +000052 // Same thing in for stmt first clause (when expr) and third clause.
Richard Smith41956372013-01-14 22:39:08 +000053 return Owned(static_cast<Stmt*>(FE.take()));
Reid Spencer5f016e22007-07-11 17:01:13 +000054}
55
56
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000057StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000058 bool HasLeadingEmptyMacro) {
59 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000060}
61
Chris Lattner337e5502011-02-18 01:27:55 +000062StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
63 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000064 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner20401692009-04-12 20:13:14 +000066 // If we have an invalid decl, just return an error.
67 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000068
Chris Lattner24e1e702009-03-04 04:23:07 +000069 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000070}
71
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000072void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
73 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000074
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000075 // If we have an invalid decl, just return.
76 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000077 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
78
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000079 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000080 var->setUsed();
81
John McCall7acddac2011-06-17 06:42:21 +000082 // foreach variables are never actually initialized in the way that
83 // the parser came up with.
84 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000085
John McCall7acddac2011-06-17 06:42:21 +000086 // In ARC, we don't need to retain the iteration variable of a fast
87 // enumeration loop. Rather than actually trying to catch that
88 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000089 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000090 QualType type = var->getType();
91
92 // Only do this if we inferred the lifetime. Inferred lifetime
93 // will show up as a local qualifier because explicit lifetime
94 // should have shown up as an AttributedType instead.
95 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
96 // Add 'const' and mark the variable as pseudo-strong.
97 var->setType(type.withConst());
98 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000099 }
100 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +0000101}
102
Chandler Carruthec8058f2011-08-17 09:34:37 +0000103/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000104///
105/// Adding a cast to void (or other expression wrappers) will prevent the
106/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000107static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000108 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000109 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110
111 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
112 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000113 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000114
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000115 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000116 IsNotEqual = Op->getOpcode() == BO_NE;
117 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
119 if (Op->getOperator() != OO_EqualEqual &&
120 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000121 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000123 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000124 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
125 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000126 } else {
127 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000128 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000129 }
130
131 // Suppress warnings when the operator, suspicious as it may be, comes from
132 // a macro expansion.
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +0000133 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthec8058f2011-08-17 09:34:37 +0000134 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000135
Chandler Carruthec8058f2011-08-17 09:34:37 +0000136 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000137 << (unsigned)IsNotEqual << E->getSourceRange();
138
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000139 // If the LHS is a plausible entity to assign to, provide a fixit hint to
140 // correct common typos.
141 if (CanAssign) {
142 if (IsNotEqual)
143 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
144 << FixItHint::CreateReplacement(Loc, "|=");
145 else
146 S.Diag(Loc, diag::note_equality_comparison_to_assign)
147 << FixItHint::CreateReplacement(Loc, "=");
148 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000149
150 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000151}
152
Anders Carlsson636463e2009-07-30 22:17:18 +0000153void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000154 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
155 return DiagnoseUnusedExprResult(Label->getSubStmt());
156
Anders Carlsson75443112009-07-30 22:39:03 +0000157 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000158 if (!E)
159 return;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000160 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
161 if (SourceMgr.isInSystemMacro(ExprLoc) ||
162 SourceMgr.isMacroBodyExpansion(ExprLoc))
163 return;
Anders Carlsson636463e2009-07-30 22:17:18 +0000164
Eli Friedmana6115062012-05-24 00:47:05 +0000165 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000166 SourceLocation Loc;
167 SourceRange R1, R2;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000168 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000169 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Chris Lattner06b3a062012-08-31 22:39:21 +0000171 // If this is a GNU statement expression expanded from a macro, it is probably
172 // unused because it is a function-like macro that can be used as either an
173 // expression or statement. Don't warn, because it is almost certainly a
174 // false positive.
175 if (isa<StmtExpr>(E) && Loc.isMacroID())
176 return;
177
Chris Lattner419cfb32009-08-16 16:57:27 +0000178 // Okay, we have an unused result. Depending on what the base expression is,
179 // we might want to make a more specific diagnostic. Check for one of these
180 // cases now.
181 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000182 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000183 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000184 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
185 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000186
Chandler Carruthec8058f2011-08-17 09:34:37 +0000187 if (DiagnoseUnusedComparison(*this, E))
188 return;
189
Eli Friedmana6115062012-05-24 00:47:05 +0000190 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000191 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000192 if (E->getType()->isVoidType())
193 return;
194
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000195 // If the callee has attribute pure, const, or warn_unused_result, warn with
196 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000197 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000198 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000199 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000200 return;
201 }
202 if (FD->getAttr<PureAttr>()) {
203 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
204 return;
205 }
206 if (FD->getAttr<ConstAttr>()) {
207 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
208 return;
209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000210 }
John McCall12f78a62010-12-02 01:19:52 +0000211 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000212 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000213 Diag(Loc, diag::err_arc_unused_init_message) << R1;
214 return;
215 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000216 const ObjCMethodDecl *MD = ME->getMethodDecl();
217 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000218 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000219 return;
220 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000221 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
222 const Expr *Source = POE->getSyntacticForm();
223 if (isa<ObjCSubscriptRefExpr>(Source))
224 DiagID = diag::warn_unused_container_subscript_expr;
225 else
226 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000227 } else if (const CXXFunctionalCastExpr *FC
228 = dyn_cast<CXXFunctionalCastExpr>(E)) {
229 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
230 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
231 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000232 }
John McCall209acbd2010-04-06 22:24:14 +0000233 // Diagnose "(void*) blah" as a typo for "(void) blah".
234 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
235 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
236 QualType T = TI->getType();
237
238 // We really do want to use the non-canonical type here.
239 if (T == Context.VoidPtrTy) {
240 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
241
242 Diag(Loc, diag::warn_unused_voidptr)
243 << FixItHint::CreateRemoval(TL.getStarLoc());
244 return;
245 }
246 }
247
Eli Friedmana6115062012-05-24 00:47:05 +0000248 if (E->isGLValue() && E->getType().isVolatileQualified()) {
249 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
250 return;
251 }
252
Ted Kremenek351ba912011-02-23 01:52:04 +0000253 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000254}
255
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000256void Sema::ActOnStartOfCompoundStmt() {
257 PushCompoundScope();
258}
259
260void Sema::ActOnFinishOfCompoundStmt() {
261 PopCompoundScope();
262}
263
264sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
265 return getCurFunction()->CompoundScopes.back();
266}
267
John McCall60d7b3a2010-08-24 06:29:42 +0000268StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000269Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000270 MultiStmtArg elts, bool isStmtExpr) {
271 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000272 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000273 // If we're in C89 mode, check that we don't have any decls after stmts. If
274 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000275 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000276 // Note that __extension__ can be around a decl.
277 unsigned i = 0;
278 // Skip over all declarations.
279 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
280 /*empty*/;
281
282 // We found the end of the list or a statement. Scan for another declstmt.
283 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
284 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000286 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000287 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000288 Diag(D->getLocation(), diag::ext_mixed_decls_code);
289 }
290 }
Chris Lattner98414c12007-08-31 21:49:55 +0000291 // Warn about unused expressions in statements.
292 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000293 // Ignore statements that are last in a statement expression.
294 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000295 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Anders Carlsson636463e2009-07-30 22:17:18 +0000297 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000298 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000299
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000300 // Check for suspicious empty body (null statement) in `for' and `while'
301 // statements. Don't do anything for template instantiations, this just adds
302 // noise.
303 if (NumElts != 0 && !CurrentInstantiationScope &&
304 getCurCompoundScope().HasEmptyLoopBodies) {
305 for (unsigned i = 0; i != NumElts - 1; ++i)
306 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
307 }
308
Nico Weberd36aa352012-12-29 20:03:39 +0000309 return Owned(new (Context) CompoundStmt(Context,
310 llvm::makeArrayRef(Elts, NumElts),
311 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000312}
313
John McCall60d7b3a2010-08-24 06:29:42 +0000314StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000315Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
316 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000317 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000318 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000319
John McCall781472f2010-08-25 08:40:02 +0000320 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000321 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000322 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000323 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000324
Richard Smith80ad52f2013-01-02 11:42:31 +0000325 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000326 // C99 6.8.4.2p3: The expression shall be an integer constant.
327 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000328 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
329 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
330 if (!LHSVal)
331 return StmtError();
332 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000333
334 // GCC extension: The expression shall be an integer constant.
335
Richard Smith282e7e62012-02-04 09:53:13 +0000336 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
337 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
338 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000339 }
340 }
341
Douglas Gregordbb26db2009-05-15 23:57:33 +0000342 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
343 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000344 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000345 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000346}
347
Chris Lattner24e1e702009-03-04 04:23:07 +0000348/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000349void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000350 DiagnoseUnusedExprResult(SubStmt);
351
Chris Lattner24e1e702009-03-04 04:23:07 +0000352 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000353 CS->setSubStmt(SubStmt);
354}
355
John McCall60d7b3a2010-08-24 06:29:42 +0000356StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000357Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000358 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000359 DiagnoseUnusedExprResult(SubStmt);
360
John McCall781472f2010-08-25 08:40:02 +0000361 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000362 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000363 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000364 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000365
Douglas Gregordbb26db2009-05-15 23:57:33 +0000366 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000367 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000368 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369}
370
John McCall60d7b3a2010-08-24 06:29:42 +0000371StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000372Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
373 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000374 // If the label was multiply defined, reject it now.
375 if (TheDecl->getStmt()) {
376 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
377 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000378 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 }
Sebastian Redlde307472009-01-11 00:38:46 +0000380
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000381 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000382 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
383 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000384 if (!TheDecl->isGnuLocal()) {
385 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000386 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000387 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000388 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Richard Smith534986f2012-04-14 00:33:13 +0000391StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000392 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000393 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000394 // Fill in the declaration and return it.
395 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000396 return Owned(LS);
397}
398
John McCall60d7b3a2010-08-24 06:29:42 +0000399StmtResult
John McCalld226f652010-08-21 09:40:31 +0000400Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000401 Stmt *thenStmt, SourceLocation ElseLoc,
402 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000403 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000405 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000406 if (CondVar) {
407 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000408 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000409 if (CondResult.isInvalid())
410 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000411 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000412 Expr *ConditionExpr = CondResult.takeAs<Expr>();
413 if (!ConditionExpr)
414 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000415
Anders Carlsson75443112009-07-30 22:39:03 +0000416 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000417
John McCall9ae2f072010-08-23 23:25:46 +0000418 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000419 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
420 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000421 }
422
Anders Carlsson75443112009-07-30 22:39:03 +0000423 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000425 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000426 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000427}
428
Chris Lattnerf4021e72007-08-23 05:46:52 +0000429/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
430/// the specified width and sign. If an overflow occurs, detect it and emit
431/// the specified diagnostic.
432void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
433 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000434 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000435 unsigned DiagID) {
436 // Perform a conversion to the promoted condition type if needed.
437 if (NewWidth > Val.getBitWidth()) {
438 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000439 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000440 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000441
442 // If the input was signed and negative and the output is
443 // unsigned, don't bother to warn: this is implementation-defined
444 // behavior.
445 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000446 } else if (NewWidth < Val.getBitWidth()) {
447 // If this is a truncation, check for overflow.
448 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000449 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000450 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000451 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000452 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000453 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000454 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Chris Lattnerf4021e72007-08-23 05:46:52 +0000456 // Regardless of whether a diagnostic was emitted, really do the
457 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000458 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000459 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000460 } else if (NewSign != Val.isSigned()) {
461 // Convert the sign to match the sign of the condition. This can cause
462 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000464 // behavior.
465 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000466 llvm::APSInt OldVal(Val);
467 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000468 }
469}
470
Chris Lattner0471f5b2007-08-23 18:29:20 +0000471namespace {
472 struct CaseCompareFunctor {
473 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
474 const llvm::APSInt &RHS) {
475 return LHS.first < RHS;
476 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000477 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
478 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
479 return LHS.first < RHS.first;
480 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000481 bool operator()(const llvm::APSInt &LHS,
482 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
483 return LHS < RHS.first;
484 }
485 };
486}
487
Chris Lattner764a7ce2007-09-21 18:15:22 +0000488/// CmpCaseVals - Comparison predicate for sorting case values.
489///
490static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
491 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
492 if (lhs.first < rhs.first)
493 return true;
494
495 if (lhs.first == rhs.first &&
496 lhs.second->getCaseLoc().getRawEncoding()
497 < rhs.second->getCaseLoc().getRawEncoding())
498 return true;
499 return false;
500}
501
Douglas Gregorba915af2010-02-08 22:24:16 +0000502/// CmpEnumVals - Comparison predicate for sorting enumeration values.
503///
504static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
505 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
506{
507 return lhs.first < rhs.first;
508}
509
510/// EqEnumVals - Comparison preficate for uniqing enumeration values.
511///
512static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
513 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
514{
515 return lhs.first == rhs.first;
516}
517
Chris Lattner5f048812009-10-16 16:45:22 +0000518/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
519/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000520static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
521 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
522 expr = cleanups->getSubExpr();
523 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
524 if (impcast->getCastKind() != CK_IntegralCast) break;
525 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000526 }
527 return expr->getType();
528}
529
John McCall60d7b3a2010-08-24 06:29:42 +0000530StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000531Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000532 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000533 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000534
Douglas Gregor586596f2010-05-06 17:25:47 +0000535 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000536 if (CondVar) {
537 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000538 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
539 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000540 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541
John McCall9ae2f072010-08-23 23:25:46 +0000542 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
John McCall9ae2f072010-08-23 23:25:46 +0000545 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000546 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000547
Douglas Gregorab41fe92012-05-04 22:38:52 +0000548 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
549 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000550
Douglas Gregorab41fe92012-05-04 22:38:52 +0000551 public:
552 SwitchConvertDiagnoser(Expr *Cond)
553 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000554
Douglas Gregorab41fe92012-05-04 22:38:52 +0000555 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
556 QualType T) {
557 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
558 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000559
Douglas Gregorab41fe92012-05-04 22:38:52 +0000560 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
561 QualType T) {
562 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
563 << T << Cond->getSourceRange();
564 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000565
Douglas Gregorab41fe92012-05-04 22:38:52 +0000566 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
567 QualType T,
568 QualType ConvTy) {
569 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
570 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000571
Douglas Gregorab41fe92012-05-04 22:38:52 +0000572 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
573 QualType ConvTy) {
574 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
575 << ConvTy->isEnumeralType() << ConvTy;
576 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000577
Douglas Gregorab41fe92012-05-04 22:38:52 +0000578 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
579 QualType T) {
580 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
581 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000582
Douglas Gregorab41fe92012-05-04 22:38:52 +0000583 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
584 QualType ConvTy) {
585 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
586 << ConvTy->isEnumeralType() << ConvTy;
587 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000588
Douglas Gregorab41fe92012-05-04 22:38:52 +0000589 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
590 QualType T,
591 QualType ConvTy) {
592 return DiagnosticBuilder::getEmpty();
593 }
594 } SwitchDiagnoser(Cond);
595
John McCall9ae2f072010-08-23 23:25:46 +0000596 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000597 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000598 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000599 if (CondResult.isInvalid()) return StmtError();
600 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
John McCalla8e0cd82011-08-06 07:30:58 +0000602 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
603 CondResult = UsualUnaryConversions(Cond);
604 if (CondResult.isInvalid()) return StmtError();
605 Cond = CondResult.take();
606
John McCalld226f652010-08-21 09:40:31 +0000607 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000608 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000609 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000610 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000611 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000612 }
John McCallb60a77e2010-08-01 00:26:45 +0000613
John McCall781472f2010-08-25 08:40:02 +0000614 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615
John McCall9ae2f072010-08-23 23:25:46 +0000616 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000617 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000618 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000619}
620
Gabor Greif28164ab2010-10-01 22:05:14 +0000621static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
622 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000623 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000624 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000625 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000626 Val.setIsSigned(IsSigned);
627}
628
John McCall60d7b3a2010-08-24 06:29:42 +0000629StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000630Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
631 Stmt *BodyStmt) {
632 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000633 assert(SS == getCurFunction()->SwitchStack.back() &&
634 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000635
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000636 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000637 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000638
Chris Lattnerf4021e72007-08-23 05:46:52 +0000639 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000640 if (!CondExpr) return StmtError();
641
642 QualType CondType = CondExpr->getType();
643
John McCall0fb97082010-05-18 03:19:21 +0000644 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000645 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000646 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000647
Chris Lattner5f048812009-10-16 16:45:22 +0000648 // C++ 6.4.2.p2:
649 // Integral promotions are performed (on the switch condition).
650 //
651 // A case value unrepresentable by the original switch condition
652 // type (before the promotion) doesn't make sense, even when it can
653 // be represented by the promoted type. Therefore we need to find
654 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000655 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000656 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000658 // appropriate type now, just return an error.
659 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000660 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000661
Chris Lattner2b334bb2010-04-16 23:34:13 +0000662 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000663 // switch(bool_expr) {...} is often a programmer error, e.g.
664 // switch(n && mask) { ... } // Doh - should be "n & mask".
665 // One can always use an if statement instead of switch(bool_expr).
666 Diag(SwitchLoc, diag::warn_bool_switch_condition)
667 << CondExpr->getSourceRange();
668 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000669 }
Sebastian Redlde307472009-01-11 00:38:46 +0000670
Chris Lattnerf4021e72007-08-23 05:46:52 +0000671 // Get the bitwidth of the switched-on value before promotions. We must
672 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000673 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000674 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000675 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000676 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000677 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000678 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Chris Lattnerf4021e72007-08-23 05:46:52 +0000680 // Accumulate all of the case values in a vector so that we can sort them
681 // and detect duplicates. This vector contains the APInt for the case after
682 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000683 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000684 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattnerf4021e72007-08-23 05:46:52 +0000686 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000687 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
688 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerf4021e72007-08-23 05:46:52 +0000690 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000692 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Douglas Gregordbb26db2009-05-15 23:57:33 +0000694 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000695 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000697 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000698 if (TheDefaultStmt) {
699 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000700 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000701
Chris Lattnerf4021e72007-08-23 05:46:52 +0000702 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000703 // we'll return a valid AST. This requires recursing down the AST and
704 // finding it, not something we are set up to do right now. For now,
705 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000706 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000707 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000708 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattnerf4021e72007-08-23 05:46:52 +0000710 } else {
711 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner1e0a3902008-01-16 19:17:22 +0000713 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000714
715 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
716 HasDependentValue = true;
717 break;
718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Richard Smith8ef7b202012-01-18 23:55:52 +0000720 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Richard Smith80ad52f2013-01-02 11:42:31 +0000722 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000723 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
724 // constant expression of the promoted type of the switch condition.
725 ExprResult ConvLo =
726 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
727 if (ConvLo.isInvalid()) {
728 CaseListIsErroneous = true;
729 continue;
730 }
731 Lo = ConvLo.take();
732 } else {
733 // We already verified that the expression has a i-c-e value (C99
734 // 6.8.4.2p3) - get that value now.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000735 SmallVector<PartialDiagnosticAt, 8> Diags;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +0000736 LoVal = Lo->EvaluateKnownConstInt(Context, &Diags);
737 if (Diags.size() == 1 &&
738 Diags[0].second.getDiagID() == diag::note_constexpr_overflow) {
Fariborz Jahanianf6e65cc2013-01-10 20:26:42 +0000739 Diag(Lo->getLocStart(), diag::warn_case_constant_overflow) <<
740 LoVal.toString(10);
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +0000741 Diag(Diags[0].first, Diags[0].second);
742 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000743
744 // If the LHS is not the same type as the condition, insert an implicit
745 // cast.
746 Lo = DefaultLvalueConversion(Lo).take();
747 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
748 }
749
750 // Convert the value to the same width/sign as the condition had prior to
751 // integral promotions.
752 //
753 // FIXME: This causes us to reject valid code:
754 // switch ((char)c) { case 256: case 0: return 0; }
755 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000756 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000757 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000758 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000759
Chris Lattner1e0a3902008-01-16 19:17:22 +0000760 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000762 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000763 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000764 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000765 CS->getRHS()->isValueDependent()) {
766 HasDependentValue = true;
767 break;
768 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000769 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000770 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000771 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000772 }
773 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000774
775 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000776 // If we don't have a default statement, check whether the
777 // condition is constant.
778 llvm::APSInt ConstantCondValue;
779 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000780 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000781 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000782 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
783 Expr::SE_AllowSideEffects);
784 assert(!HasConstantCond ||
785 (ConstantCondValue.getBitWidth() == CondWidth &&
786 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000787 }
Richard Smith80d4b552011-12-28 19:48:30 +0000788 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000789
Douglas Gregordbb26db2009-05-15 23:57:33 +0000790 // Sort all the scalar case values so we can easily detect duplicates.
791 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
792
793 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000794 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
795 if (ShouldCheckConstantCond &&
796 CaseVals[i].first == ConstantCondValue)
797 ShouldCheckConstantCond = false;
798
799 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000800 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000801 // First, determine if either case value has a name
802 StringRef PrevString, CurrString;
803 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
804 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
805 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
806 PrevString = DeclRef->getDecl()->getName();
807 }
808 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
809 CurrString = DeclRef->getDecl()->getName();
810 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000811 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000812 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000813
814 if (PrevString == CurrString)
815 Diag(CaseVals[i].second->getLHS()->getLocStart(),
816 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000817 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000818 else
819 Diag(CaseVals[i].second->getLHS()->getLocStart(),
820 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000821 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
822 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000823 CaseValStr;
824
John McCall0fb97082010-05-18 03:19:21 +0000825 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000826 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000827 // FIXME: We really want to remove the bogus case stmt from the
828 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000829 CaseListIsErroneous = true;
830 }
831 }
832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregordbb26db2009-05-15 23:57:33 +0000834 // Detect duplicate case ranges, which usually don't exist at all in
835 // the first place.
836 if (!CaseRanges.empty()) {
837 // Sort all the case ranges by their low value so we can easily detect
838 // overlaps between ranges.
839 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregordbb26db2009-05-15 23:57:33 +0000841 // Scan the ranges, computing the high values and removing empty ranges.
842 std::vector<llvm::APSInt> HiVals;
843 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000844 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000845 CaseStmt *CR = CaseRanges[i].second;
846 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000847 llvm::APSInt HiVal;
848
Richard Smith80ad52f2013-01-02 11:42:31 +0000849 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000850 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
851 // constant expression of the promoted type of the switch condition.
852 ExprResult ConvHi =
853 CheckConvertedConstantExpression(Hi, CondType, HiVal,
854 CCEK_CaseValue);
855 if (ConvHi.isInvalid()) {
856 CaseListIsErroneous = true;
857 continue;
858 }
859 Hi = ConvHi.take();
860 } else {
861 HiVal = Hi->EvaluateKnownConstInt(Context);
862
863 // If the RHS is not the same type as the condition, insert an
864 // implicit cast.
865 Hi = DefaultLvalueConversion(Hi).take();
866 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
867 }
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Douglas Gregordbb26db2009-05-15 23:57:33 +0000869 // Convert the value to the same width/sign as the condition.
870 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000871 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000872 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Douglas Gregordbb26db2009-05-15 23:57:33 +0000874 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Douglas Gregordbb26db2009-05-15 23:57:33 +0000876 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000877 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000878 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
879 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000880 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000881 CaseRanges.erase(CaseRanges.begin()+i);
882 --i, --e;
883 continue;
884 }
John McCall0fb97082010-05-18 03:19:21 +0000885
886 if (ShouldCheckConstantCond &&
887 LoVal <= ConstantCondValue &&
888 ConstantCondValue <= HiVal)
889 ShouldCheckConstantCond = false;
890
Douglas Gregordbb26db2009-05-15 23:57:33 +0000891 HiVals.push_back(HiVal);
892 }
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Douglas Gregordbb26db2009-05-15 23:57:33 +0000894 // Rescan the ranges, looking for overlap with singleton values and other
895 // ranges. Since the range list is sorted, we only need to compare case
896 // ranges with their neighbors.
897 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
898 llvm::APSInt &CRLo = CaseRanges[i].first;
899 llvm::APSInt &CRHi = HiVals[i];
900 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Douglas Gregordbb26db2009-05-15 23:57:33 +0000902 // Check to see whether the case range overlaps with any
903 // singleton cases.
904 CaseStmt *OverlapStmt = 0;
905 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Douglas Gregordbb26db2009-05-15 23:57:33 +0000907 // Find the smallest value >= the lower bound. If I is in the
908 // case range, then we have overlap.
909 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
910 CaseVals.end(), CRLo,
911 CaseCompareFunctor());
912 if (I != CaseVals.end() && I->first < CRHi) {
913 OverlapVal = I->first; // Found overlap with scalar.
914 OverlapStmt = I->second;
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Douglas Gregordbb26db2009-05-15 23:57:33 +0000917 // Find the smallest value bigger than the upper bound.
918 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
919 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
920 OverlapVal = (I-1)->first; // Found overlap with scalar.
921 OverlapStmt = (I-1)->second;
922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Douglas Gregordbb26db2009-05-15 23:57:33 +0000924 // Check to see if this case stmt overlaps with the subsequent
925 // case range.
926 if (i && CRLo <= HiVals[i-1]) {
927 OverlapVal = HiVals[i-1]; // Found overlap with range.
928 OverlapStmt = CaseRanges[i-1].second;
929 }
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregordbb26db2009-05-15 23:57:33 +0000931 if (OverlapStmt) {
932 // If we have a duplicate, report it.
933 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
934 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000935 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000936 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000937 // FIXME: We really want to remove the bogus case stmt from the
938 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000939 CaseListIsErroneous = true;
940 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000941 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000942 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000943
John McCall0fb97082010-05-18 03:19:21 +0000944 // Complain if we have a constant condition and we didn't find a match.
945 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
946 // TODO: it would be nice if we printed enums as enums, chars as
947 // chars, etc.
948 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
949 << ConstantCondValue.toString(10)
950 << CondExpr->getSourceRange();
951 }
952
953 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000954 // values. We only issue a warning if there is not 'default:', but
955 // we still do the analysis to preserve this information in the AST
956 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000957 //
Chris Lattnerce784612010-09-16 17:09:42 +0000958 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000959
Douglas Gregorba915af2010-02-08 22:24:16 +0000960 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000961 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000962 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000963 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000964 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000965 EnumValsTy EnumVals;
966
John McCall0fb97082010-05-18 03:19:21 +0000967 // Gather all enum values, set their type and sort them,
968 // allowing easier comparison with CaseVals.
969 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000970 EDI != ED->enumerator_end(); ++EDI) {
971 llvm::APSInt Val = EDI->getInitVal();
972 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000973 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000974 }
975 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000976 EnumValsTy::iterator EIend =
977 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000978
979 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000980 EnumValsTy::const_iterator EI = EnumVals.begin();
981 for (CaseValsTy::const_iterator CI = CaseVals.begin();
982 CI != CaseVals.end(); CI++) {
983 while (EI != EIend && EI->first < CI->first)
984 EI++;
985 if (EI == EIend || EI->first > CI->first)
986 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000987 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000988 }
989 // See which of case ranges aren't in enum
990 EI = EnumVals.begin();
991 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
992 RI != CaseRanges.end() && EI != EIend; RI++) {
993 while (EI != EIend && EI->first < RI->first)
994 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000995
David Blaikie93667502012-01-22 02:31:55 +0000996 if (EI == EIend || EI->first != RI->first) {
997 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000998 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000999 }
David Blaikie93667502012-01-22 02:31:55 +00001000
Chad Rosier1093f492012-08-10 17:56:09 +00001001 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001002 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1003 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1004 while (EI != EIend && EI->first < Hi)
1005 EI++;
1006 if (EI == EIend || EI->first != Hi)
1007 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001008 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001010
Ted Kremenek559fb552010-09-09 00:05:53 +00001011 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001012 CaseValsTy::const_iterator CI = CaseVals.begin();
1013 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001014 bool hasCasesNotInSwitch = false;
1015
Chris Lattner5f9e2722011-07-23 10:55:15 +00001016 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
David Blaikie93667502012-01-22 02:31:55 +00001018 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001019 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001020 llvm::APSInt CIVal;
1021 while (CI != CaseVals.end() && CI->first < EI->first)
1022 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001023
Douglas Gregorba915af2010-02-08 22:24:16 +00001024 if (CI != CaseVals.end() && CI->first == EI->first)
1025 continue;
1026
Ted Kremenek559fb552010-09-09 00:05:53 +00001027 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001028 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001029 llvm::APSInt Hi =
1030 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001031 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001032 if (EI->first <= Hi)
1033 break;
1034 }
1035
Ted Kremenek559fb552010-09-09 00:05:53 +00001036 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001037 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001038 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001039 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001040 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001041
David Blaikie585d7792012-01-23 04:46:12 +00001042 if (TheDefaultStmt && UnhandledNames.empty())
1043 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001044
Chris Lattnerce784612010-09-16 17:09:42 +00001045 // Produce a nice diagnostic if multiple values aren't handled.
1046 switch (UnhandledNames.size()) {
1047 case 0: break;
1048 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001049 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001050 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001051 << UnhandledNames[0];
1052 break;
1053 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001054 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001055 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001056 << UnhandledNames[0] << UnhandledNames[1];
1057 break;
1058 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001059 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1060 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001061 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1062 break;
1063 default:
David Blaikie585d7792012-01-23 04:46:12 +00001064 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1065 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001066 << (unsigned)UnhandledNames.size()
1067 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1068 break;
1069 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001070
1071 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001072 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001073 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001074 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001075
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001076 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1077 diag::warn_empty_switch_body);
1078
Mike Stump390b4cc2009-05-16 07:39:55 +00001079 // FIXME: If the case list was broken is some way, we don't have a good system
1080 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001081 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001082 return StmtError();
1083
Sebastian Redlde307472009-01-11 00:38:46 +00001084 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001085}
1086
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001087void
1088Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1089 Expr *SrcExpr) {
1090 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001091 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001092 == DiagnosticsEngine::Ignored)
1093 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001094
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001095 if (const EnumType *ET = DstType->getAs<EnumType>())
1096 if (!Context.hasSameType(SrcType, DstType) &&
1097 SrcType->isIntegerType()) {
1098 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1099 SrcExpr->isIntegerConstantExpr(Context)) {
1100 // Get the bitwidth of the enum value before promotions.
1101 unsigned DstWith = Context.getIntWidth(DstType);
1102 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1103
1104 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1105 const EnumDecl *ED = ET->getDecl();
1106 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1107 EnumValsTy;
1108 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001109
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001110 // Gather all enum values, set their type and sort them,
1111 // allowing easier comparison with rhs constant.
1112 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1113 EDI != ED->enumerator_end(); ++EDI) {
1114 llvm::APSInt Val = EDI->getInitVal();
1115 AdjustAPSInt(Val, DstWith, DstIsSigned);
1116 EnumVals.push_back(std::make_pair(Val, *EDI));
1117 }
1118 if (EnumVals.empty())
1119 return;
1120 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1121 EnumValsTy::iterator EIend =
1122 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001123
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001124 // See which case values aren't in enum.
1125 EnumValsTy::const_iterator EI = EnumVals.begin();
1126 while (EI != EIend && EI->first < RhsVal)
1127 EI++;
1128 if (EI == EIend || EI->first != RhsVal) {
1129 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1130 << DstType;
1131 }
1132 }
1133 }
1134}
1135
John McCall60d7b3a2010-08-24 06:29:42 +00001136StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001137Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001138 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001139 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001140
Douglas Gregor5656e142009-11-24 21:15:44 +00001141 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001142 if (CondVar) {
1143 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001144 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001145 if (CondResult.isInvalid())
1146 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001147 }
John McCall9ae2f072010-08-23 23:25:46 +00001148 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001149 if (!ConditionExpr)
1150 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001151
John McCall9ae2f072010-08-23 23:25:46 +00001152 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001154 if (isa<NullStmt>(Body))
1155 getCurCompoundScope().setHasEmptyLoopBodies();
1156
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001157 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001158 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001159}
1160
John McCall60d7b3a2010-08-24 06:29:42 +00001161StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001162Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001163 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001164 Expr *Cond, SourceLocation CondRParen) {
1165 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001166
John Wiegley429bb272011-04-08 18:41:53 +00001167 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001168 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001169 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001170 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001171
Richard Smith41956372013-01-14 22:39:08 +00001172 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001173 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001174 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001175 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001176
John McCall9ae2f072010-08-23 23:25:46 +00001177 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001178
John McCall9ae2f072010-08-23 23:25:46 +00001179 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001180}
1181
Richard Trieu694e7962012-04-30 18:01:30 +00001182namespace {
1183 // This visitor will traverse a conditional statement and store all
1184 // the evaluated decls into a vector. Simple is set to true if none
1185 // of the excluded constructs are used.
1186 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1187 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001188 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001189 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001190public:
1191 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1192
1193 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001194 SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001195 Inherited(S.Context),
1196 Decls(Decls),
1197 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001198 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001199
1200 bool isSimple() { return Simple; }
1201
1202 // Replaces the method in EvaluatedExprVisitor.
1203 void VisitMemberExpr(MemberExpr* E) {
1204 Simple = false;
1205 }
1206
1207 // Any Stmt not whitelisted will cause the condition to be marked complex.
1208 void VisitStmt(Stmt *S) {
1209 Simple = false;
1210 }
1211
1212 void VisitBinaryOperator(BinaryOperator *E) {
1213 Visit(E->getLHS());
1214 Visit(E->getRHS());
1215 }
1216
1217 void VisitCastExpr(CastExpr *E) {
1218 Visit(E->getSubExpr());
1219 }
1220
1221 void VisitUnaryOperator(UnaryOperator *E) {
1222 // Skip checking conditionals with derefernces.
1223 if (E->getOpcode() == UO_Deref)
1224 Simple = false;
1225 else
1226 Visit(E->getSubExpr());
1227 }
1228
1229 void VisitConditionalOperator(ConditionalOperator *E) {
1230 Visit(E->getCond());
1231 Visit(E->getTrueExpr());
1232 Visit(E->getFalseExpr());
1233 }
1234
1235 void VisitParenExpr(ParenExpr *E) {
1236 Visit(E->getSubExpr());
1237 }
1238
1239 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1240 Visit(E->getOpaqueValue()->getSourceExpr());
1241 Visit(E->getFalseExpr());
1242 }
1243
1244 void VisitIntegerLiteral(IntegerLiteral *E) { }
1245 void VisitFloatingLiteral(FloatingLiteral *E) { }
1246 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1247 void VisitCharacterLiteral(CharacterLiteral *E) { }
1248 void VisitGNUNullExpr(GNUNullExpr *E) { }
1249 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1250
1251 void VisitDeclRefExpr(DeclRefExpr *E) {
1252 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1253 if (!VD) return;
1254
1255 Ranges.push_back(E->getSourceRange());
1256
1257 Decls.insert(VD);
1258 }
1259
1260 }; // end class DeclExtractor
1261
1262 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001263 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001264 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1265 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1266 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001267
1268public:
1269 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1270
1271 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1272 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1273 if (!Statement) return;
1274
1275 Visit(Statement);
1276 }
1277
1278 void VisitReturnStmt(ReturnStmt *S) {
1279 FoundDecl = true;
1280 }
1281
1282 void VisitBreakStmt(BreakStmt *S) {
1283 FoundDecl = true;
1284 }
1285
1286 void VisitGotoStmt(GotoStmt *S) {
1287 FoundDecl = true;
1288 }
1289
1290 void VisitCastExpr(CastExpr *E) {
1291 if (E->getCastKind() == CK_LValueToRValue)
1292 CheckLValueToRValueCast(E->getSubExpr());
1293 else
1294 Visit(E->getSubExpr());
1295 }
1296
1297 void CheckLValueToRValueCast(Expr *E) {
1298 E = E->IgnoreParenImpCasts();
1299
1300 if (isa<DeclRefExpr>(E)) {
1301 return;
1302 }
1303
1304 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1305 Visit(CO->getCond());
1306 CheckLValueToRValueCast(CO->getTrueExpr());
1307 CheckLValueToRValueCast(CO->getFalseExpr());
1308 return;
1309 }
1310
1311 if (BinaryConditionalOperator *BCO =
1312 dyn_cast<BinaryConditionalOperator>(E)) {
1313 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1314 CheckLValueToRValueCast(BCO->getFalseExpr());
1315 return;
1316 }
1317
1318 Visit(E);
1319 }
1320
1321 void VisitDeclRefExpr(DeclRefExpr *E) {
1322 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1323 if (Decls.count(VD))
1324 FoundDecl = true;
1325 }
1326
1327 bool FoundDeclInUse() { return FoundDecl; }
1328
1329 }; // end class DeclMatcher
1330
1331 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1332 Expr *Third, Stmt *Body) {
1333 // Condition is empty
1334 if (!Second) return;
1335
1336 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1337 Second->getLocStart())
1338 == DiagnosticsEngine::Ignored)
1339 return;
1340
1341 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1342 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001343 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001344 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001345 DE.Visit(Second);
1346
1347 // Don't analyze complex conditionals.
1348 if (!DE.isSimple()) return;
1349
1350 // No decls found.
1351 if (Decls.size() == 0) return;
1352
Richard Trieu90875992012-05-04 03:01:54 +00001353 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001354 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1355 E = Decls.end();
1356 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001357 if ((*I)->getType().isVolatileQualified() ||
1358 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001359
1360 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1361 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1362 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1363 return;
1364
1365 // Load decl names into diagnostic.
1366 if (Decls.size() > 4)
1367 PDiag << 0;
1368 else {
1369 PDiag << Decls.size();
1370 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1371 E = Decls.end();
1372 I != E; ++I)
1373 PDiag << (*I)->getDeclName();
1374 }
1375
1376 // Load SourceRanges into diagnostic if there is room.
1377 // Otherwise, load the SourceRange of the conditional expression.
1378 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001379 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1380 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001381 I != E; ++I)
1382 PDiag << *I;
1383 else
1384 PDiag << Second->getSourceRange();
1385
1386 S.Diag(Ranges.begin()->getBegin(), PDiag);
1387 }
1388
1389} // end namespace
1390
John McCall60d7b3a2010-08-24 06:29:42 +00001391StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001392Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001393 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001394 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001395 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001396 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001397 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001398 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1399 // declare identifiers for objects having storage class 'auto' or
1400 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001401 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1402 DI!=DE; ++DI) {
1403 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001404 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001405 VD = 0;
1406 if (VD == 0)
1407 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1408 // FIXME: mark decl erroneous!
1409 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001410 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001412
Richard Trieu694e7962012-04-30 18:01:30 +00001413 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1414
John McCall60d7b3a2010-08-24 06:29:42 +00001415 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001416 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001417 if (secondVar) {
1418 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001419 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001420 if (SecondResult.isInvalid())
1421 return StmtError();
1422 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001423
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001424 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001425
Anders Carlsson3af708f2009-08-01 01:39:59 +00001426 DiagnoseUnusedExprResult(First);
1427 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001428 DiagnoseUnusedExprResult(Body);
1429
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001430 if (isa<NullStmt>(Body))
1431 getCurCompoundScope().setHasEmptyLoopBodies();
1432
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433 return Owned(new (Context) ForStmt(Context, First,
1434 SecondResult.take(), ConditionVar,
1435 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001436 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001437}
1438
John McCallf6a16482010-12-04 03:47:34 +00001439/// In an Objective C collection iteration statement:
1440/// for (x in y)
1441/// x can be an arbitrary l-value expression. Bind it up as a
1442/// full-expression.
1443StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001444 // Reduce placeholder expressions here. Note that this rejects the
1445 // use of pseudo-object l-values in this position.
1446 ExprResult result = CheckPlaceholderExpr(E);
1447 if (result.isInvalid()) return StmtError();
1448 E = result.take();
1449
Richard Smith41956372013-01-14 22:39:08 +00001450 ExprResult FullExpr = ActOnFinishFullExpr(E);
1451 if (FullExpr.isInvalid())
1452 return StmtError();
1453 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001454}
1455
John McCall990567c2011-07-27 01:07:15 +00001456ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001457Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1458 if (!collection)
1459 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001460
John McCall990567c2011-07-27 01:07:15 +00001461 // Bail out early if we've got a type-dependent expression.
1462 if (collection->isTypeDependent()) return Owned(collection);
1463
1464 // Perform normal l-value conversion.
1465 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1466 if (result.isInvalid())
1467 return ExprError();
1468 collection = result.take();
1469
1470 // The operand needs to have object-pointer type.
1471 // TODO: should we do a contextual conversion?
1472 const ObjCObjectPointerType *pointerType =
1473 collection->getType()->getAs<ObjCObjectPointerType>();
1474 if (!pointerType)
1475 return Diag(forLoc, diag::err_collection_expr_type)
1476 << collection->getType() << collection->getSourceRange();
1477
1478 // Check that the operand provides
1479 // - countByEnumeratingWithState:objects:count:
1480 const ObjCObjectType *objectType = pointerType->getObjectType();
1481 ObjCInterfaceDecl *iface = objectType->getInterface();
1482
1483 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001484 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001485 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001486 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001487 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001488 ? diag::err_arc_collection_forward
1489 : 0,
1490 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001491 // Otherwise, if we have any useful type information, check that
1492 // the type declares the appropriate method.
1493 } else if (iface || !objectType->qual_empty()) {
1494 IdentifierInfo *selectorIdents[] = {
1495 &Context.Idents.get("countByEnumeratingWithState"),
1496 &Context.Idents.get("objects"),
1497 &Context.Idents.get("count")
1498 };
1499 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1500
1501 ObjCMethodDecl *method = 0;
1502
1503 // If there's an interface, look in both the public and private APIs.
1504 if (iface) {
1505 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001506 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001507 }
1508
1509 // Also check protocol qualifiers.
1510 if (!method)
1511 method = LookupMethodInQualifiedType(selector, pointerType,
1512 /*instance*/ true);
1513
1514 // If we didn't find it anywhere, give up.
1515 if (!method) {
1516 Diag(forLoc, diag::warn_collection_expr_type)
1517 << collection->getType() << selector << collection->getSourceRange();
1518 }
1519
1520 // TODO: check for an incompatible signature?
1521 }
1522
1523 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001524 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001525}
1526
John McCall60d7b3a2010-08-24 06:29:42 +00001527StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001528Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001529 Stmt *First, Expr *collection,
1530 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001531
1532 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001533 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001534
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001535 if (First) {
1536 QualType FirstType;
1537 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001538 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001539 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1540 diag::err_toomany_element_decls));
1541
John McCallf85e1932011-06-15 23:02:42 +00001542 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1543 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001544 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1545 // declare identifiers for objects having storage class 'auto' or
1546 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001547 if (!D->hasLocalStorage())
1548 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001549 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001550 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001551 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001552 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001553 return StmtError(Diag(First->getLocStart(),
1554 diag::err_selector_element_not_lvalue)
1555 << First->getSourceRange());
1556
Mike Stump1eb44332009-09-09 15:08:12 +00001557 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001558 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001559 if (!FirstType->isDependentType() &&
1560 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001561 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001562 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1563 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001564 }
Chad Rosier1093f492012-08-10 17:56:09 +00001565
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001566 if (CollectionExprResult.isInvalid())
1567 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001568
Richard Smith41956372013-01-14 22:39:08 +00001569 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1570 if (CollectionExprResult.isInvalid())
1571 return StmtError();
1572
Chad Rosier1093f492012-08-10 17:56:09 +00001573 return Owned(new (Context) ObjCForCollectionStmt(First,
1574 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001575 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001576}
Reid Spencer5f016e22007-07-11 17:01:13 +00001577
Richard Smithad762fc2011-04-14 22:09:26 +00001578/// Finish building a variable declaration for a for-range statement.
1579/// \return true if an error occurs.
1580static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1581 SourceLocation Loc, int diag) {
1582 // Deduce the type for the iterator variable now rather than leaving it to
1583 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1584 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001585 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001586 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1587 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001588 SemaRef.Diag(Loc, diag) << Init->getType();
1589 if (!InitTSI) {
1590 Decl->setInvalidDecl();
1591 return true;
1592 }
1593 Decl->setTypeSourceInfo(InitTSI);
1594 Decl->setType(InitTSI->getType());
1595
John McCallf85e1932011-06-15 23:02:42 +00001596 // In ARC, infer lifetime.
1597 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1598 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001599 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001600 SemaRef.inferObjCARCLifetime(Decl))
1601 Decl->setInvalidDecl();
1602
Richard Smithad762fc2011-04-14 22:09:26 +00001603 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1604 /*TypeMayContainAuto=*/false);
1605 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001606 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001607 return false;
1608}
1609
Sam Panzere1715b62012-08-21 00:52:01 +00001610namespace {
1611
Richard Smithad762fc2011-04-14 22:09:26 +00001612/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001613/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001614/// nor from the diagnostics produced when analysing the implicit expressions
1615/// required in a for-range statement.
1616void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001617 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001618 CallExpr *CE = dyn_cast<CallExpr>(E);
1619 if (!CE)
1620 return;
1621 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1622 if (!D)
1623 return;
1624 SourceLocation Loc = D->getLocation();
1625
1626 std::string Description;
1627 bool IsTemplate = false;
1628 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1629 Description = SemaRef.getTemplateArgumentBindingsText(
1630 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1631 IsTemplate = true;
1632 }
1633
1634 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1635 << BEF << IsTemplate << Description << E->getType();
1636}
1637
Sam Panzere1715b62012-08-21 00:52:01 +00001638/// Build a variable declaration for a for-range statement.
1639VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1640 QualType Type, const char *Name) {
1641 DeclContext *DC = SemaRef.CurContext;
1642 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1643 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1644 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1645 TInfo, SC_Auto, SC_None);
1646 Decl->setImplicit();
1647 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001648}
1649
1650}
1651
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001652static bool ObjCEnumerationCollection(Expr *Collection) {
1653 return !Collection->isTypeDependent()
1654 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1655}
1656
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001657/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001658///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001659/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001660/// A range-based for statement is equivalent to
1661///
1662/// {
1663/// auto && __range = range-init;
1664/// for ( auto __begin = begin-expr,
1665/// __end = end-expr;
1666/// __begin != __end;
1667/// ++__begin ) {
1668/// for-range-declaration = *__begin;
1669/// statement
1670/// }
1671/// }
1672///
1673/// The body of the loop is not available yet, since it cannot be analysed until
1674/// we have determined the type of the for-range-declaration.
1675StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001676Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001677 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001678 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001679 if (!First || !Range)
1680 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001681
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001682 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001683 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001684
1685 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1686 assert(DS && "first part of for range not a decl stmt");
1687
1688 if (!DS->isSingleDecl()) {
1689 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1690 return StmtError();
1691 }
1692 if (DS->getSingleDecl()->isInvalidDecl())
1693 return StmtError();
1694
1695 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1696 return StmtError();
1697
1698 // Build auto && __range = range-init
1699 SourceLocation RangeLoc = Range->getLocStart();
1700 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1701 Context.getAutoRRefDeductType(),
1702 "__range");
1703 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1704 diag::err_for_range_deduction_failure))
1705 return StmtError();
1706
1707 // Claim the type doesn't contain auto: we've already done the checking.
1708 DeclGroupPtrTy RangeGroup =
1709 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1710 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1711 if (RangeDecl.isInvalid())
1712 return StmtError();
1713
1714 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1715 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001716 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001717}
1718
1719/// \brief Create the initialization, compare, and increment steps for
1720/// the range-based for loop expression.
1721/// This function does not handle array-based for loops,
1722/// which are created in Sema::BuildCXXForRangeStmt.
1723///
1724/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1725/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1726/// CandidateSet and BEF are set and some non-success value is returned on
1727/// failure.
1728static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1729 Expr *BeginRange, Expr *EndRange,
1730 QualType RangeType,
1731 VarDecl *BeginVar,
1732 VarDecl *EndVar,
1733 SourceLocation ColonLoc,
1734 OverloadCandidateSet *CandidateSet,
1735 ExprResult *BeginExpr,
1736 ExprResult *EndExpr,
1737 Sema::BeginEndFunction *BEF) {
1738 DeclarationNameInfo BeginNameInfo(
1739 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1740 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1741 ColonLoc);
1742
1743 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1744 Sema::LookupMemberName);
1745 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1746
1747 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1748 // - if _RangeT is a class type, the unqualified-ids begin and end are
1749 // looked up in the scope of class _RangeT as if by class member access
1750 // lookup (3.4.5), and if either (or both) finds at least one
1751 // declaration, begin-expr and end-expr are __range.begin() and
1752 // __range.end(), respectively;
1753 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1754 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1755
1756 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1757 SourceLocation RangeLoc = BeginVar->getLocation();
1758 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1759
1760 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1761 << RangeLoc << BeginRange->getType() << *BEF;
1762 return Sema::FRS_DiagnosticIssued;
1763 }
1764 } else {
1765 // - otherwise, begin-expr and end-expr are begin(__range) and
1766 // end(__range), respectively, where begin and end are looked up with
1767 // argument-dependent lookup (3.4.2). For the purposes of this name
1768 // lookup, namespace std is an associated namespace.
1769
1770 }
1771
1772 *BEF = Sema::BEF_begin;
1773 Sema::ForRangeStatus RangeStatus =
1774 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1775 Sema::BEF_begin, BeginNameInfo,
1776 BeginMemberLookup, CandidateSet,
1777 BeginRange, BeginExpr);
1778
1779 if (RangeStatus != Sema::FRS_Success)
1780 return RangeStatus;
1781 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1782 diag::err_for_range_iter_deduction_failure)) {
1783 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1784 return Sema::FRS_DiagnosticIssued;
1785 }
1786
1787 *BEF = Sema::BEF_end;
1788 RangeStatus =
1789 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1790 Sema::BEF_end, EndNameInfo,
1791 EndMemberLookup, CandidateSet,
1792 EndRange, EndExpr);
1793 if (RangeStatus != Sema::FRS_Success)
1794 return RangeStatus;
1795 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1796 diag::err_for_range_iter_deduction_failure)) {
1797 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1798 return Sema::FRS_DiagnosticIssued;
1799 }
1800 return Sema::FRS_Success;
1801}
1802
1803/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001804/// If the attempt fails, this function will return a valid, null StmtResult
1805/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001806static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1807 SourceLocation ForLoc,
1808 Stmt *LoopVarDecl,
1809 SourceLocation ColonLoc,
1810 Expr *Range,
1811 SourceLocation RangeLoc,
1812 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001813 // Determine whether we can rebuild the for-range statement with a
1814 // dereferenced range expression.
1815 ExprResult AdjustedRange;
1816 {
1817 Sema::SFINAETrap Trap(SemaRef);
1818
1819 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1820 if (AdjustedRange.isInvalid())
1821 return StmtResult();
1822
1823 StmtResult SR =
1824 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1825 AdjustedRange.get(), RParenLoc,
1826 Sema::BFRK_Check);
1827 if (SR.isInvalid())
1828 return StmtResult();
1829 }
1830
1831 // The attempt to dereference worked well enough that it could produce a valid
1832 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1833 // case there are any other (non-fatal) problems with it.
1834 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1835 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1836 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1837 AdjustedRange.get(), RParenLoc,
1838 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001839}
1840
Richard Smith8b533d92012-09-20 21:52:32 +00001841/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001842StmtResult
1843Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1844 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1845 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001846 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001847 Scope *S = getCurScope();
1848
1849 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1850 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1851 QualType RangeVarType = RangeVar->getType();
1852
1853 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1854 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1855
1856 StmtResult BeginEndDecl = BeginEnd;
1857 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1858
1859 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1860 SourceLocation RangeLoc = RangeVar->getLocation();
1861
Ted Kremeneke50b0152011-10-10 22:36:28 +00001862 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1863
1864 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1865 VK_LValue, ColonLoc);
1866 if (BeginRangeRef.isInvalid())
1867 return StmtError();
1868
1869 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1870 VK_LValue, ColonLoc);
1871 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001872 return StmtError();
1873
1874 QualType AutoType = Context.getAutoDeductType();
1875 Expr *Range = RangeVar->getInit();
1876 if (!Range)
1877 return StmtError();
1878 QualType RangeType = Range->getType();
1879
1880 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001881 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001882 return StmtError();
1883
1884 // Build auto __begin = begin-expr, __end = end-expr.
1885 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1886 "__begin");
1887 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1888 "__end");
1889
1890 // Build begin-expr and end-expr and attach to __begin and __end variables.
1891 ExprResult BeginExpr, EndExpr;
1892 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1893 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1894 // __range + __bound, respectively, where __bound is the array bound. If
1895 // _RangeT is an array of unknown size or an array of incomplete type,
1896 // the program is ill-formed;
1897
1898 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001899 BeginExpr = BeginRangeRef;
1900 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001901 diag::err_for_range_iter_deduction_failure)) {
1902 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1903 return StmtError();
1904 }
1905
1906 // Find the array bound.
1907 ExprResult BoundExpr;
1908 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1909 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001910 Context.getPointerDiffType(),
1911 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001912 else if (const VariableArrayType *VAT =
1913 dyn_cast<VariableArrayType>(UnqAT))
1914 BoundExpr = VAT->getSizeExpr();
1915 else {
1916 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1917 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001918 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001919 }
1920
1921 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001922 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001923 BoundExpr.get());
1924 if (EndExpr.isInvalid())
1925 return StmtError();
1926 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1927 diag::err_for_range_iter_deduction_failure)) {
1928 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1929 return StmtError();
1930 }
1931 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001932 OverloadCandidateSet CandidateSet(RangeLoc);
1933 Sema::BeginEndFunction BEFFailure;
1934 ForRangeStatus RangeStatus =
1935 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1936 EndRangeRef.get(), RangeType,
1937 BeginVar, EndVar, ColonLoc, &CandidateSet,
1938 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001939
Sam Panzere1715b62012-08-21 00:52:01 +00001940 // If building the range failed, try dereferencing the range expression
1941 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001942 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001943 BEFFailure == BEF_begin) {
1944 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1945 LoopVarDecl, ColonLoc,
1946 Range, RangeLoc,
1947 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001948 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001949 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001950 }
1951
Sam Panzere1715b62012-08-21 00:52:01 +00001952 // Otherwise, emit diagnostics if we haven't already.
1953 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001954 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001955 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1956 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001957 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001958 }
1959 // Return an error if no fix was discovered.
1960 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001961 return StmtError();
1962 }
1963
Sam Panzere1715b62012-08-21 00:52:01 +00001964 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1965 "invalid range expression in for loop");
1966
1967 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001968 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1969 if (!Context.hasSameType(BeginType, EndType)) {
1970 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1971 << BeginType << EndType;
1972 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1973 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1974 }
1975
1976 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1977 // Claim the type doesn't contain auto: we've already done the checking.
1978 DeclGroupPtrTy BeginEndGroup =
1979 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1980 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1981
Ted Kremeneke50b0152011-10-10 22:36:28 +00001982 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1983 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001984 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001985 if (BeginRef.isInvalid())
1986 return StmtError();
1987
Richard Smithad762fc2011-04-14 22:09:26 +00001988 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1989 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001990 if (EndRef.isInvalid())
1991 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001992
1993 // Build and check __begin != __end expression.
1994 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1995 BeginRef.get(), EndRef.get());
1996 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1997 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1998 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00001999 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2000 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002001 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2002 if (!Context.hasSameType(BeginType, EndType))
2003 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2004 return StmtError();
2005 }
2006
2007 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002008 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2009 VK_LValue, ColonLoc);
2010 if (BeginRef.isInvalid())
2011 return StmtError();
2012
Richard Smithad762fc2011-04-14 22:09:26 +00002013 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2014 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2015 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002016 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2017 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002018 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2019 return StmtError();
2020 }
2021
2022 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002023 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2024 VK_LValue, ColonLoc);
2025 if (BeginRef.isInvalid())
2026 return StmtError();
2027
Richard Smithad762fc2011-04-14 22:09:26 +00002028 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2029 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002030 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2031 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002032 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2033 return StmtError();
2034 }
2035
Richard Smith8b533d92012-09-20 21:52:32 +00002036 // Attach *__begin as initializer for VD. Don't touch it if we're just
2037 // trying to determine whether this would be a valid range.
2038 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002039 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2040 /*TypeMayContainAuto=*/true);
2041 if (LoopVar->isInvalidDecl())
2042 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2043 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002044 } else {
2045 // The range is implicitly used as a placeholder when it is dependent.
2046 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002047 }
2048
Richard Smith8b533d92012-09-20 21:52:32 +00002049 // Don't bother to actually allocate the result if we're just trying to
2050 // determine whether it would be valid.
2051 if (Kind == BFRK_Check)
2052 return StmtResult();
2053
Richard Smithad762fc2011-04-14 22:09:26 +00002054 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2055 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2056 NotEqExpr.take(), IncrExpr.take(),
2057 LoopVarDS, /*Body=*/0, ForLoc,
2058 ColonLoc, RParenLoc));
2059}
2060
Chad Rosier1093f492012-08-10 17:56:09 +00002061/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002062/// statement.
2063StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2064 if (!S || !B)
2065 return StmtError();
2066 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002067
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002068 ForStmt->setBody(B);
2069 return S;
2070}
2071
Richard Smithad762fc2011-04-14 22:09:26 +00002072/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2073/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2074/// body cannot be performed until after the type of the range variable is
2075/// determined.
2076StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2077 if (!S || !B)
2078 return StmtError();
2079
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002080 if (isa<ObjCForCollectionStmt>(S))
2081 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002082
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002083 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2084 ForStmt->setBody(B);
2085
2086 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2087 diag::warn_empty_range_based_for_body);
2088
Richard Smithad762fc2011-04-14 22:09:26 +00002089 return S;
2090}
2091
Chris Lattner57ad3782011-02-17 20:34:02 +00002092StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2093 SourceLocation LabelLoc,
2094 LabelDecl *TheDecl) {
2095 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002096 TheDecl->setUsed();
2097 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002098}
2099
John McCall60d7b3a2010-08-24 06:29:42 +00002100StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002101Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002102 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002103 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002104 if (!E->isTypeDependent()) {
2105 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002106 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002107 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002108 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002109 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2110 if (ExprRes.isInvalid())
2111 return StmtError();
2112 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002113 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002114 return StmtError();
2115 }
John McCallb60a77e2010-08-01 00:26:45 +00002116
Richard Smith41956372013-01-14 22:39:08 +00002117 ExprResult ExprRes = ActOnFinishFullExpr(E);
2118 if (ExprRes.isInvalid())
2119 return StmtError();
2120 E = ExprRes.take();
2121
John McCall781472f2010-08-25 08:40:02 +00002122 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002123
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002124 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002125}
2126
John McCall60d7b3a2010-08-24 06:29:42 +00002127StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002128Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 Scope *S = CurScope->getContinueParent();
2130 if (!S) {
2131 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002132 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002134
Ted Kremenek8189cde2009-02-07 01:47:29 +00002135 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002136}
2137
John McCall60d7b3a2010-08-24 06:29:42 +00002138StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002139Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 Scope *S = CurScope->getBreakParent();
2141 if (!S) {
2142 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002143 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002145
Ted Kremenek8189cde2009-02-07 01:47:29 +00002146 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002147}
2148
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002149/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002150/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002151///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002152/// \param ReturnType If we're determining the copy elision candidate for
2153/// a return statement, this is the return type of the function. If we're
2154/// determining the copy elision candidate for a throw expression, this will
2155/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002156///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002157/// \param E The expression being returned from the function or block, or
2158/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002159///
Douglas Gregor4926d832011-05-20 15:00:53 +00002160/// \param AllowFunctionParameter Whether we allow function parameters to
2161/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2162/// we re-use this logic to determine whether we should try to move as part of
2163/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002164///
2165/// \returns The NRVO candidate variable, if the return statement may use the
2166/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002167const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2168 Expr *E,
2169 bool AllowFunctionParameter) {
2170 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002171 // - in a return statement in a function with ...
2172 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002173 if (!ReturnType.isNull()) {
2174 if (!ReturnType->isRecordType())
2175 return 0;
2176 // ... the same cv-unqualified type as the function return type ...
2177 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2178 return 0;
2179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180
2181 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002182 // (other than a function or catch-clause parameter)) ...
2183 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002184 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002185 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002186 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2187 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002188 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002189
John McCall1cd76e82011-11-11 03:57:31 +00002190 // ...object (other than a function or catch-clause parameter)...
2191 if (VD->getKind() != Decl::Var &&
2192 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2193 return 0;
2194 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002195
John McCall1cd76e82011-11-11 03:57:31 +00002196 // ...automatic...
2197 if (!VD->hasLocalStorage()) return 0;
2198
2199 // ...non-volatile...
2200 if (VD->getType().isVolatileQualified()) return 0;
2201 if (VD->getType()->isReferenceType()) return 0;
2202
2203 // __block variables can't be allocated in a way that permits NRVO.
2204 if (VD->hasAttr<BlocksAttr>()) return 0;
2205
2206 // Variables with higher required alignment than their type's ABI
2207 // alignment cannot use NRVO.
2208 if (VD->hasAttr<AlignedAttr>() &&
2209 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2210 return 0;
2211
2212 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002213}
2214
Douglas Gregor07f402c2011-01-21 21:08:57 +00002215/// \brief Perform the initialization of a potentially-movable value, which
2216/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002217///
2218/// This routine implements C++0x [class.copy]p33, which attempts to treat
2219/// returned lvalues as rvalues in certain cases (to prefer move construction),
2220/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002221ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002222Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2223 const VarDecl *NRVOCandidate,
2224 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002225 Expr *Value,
2226 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002227 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002228 // When the criteria for elision of a copy operation are met or would
2229 // be met save for the fact that the source object is a function
2230 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002231 // overload resolution to select the constructor for the copy is first
2232 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002233 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002234 if (AllowNRVO &&
2235 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002236 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002237 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002238
Douglas Gregorcc15f012011-01-21 19:38:21 +00002239 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002240 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002241 = InitializationKind::CreateCopy(Value->getLocStart(),
2242 Value->getLocStart());
2243 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
2245 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002246 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002247 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002248 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002249 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002250 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2251 StepEnd = Seq.step_end();
2252 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002253 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002254 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002255
2256 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002257 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002258
Douglas Gregorcc15f012011-01-21 19:38:21 +00002259 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002260 = Constructor->getParamDecl(0)->getType()
2261 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002262
Douglas Gregorcc15f012011-01-21 19:38:21 +00002263 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002264 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002265 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2266 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002267 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002268
Douglas Gregorcc15f012011-01-21 19:38:21 +00002269 // Promote "AsRvalue" to the heap, since we now need this
2270 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002271 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002272 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002273
Douglas Gregorcc15f012011-01-21 19:38:21 +00002274 // Complete type-checking the initialization of the return type
2275 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002276 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002277 }
2278 }
2279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002280
Douglas Gregorcc15f012011-01-21 19:38:21 +00002281 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002282 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002283 // (again) now with the return value expression as written.
2284 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002285 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286
Douglas Gregorcc15f012011-01-21 19:38:21 +00002287 return Res;
2288}
2289
Eli Friedman84b007f2012-01-26 03:00:14 +00002290/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2291/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002292///
John McCall60d7b3a2010-08-24 06:29:42 +00002293StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002294Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2295 // If this is the first return we've seen, infer the return type.
2296 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2297 // rules which allows multiple return statements.
2298 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002299 QualType FnRetType = CurCap->ReturnType;
2300
2301 // For blocks/lambdas with implicit return types, we check each return
2302 // statement individually, and deduce the common return type when the block
2303 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002304 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002305 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002306 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2307 if (Result.isInvalid())
2308 return StmtError();
2309 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002310
Jordan Rose7dd900e2012-07-02 21:19:23 +00002311 if (!RetValExp->isTypeDependent())
2312 FnRetType = RetValExp->getType();
2313 else
2314 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002315 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002316 if (RetValExp) {
2317 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2318 // initializer list, because it is not an expression (even
2319 // though we represent it as one). We still deduce 'void'.
2320 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2321 << RetValExp->getSourceRange();
2322 }
2323
Jordan Rose7dd900e2012-07-02 21:19:23 +00002324 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002325 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002326
2327 // Although we'll properly infer the type of the block once it's completed,
2328 // make sure we provide a return type now for better error recovery.
2329 if (CurCap->ReturnType.isNull())
2330 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002331 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002332 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002333
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002334 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002335 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2336 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2337 return StmtError();
2338 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002339 } else {
2340 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2341 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2342 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2343 return StmtError();
2344 }
2345 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002346
Steve Naroff4eb206b2008-09-03 18:15:37 +00002347 // Otherwise, verify that this result type matches the previous one. We are
2348 // pickier with blocks than for normal functions because we don't have GCC
2349 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002350 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002351 if (FnRetType->isDependentType()) {
2352 // Delay processing for now. TODO: there are lots of dependent
2353 // types we can conclusively prove aren't void.
2354 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002355 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002356 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002357 (RetValExp->isTypeDependent() ||
2358 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002359 if (!getLangOpts().CPlusPlus &&
2360 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002361 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002362 else {
2363 Diag(ReturnLoc, diag::err_return_block_has_expr);
2364 RetValExp = 0;
2365 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002366 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002367 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002368 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2369 } else if (!RetValExp->isTypeDependent()) {
2370 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002371
John McCall0a7efe12011-08-17 22:09:46 +00002372 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2373 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2374 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002375
John McCall0a7efe12011-08-17 22:09:46 +00002376 // In C++ the return statement is handled via a copy initialization.
2377 // the C version of which boils down to CheckSingleAssignmentConstraints.
2378 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2379 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2380 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002381 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002382 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2383 FnRetType, RetValExp);
2384 if (Res.isInvalid()) {
2385 // FIXME: Cleanup temporaries here, anyway?
2386 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002387 }
John McCall0a7efe12011-08-17 22:09:46 +00002388 RetValExp = Res.take();
2389 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002390 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002391
John McCalld963c372011-08-17 21:34:14 +00002392 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002393 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2394 if (ER.isInvalid())
2395 return StmtError();
2396 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002397 }
John McCall0a7efe12011-08-17 22:09:46 +00002398 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2399 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002400
Jordan Rose7dd900e2012-07-02 21:19:23 +00002401 // If we need to check for the named return value optimization,
2402 // or if we need to infer the return type,
2403 // save the return statement in our scope for later processing.
2404 if (CurCap->HasImplicitReturnType ||
2405 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2406 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002407 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002408
Douglas Gregor5077c382010-05-15 06:01:05 +00002409 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002410}
Reid Spencer5f016e22007-07-11 17:01:13 +00002411
John McCall60d7b3a2010-08-24 06:29:42 +00002412StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002413Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002414 // Check for unexpanded parameter packs.
2415 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2416 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002417
Eli Friedman84b007f2012-01-26 03:00:14 +00002418 if (isa<CapturingScopeInfo>(getCurFunction()))
2419 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002420
Chris Lattner371f2582008-12-04 23:50:19 +00002421 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002422 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002423 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002424 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002425 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002426 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002427 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002428 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002429 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002430 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2431 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002432 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002433 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002434 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2435 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002436 }
2437 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002438 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002439
Douglas Gregor5077c382010-05-15 06:01:05 +00002440 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002441 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002442 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002443 if (isa<InitListExpr>(RetValExp)) {
2444 // We simply never allow init lists as the return value of void
2445 // functions. This is compatible because this was never allowed before,
2446 // so there's no legacy code to deal with.
2447 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2448 int FunctionKind = 0;
2449 if (isa<ObjCMethodDecl>(CurDecl))
2450 FunctionKind = 1;
2451 else if (isa<CXXConstructorDecl>(CurDecl))
2452 FunctionKind = 2;
2453 else if (isa<CXXDestructorDecl>(CurDecl))
2454 FunctionKind = 3;
2455
2456 Diag(ReturnLoc, diag::err_return_init_list)
2457 << CurDecl->getDeclName() << FunctionKind
2458 << RetValExp->getSourceRange();
2459
2460 // Drop the expression.
2461 RetValExp = 0;
2462 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002463 // C99 6.8.6.4p1 (ext_ since GCC warns)
2464 unsigned D = diag::ext_return_has_expr;
2465 if (RetValExp->getType()->isVoidType())
2466 D = diag::ext_return_has_void_expr;
2467 else {
2468 ExprResult Result = Owned(RetValExp);
2469 Result = IgnoredValueConversions(Result.take());
2470 if (Result.isInvalid())
2471 return StmtError();
2472 RetValExp = Result.take();
2473 RetValExp = ImpCastExprToType(RetValExp,
2474 Context.VoidTy, CK_ToVoid).take();
2475 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002476
Nick Lewycky8d794612011-06-01 07:44:31 +00002477 // return (some void expression); is legal in C++.
2478 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002479 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002480 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002481
2482 int FunctionKind = 0;
2483 if (isa<ObjCMethodDecl>(CurDecl))
2484 FunctionKind = 1;
2485 else if (isa<CXXConstructorDecl>(CurDecl))
2486 FunctionKind = 2;
2487 else if (isa<CXXDestructorDecl>(CurDecl))
2488 FunctionKind = 3;
2489
Nick Lewycky8d794612011-06-01 07:44:31 +00002490 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002491 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002492 << RetValExp->getSourceRange();
2493 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002494 }
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Sebastian Redl33deb352012-02-22 10:50:08 +00002496 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002497 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2498 if (ER.isInvalid())
2499 return StmtError();
2500 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002501 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002503
Douglas Gregor5077c382010-05-15 06:01:05 +00002504 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2505 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002506 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2507 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002508 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002509
2510 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002511 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002512 else
Chris Lattner08631c52008-11-23 21:45:46 +00002513 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002514 Result = new (Context) ReturnStmt(ReturnLoc);
2515 } else {
2516 const VarDecl *NRVOCandidate = 0;
2517 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2518 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002519
Eli Friedman38ac2432012-03-30 01:13:43 +00002520 if (!RelatedRetType.isNull()) {
2521 // If we have a related result type, perform an extra conversion here.
2522 // FIXME: The diagnostics here don't really describe what is happening.
2523 InitializedEntity Entity =
2524 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002525
Eli Friedman38ac2432012-03-30 01:13:43 +00002526 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2527 RetValExp);
2528 if (Res.isInvalid()) {
2529 // FIXME: Cleanup temporaries here, anyway?
2530 return StmtError();
2531 }
2532 RetValExp = Res.takeAs<Expr>();
2533 }
2534
Douglas Gregor5077c382010-05-15 06:01:05 +00002535 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2536 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2537 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002538
John McCall856d3792011-06-16 23:24:51 +00002539 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002540 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002541 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002542 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002543 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002544 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002545 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002546 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002547 if (Res.isInvalid()) {
2548 // FIXME: Cleanup temporaries here, anyway?
2549 return StmtError();
2550 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002551
Douglas Gregor5077c382010-05-15 06:01:05 +00002552 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002553 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002554 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002555 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002556
John McCallb4eb64d2010-10-08 02:01:28 +00002557 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002558 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2559 if (ER.isInvalid())
2560 return StmtError();
2561 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002562 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002563 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002564 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002565
2566 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002567 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002568 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002569 !CurContext->isDependentContext())
2570 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002571
Douglas Gregor5077c382010-05-15 06:01:05 +00002572 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002573}
2574
John McCall60d7b3a2010-08-24 06:29:42 +00002575StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002576Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002577 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002578 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002579 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002580 if (Var && Var->isInvalidDecl())
2581 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002582
John McCall9ae2f072010-08-23 23:25:46 +00002583 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002584}
2585
John McCall60d7b3a2010-08-24 06:29:42 +00002586StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002587Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2588 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002589}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002590
John McCall60d7b3a2010-08-24 06:29:42 +00002591StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002592Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002593 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002594 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002595 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2596
John McCall781472f2010-08-25 08:40:02 +00002597 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002598 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002599 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002600 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002601 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002602 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002603}
2604
John McCalld1376ee2012-05-08 21:41:25 +00002605StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002606 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002607 ExprResult Result = DefaultLvalueConversion(Throw);
2608 if (Result.isInvalid())
2609 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002610
Richard Smith41956372013-01-14 22:39:08 +00002611 Result = ActOnFinishFullExpr(Result.take());
2612 if (Result.isInvalid())
2613 return StmtError();
2614 Throw = Result.take();
2615
Douglas Gregord1377b22010-04-22 21:44:01 +00002616 QualType ThrowType = Throw->getType();
2617 // Make sure the expression type is an ObjC pointer or "void *".
2618 if (!ThrowType->isDependentType() &&
2619 !ThrowType->isObjCObjectPointerType()) {
2620 const PointerType *PT = ThrowType->getAs<PointerType>();
2621 if (!PT || !PT->getPointeeType()->isVoidType())
2622 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2623 << Throw->getType() << Throw->getSourceRange());
2624 }
2625 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002626
John McCall9ae2f072010-08-23 23:25:46 +00002627 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002628}
2629
John McCall60d7b3a2010-08-24 06:29:42 +00002630StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002631Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002632 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002633 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002634 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2635
John McCall9ae2f072010-08-23 23:25:46 +00002636 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002637 // @throw without an expression designates a rethrow (which much occur
2638 // in the context of an @catch clause).
2639 Scope *AtCatchParent = CurScope;
2640 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2641 AtCatchParent = AtCatchParent->getParent();
2642 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002643 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002644 }
John McCall9ae2f072010-08-23 23:25:46 +00002645 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002646}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002647
John McCall07524032011-07-27 21:50:02 +00002648ExprResult
2649Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2650 ExprResult result = DefaultLvalueConversion(operand);
2651 if (result.isInvalid())
2652 return ExprError();
2653 operand = result.take();
2654
2655 // Make sure the expression type is an ObjC pointer or "void *".
2656 QualType type = operand->getType();
2657 if (!type->isDependentType() &&
2658 !type->isObjCObjectPointerType()) {
2659 const PointerType *pointerType = type->getAs<PointerType>();
2660 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2661 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2662 << type << operand->getSourceRange();
2663 }
2664
2665 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002666 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002667}
2668
John McCall60d7b3a2010-08-24 06:29:42 +00002669StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002670Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2671 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002672 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002673 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002674 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002675}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002676
2677/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2678/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002679StmtResult
John McCalld226f652010-08-21 09:40:31 +00002680Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002681 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002682 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002683 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002684 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002685 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002686}
Sebastian Redl8351da02008-12-22 21:35:02 +00002687
John McCallf85e1932011-06-15 23:02:42 +00002688StmtResult
2689Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2690 getCurFunction()->setHasBranchProtectedScope();
2691 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2692}
2693
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002694namespace {
2695
Sebastian Redlc447aba2009-07-29 17:15:45 +00002696class TypeWithHandler {
2697 QualType t;
2698 CXXCatchStmt *stmt;
2699public:
2700 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2701 : t(type), stmt(statement) {}
2702
John McCall0953e762009-09-24 19:53:00 +00002703 // An arbitrary order is fine as long as it places identical
2704 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002705 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002706 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002707 return true;
John McCall0953e762009-09-24 19:53:00 +00002708 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002709 return false;
2710 else
2711 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2712 }
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Sebastian Redlc447aba2009-07-29 17:15:45 +00002714 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002715 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002716 }
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Sebastian Redlc447aba2009-07-29 17:15:45 +00002718 CXXCatchStmt *getCatchStmt() const { return stmt; }
2719 SourceLocation getTypeSpecStartLoc() const {
2720 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2721 }
2722};
2723
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002724}
2725
Sebastian Redl8351da02008-12-22 21:35:02 +00002726/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2727/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002728StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002729Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002730 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002731 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002732 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002733 !getSourceManager().isInSystemHeader(TryLoc))
2734 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002735
Sebastian Redl8351da02008-12-22 21:35:02 +00002736 unsigned NumHandlers = RawHandlers.size();
2737 assert(NumHandlers > 0 &&
2738 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002739 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002740
Chris Lattner5f9e2722011-07-23 10:55:15 +00002741 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002742
2743 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002744 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002745 if (!Handler->getExceptionDecl()) {
2746 if (i < NumHandlers - 1)
2747 return StmtError(Diag(Handler->getLocStart(),
2748 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Sebastian Redlc447aba2009-07-29 17:15:45 +00002750 continue;
2751 }
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Sebastian Redlc447aba2009-07-29 17:15:45 +00002753 const QualType CaughtType = Handler->getCaughtType();
2754 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2755 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002756 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002757
2758 // Detect handlers for the same type as an earlier one.
2759 if (NumHandlers > 1) {
2760 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Sebastian Redlc447aba2009-07-29 17:15:45 +00002762 TypeWithHandler prev = TypesWithHandlers[0];
2763 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2764 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Sebastian Redlc447aba2009-07-29 17:15:45 +00002766 if (curr == prev) {
2767 Diag(curr.getTypeSpecStartLoc(),
2768 diag::warn_exception_caught_by_earlier_handler)
2769 << curr.getCatchStmt()->getCaughtType().getAsString();
2770 Diag(prev.getTypeSpecStartLoc(),
2771 diag::note_previous_exception_handler)
2772 << prev.getCatchStmt()->getCaughtType().getAsString();
2773 }
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Sebastian Redlc447aba2009-07-29 17:15:45 +00002775 prev = curr;
2776 }
2777 }
Mike Stump1eb44332009-09-09 15:08:12 +00002778
John McCall781472f2010-08-25 08:40:02 +00002779 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002780
Sebastian Redl8351da02008-12-22 21:35:02 +00002781 // FIXME: We should detect handlers that cannot catch anything because an
2782 // earlier handler catches a superclass. Need to find a method that is not
2783 // quadratic for this.
2784 // Neither of these are explicitly forbidden, but every compiler detects them
2785 // and warns.
2786
John McCall9ae2f072010-08-23 23:25:46 +00002787 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002788 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002789}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002790
2791StmtResult
2792Sema::ActOnSEHTryBlock(bool IsCXXTry,
2793 SourceLocation TryLoc,
2794 Stmt *TryBlock,
2795 Stmt *Handler) {
2796 assert(TryBlock && Handler);
2797
2798 getCurFunction()->setHasBranchProtectedScope();
2799
2800 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2801}
2802
2803StmtResult
2804Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2805 Expr *FilterExpr,
2806 Stmt *Block) {
2807 assert(FilterExpr && Block);
2808
2809 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002810 return StmtError(Diag(FilterExpr->getExprLoc(),
2811 diag::err_filter_expression_integral)
2812 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002813 }
2814
2815 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2816}
2817
2818StmtResult
2819Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2820 Stmt *Block) {
2821 assert(Block);
2822 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2823}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002824
2825StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2826 bool IsIfExists,
2827 NestedNameSpecifierLoc QualifierLoc,
2828 DeclarationNameInfo NameInfo,
2829 Stmt *Nested)
2830{
2831 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002832 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002833 cast<CompoundStmt>(Nested));
2834}
2835
2836
Chad Rosier1093f492012-08-10 17:56:09 +00002837StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002838 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002839 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002840 UnqualifiedId &Name,
2841 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002842 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002843 SS.getWithLocInContext(Context),
2844 GetNameFromUnqualifiedId(Name),
2845 Nested);
2846}