blob: 9b7ba04044ef98b1c05396f1afbeeb3ca9cae9a3 [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();
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000161 // In most cases, we don't want to warn if the expression is written in a
162 // macro body, or if the macro comes from a system header. If the offending
163 // expression is a call to a function with the warn_unused_result attribute,
164 // we warn no matter the location. Because of the order in which the various
165 // checks need to happen, we factor out the macro-related test here.
166 bool ShouldSuppress =
167 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
168 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson636463e2009-07-30 22:17:18 +0000169
Eli Friedmana6115062012-05-24 00:47:05 +0000170 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000171 SourceLocation Loc;
172 SourceRange R1, R2;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000173 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000174 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Chris Lattner06b3a062012-08-31 22:39:21 +0000176 // If this is a GNU statement expression expanded from a macro, it is probably
177 // unused because it is a function-like macro that can be used as either an
178 // expression or statement. Don't warn, because it is almost certainly a
179 // false positive.
180 if (isa<StmtExpr>(E) && Loc.isMacroID())
181 return;
182
Chris Lattner419cfb32009-08-16 16:57:27 +0000183 // Okay, we have an unused result. Depending on what the base expression is,
184 // we might want to make a more specific diagnostic. Check for one of these
185 // cases now.
186 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000187 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000188 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000189 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
190 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000191
Chandler Carruthec8058f2011-08-17 09:34:37 +0000192 if (DiagnoseUnusedComparison(*this, E))
193 return;
194
Eli Friedmana6115062012-05-24 00:47:05 +0000195 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000196 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000197 if (E->getType()->isVoidType())
198 return;
199
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000200 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000201 // a more specific message to make it clear what is happening. If the call
202 // is written in a macro body, only warn if it has the warn_unused_result
203 // attribute.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000204 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000205 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000206 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000207 return;
208 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000209 if (ShouldSuppress)
210 return;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000211 if (FD->getAttr<PureAttr>()) {
212 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
213 return;
214 }
215 if (FD->getAttr<ConstAttr>()) {
216 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
217 return;
218 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000219 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000220 } else if (ShouldSuppress)
221 return;
222
223 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000224 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000225 Diag(Loc, diag::err_arc_unused_init_message) << R1;
226 return;
227 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000228 const ObjCMethodDecl *MD = ME->getMethodDecl();
229 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000230 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000231 return;
232 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000233 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
234 const Expr *Source = POE->getSyntacticForm();
235 if (isa<ObjCSubscriptRefExpr>(Source))
236 DiagID = diag::warn_unused_container_subscript_expr;
237 else
238 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000239 } else if (const CXXFunctionalCastExpr *FC
240 = dyn_cast<CXXFunctionalCastExpr>(E)) {
241 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
242 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
243 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000244 }
John McCall209acbd2010-04-06 22:24:14 +0000245 // Diagnose "(void*) blah" as a typo for "(void) blah".
246 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
247 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
248 QualType T = TI->getType();
249
250 // We really do want to use the non-canonical type here.
251 if (T == Context.VoidPtrTy) {
David Blaikie39e6ab42013-02-18 22:06:02 +0000252 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall209acbd2010-04-06 22:24:14 +0000253
254 Diag(Loc, diag::warn_unused_voidptr)
255 << FixItHint::CreateRemoval(TL.getStarLoc());
256 return;
257 }
258 }
259
Eli Friedmana6115062012-05-24 00:47:05 +0000260 if (E->isGLValue() && E->getType().isVolatileQualified()) {
261 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
262 return;
263 }
264
Ted Kremenek351ba912011-02-23 01:52:04 +0000265 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000266}
267
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000268void Sema::ActOnStartOfCompoundStmt() {
269 PushCompoundScope();
270}
271
272void Sema::ActOnFinishOfCompoundStmt() {
273 PopCompoundScope();
274}
275
276sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
277 return getCurFunction()->CompoundScopes.back();
278}
279
John McCall60d7b3a2010-08-24 06:29:42 +0000280StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000281Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000282 MultiStmtArg elts, bool isStmtExpr) {
283 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000284 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000285 // If we're in C89 mode, check that we don't have any decls after stmts. If
286 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000287 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000288 // Note that __extension__ can be around a decl.
289 unsigned i = 0;
290 // Skip over all declarations.
291 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
292 /*empty*/;
293
294 // We found the end of the list or a statement. Scan for another declstmt.
295 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
296 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000298 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000299 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000300 Diag(D->getLocation(), diag::ext_mixed_decls_code);
301 }
302 }
Chris Lattner98414c12007-08-31 21:49:55 +0000303 // Warn about unused expressions in statements.
304 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000305 // Ignore statements that are last in a statement expression.
306 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000307 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Anders Carlsson636463e2009-07-30 22:17:18 +0000309 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000310 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000311
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000312 // Check for suspicious empty body (null statement) in `for' and `while'
313 // statements. Don't do anything for template instantiations, this just adds
314 // noise.
315 if (NumElts != 0 && !CurrentInstantiationScope &&
316 getCurCompoundScope().HasEmptyLoopBodies) {
317 for (unsigned i = 0; i != NumElts - 1; ++i)
318 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
319 }
320
Nico Weberd36aa352012-12-29 20:03:39 +0000321 return Owned(new (Context) CompoundStmt(Context,
322 llvm::makeArrayRef(Elts, NumElts),
323 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000324}
325
John McCall60d7b3a2010-08-24 06:29:42 +0000326StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000327Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
328 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000329 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000330 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000331
John McCall781472f2010-08-25 08:40:02 +0000332 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000333 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000334 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000335 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000336
Richard Smith80ad52f2013-01-02 11:42:31 +0000337 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000338 // C99 6.8.4.2p3: The expression shall be an integer constant.
339 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000340 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
341 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
342 if (!LHSVal)
343 return StmtError();
344 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000345
346 // GCC extension: The expression shall be an integer constant.
347
Richard Smith282e7e62012-02-04 09:53:13 +0000348 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
349 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
350 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000351 }
352 }
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000353
354 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
355 getLangOpts().CPlusPlus11).take();
356 if (RHSVal)
357 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
358 getLangOpts().CPlusPlus11).take();
Richard Smith8ef7b202012-01-18 23:55:52 +0000359
Douglas Gregordbb26db2009-05-15 23:57:33 +0000360 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
361 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000362 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000363 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
Chris Lattner24e1e702009-03-04 04:23:07 +0000366/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000367void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000368 DiagnoseUnusedExprResult(SubStmt);
369
Chris Lattner24e1e702009-03-04 04:23:07 +0000370 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000371 CS->setSubStmt(SubStmt);
372}
373
John McCall60d7b3a2010-08-24 06:29:42 +0000374StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000375Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000376 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000377 DiagnoseUnusedExprResult(SubStmt);
378
John McCall781472f2010-08-25 08:40:02 +0000379 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000380 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000381 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000382 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000383
Douglas Gregordbb26db2009-05-15 23:57:33 +0000384 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000385 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000386 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000387}
388
John McCall60d7b3a2010-08-24 06:29:42 +0000389StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000390Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
391 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000392 // If the label was multiply defined, reject it now.
393 if (TheDecl->getStmt()) {
394 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
395 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000396 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 }
Sebastian Redlde307472009-01-11 00:38:46 +0000398
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000399 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000400 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
401 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000402 if (!TheDecl->isGnuLocal()) {
403 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000404 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000405 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000406 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000407}
408
Richard Smith534986f2012-04-14 00:33:13 +0000409StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000410 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000411 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000412 // Fill in the declaration and return it.
413 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000414 return Owned(LS);
415}
416
John McCall60d7b3a2010-08-24 06:29:42 +0000417StmtResult
John McCalld226f652010-08-21 09:40:31 +0000418Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000419 Stmt *thenStmt, SourceLocation ElseLoc,
420 Stmt *elseStmt) {
Argyrios Kyrtzidis820b23d2013-02-15 18:34:13 +0000421 // If the condition was invalid, discard the if statement. We could recover
422 // better by replacing it with a valid expr, but don't do that yet.
423 if (!CondVal.get() && !CondVar) {
424 getCurFunction()->setHasDroppedStmt();
425 return StmtError();
426 }
427
John McCall60d7b3a2010-08-24 06:29:42 +0000428 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000430 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000431 if (CondVar) {
432 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000433 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000434 if (CondResult.isInvalid())
435 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000436 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000437 Expr *ConditionExpr = CondResult.takeAs<Expr>();
438 if (!ConditionExpr)
439 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000440
Anders Carlsson75443112009-07-30 22:39:03 +0000441 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000442
John McCall9ae2f072010-08-23 23:25:46 +0000443 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000444 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
445 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000446 }
447
Anders Carlsson75443112009-07-30 22:39:03 +0000448 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000449
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000451 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000452}
453
Chris Lattnerf4021e72007-08-23 05:46:52 +0000454/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
455/// the specified width and sign. If an overflow occurs, detect it and emit
456/// the specified diagnostic.
457void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
458 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000459 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000460 unsigned DiagID) {
461 // Perform a conversion to the promoted condition type if needed.
462 if (NewWidth > Val.getBitWidth()) {
463 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000464 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000465 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000466
467 // If the input was signed and negative and the output is
468 // unsigned, don't bother to warn: this is implementation-defined
469 // behavior.
470 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000471 } else if (NewWidth < Val.getBitWidth()) {
472 // If this is a truncation, check for overflow.
473 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000474 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000475 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000476 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000477 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000478 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000479 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnerf4021e72007-08-23 05:46:52 +0000481 // Regardless of whether a diagnostic was emitted, really do the
482 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000483 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000484 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000485 } else if (NewSign != Val.isSigned()) {
486 // Convert the sign to match the sign of the condition. This can cause
487 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000489 // behavior.
490 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000491 llvm::APSInt OldVal(Val);
492 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000493 }
494}
495
Chris Lattner0471f5b2007-08-23 18:29:20 +0000496namespace {
497 struct CaseCompareFunctor {
498 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
499 const llvm::APSInt &RHS) {
500 return LHS.first < RHS;
501 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000502 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
503 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
504 return LHS.first < RHS.first;
505 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000506 bool operator()(const llvm::APSInt &LHS,
507 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
508 return LHS < RHS.first;
509 }
510 };
511}
512
Chris Lattner764a7ce2007-09-21 18:15:22 +0000513/// CmpCaseVals - Comparison predicate for sorting case values.
514///
515static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
516 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
517 if (lhs.first < rhs.first)
518 return true;
519
520 if (lhs.first == rhs.first &&
521 lhs.second->getCaseLoc().getRawEncoding()
522 < rhs.second->getCaseLoc().getRawEncoding())
523 return true;
524 return false;
525}
526
Douglas Gregorba915af2010-02-08 22:24:16 +0000527/// CmpEnumVals - Comparison predicate for sorting enumeration values.
528///
529static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
530 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
531{
532 return lhs.first < rhs.first;
533}
534
535/// EqEnumVals - Comparison preficate for uniqing enumeration values.
536///
537static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
538 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
539{
540 return lhs.first == rhs.first;
541}
542
Chris Lattner5f048812009-10-16 16:45:22 +0000543/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
544/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000545static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
546 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
547 expr = cleanups->getSubExpr();
548 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
549 if (impcast->getCastKind() != CK_IntegralCast) break;
550 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000551 }
552 return expr->getType();
553}
554
John McCall60d7b3a2010-08-24 06:29:42 +0000555StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000557 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000558 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000559
Douglas Gregor586596f2010-05-06 17:25:47 +0000560 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000561 if (CondVar) {
562 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000563 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
564 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000565 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
John McCall9ae2f072010-08-23 23:25:46 +0000567 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000568 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569
John McCall9ae2f072010-08-23 23:25:46 +0000570 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000571 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
Douglas Gregorab41fe92012-05-04 22:38:52 +0000573 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
574 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000575
Douglas Gregorab41fe92012-05-04 22:38:52 +0000576 public:
577 SwitchConvertDiagnoser(Expr *Cond)
578 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000579
Douglas Gregorab41fe92012-05-04 22:38:52 +0000580 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
581 QualType T) {
582 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
583 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000584
Douglas Gregorab41fe92012-05-04 22:38:52 +0000585 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
586 QualType T) {
587 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
588 << T << Cond->getSourceRange();
589 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000590
Douglas Gregorab41fe92012-05-04 22:38:52 +0000591 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
592 QualType T,
593 QualType ConvTy) {
594 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
595 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000596
Douglas Gregorab41fe92012-05-04 22:38:52 +0000597 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
598 QualType ConvTy) {
599 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
600 << ConvTy->isEnumeralType() << ConvTy;
601 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000602
Douglas Gregorab41fe92012-05-04 22:38:52 +0000603 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
604 QualType T) {
605 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
606 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000607
Douglas Gregorab41fe92012-05-04 22:38:52 +0000608 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
609 QualType ConvTy) {
610 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
611 << ConvTy->isEnumeralType() << ConvTy;
612 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000613
Douglas Gregorab41fe92012-05-04 22:38:52 +0000614 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
615 QualType T,
616 QualType ConvTy) {
617 return DiagnosticBuilder::getEmpty();
618 }
619 } SwitchDiagnoser(Cond);
620
John McCall9ae2f072010-08-23 23:25:46 +0000621 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000622 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000623 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000624 if (CondResult.isInvalid()) return StmtError();
625 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
John McCalla8e0cd82011-08-06 07:30:58 +0000627 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
628 CondResult = UsualUnaryConversions(Cond);
629 if (CondResult.isInvalid()) return StmtError();
630 Cond = CondResult.take();
631
John McCalld226f652010-08-21 09:40:31 +0000632 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000633 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000634 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000635 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000636 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000637 }
John McCallb60a77e2010-08-01 00:26:45 +0000638
John McCall781472f2010-08-25 08:40:02 +0000639 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640
John McCall9ae2f072010-08-23 23:25:46 +0000641 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000642 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000643 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000644}
645
Gabor Greif28164ab2010-10-01 22:05:14 +0000646static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
647 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000648 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000649 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000650 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000651 Val.setIsSigned(IsSigned);
652}
653
John McCall60d7b3a2010-08-24 06:29:42 +0000654StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000655Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
656 Stmt *BodyStmt) {
657 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000658 assert(SS == getCurFunction()->SwitchStack.back() &&
659 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000660
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000661 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000662 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000663
Chris Lattnerf4021e72007-08-23 05:46:52 +0000664 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000665 if (!CondExpr) return StmtError();
666
667 QualType CondType = CondExpr->getType();
668
John McCall0fb97082010-05-18 03:19:21 +0000669 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000670 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000671 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000672
Chris Lattner5f048812009-10-16 16:45:22 +0000673 // C++ 6.4.2.p2:
674 // Integral promotions are performed (on the switch condition).
675 //
676 // A case value unrepresentable by the original switch condition
677 // type (before the promotion) doesn't make sense, even when it can
678 // be represented by the promoted type. Therefore we need to find
679 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000680 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000681 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000683 // appropriate type now, just return an error.
684 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000685 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000686
Chris Lattner2b334bb2010-04-16 23:34:13 +0000687 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000688 // switch(bool_expr) {...} is often a programmer error, e.g.
689 // switch(n && mask) { ... } // Doh - should be "n & mask".
690 // One can always use an if statement instead of switch(bool_expr).
691 Diag(SwitchLoc, diag::warn_bool_switch_condition)
692 << CondExpr->getSourceRange();
693 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000694 }
Sebastian Redlde307472009-01-11 00:38:46 +0000695
Chris Lattnerf4021e72007-08-23 05:46:52 +0000696 // Get the bitwidth of the switched-on value before promotions. We must
697 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000698 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000699 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000700 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000701 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000702 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000703 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Chris Lattnerf4021e72007-08-23 05:46:52 +0000705 // Accumulate all of the case values in a vector so that we can sort them
706 // and detect duplicates. This vector contains the APInt for the case after
707 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000708 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000709 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattnerf4021e72007-08-23 05:46:52 +0000711 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000712 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
713 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattnerf4021e72007-08-23 05:46:52 +0000715 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000717 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Douglas Gregordbb26db2009-05-15 23:57:33 +0000719 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000720 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000722 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000723 if (TheDefaultStmt) {
724 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000725 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000726
Chris Lattnerf4021e72007-08-23 05:46:52 +0000727 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000728 // we'll return a valid AST. This requires recursing down the AST and
729 // finding it, not something we are set up to do right now. For now,
730 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000731 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000732 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000733 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerf4021e72007-08-23 05:46:52 +0000735 } else {
736 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner1e0a3902008-01-16 19:17:22 +0000738 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000739
740 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
741 HasDependentValue = true;
742 break;
743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Richard Smith8ef7b202012-01-18 23:55:52 +0000745 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Richard Smith80ad52f2013-01-02 11:42:31 +0000747 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000748 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
749 // constant expression of the promoted type of the switch condition.
750 ExprResult ConvLo =
751 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
752 if (ConvLo.isInvalid()) {
753 CaseListIsErroneous = true;
754 continue;
755 }
756 Lo = ConvLo.take();
757 } else {
758 // We already verified that the expression has a i-c-e value (C99
759 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000760 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000761
762 // If the LHS is not the same type as the condition, insert an implicit
763 // cast.
764 Lo = DefaultLvalueConversion(Lo).take();
765 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
766 }
767
768 // Convert the value to the same width/sign as the condition had prior to
769 // integral promotions.
770 //
771 // FIXME: This causes us to reject valid code:
772 // switch ((char)c) { case 256: case 0: return 0; }
773 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000774 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000775 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000776 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000777
Chris Lattner1e0a3902008-01-16 19:17:22 +0000778 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000780 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000781 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000782 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000783 CS->getRHS()->isValueDependent()) {
784 HasDependentValue = true;
785 break;
786 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000787 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000788 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000789 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000790 }
791 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000792
793 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000794 // If we don't have a default statement, check whether the
795 // condition is constant.
796 llvm::APSInt ConstantCondValue;
797 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000798 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000799 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000800 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
801 Expr::SE_AllowSideEffects);
802 assert(!HasConstantCond ||
803 (ConstantCondValue.getBitWidth() == CondWidth &&
804 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000805 }
Richard Smith80d4b552011-12-28 19:48:30 +0000806 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000807
Douglas Gregordbb26db2009-05-15 23:57:33 +0000808 // Sort all the scalar case values so we can easily detect duplicates.
809 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
810
811 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000812 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
813 if (ShouldCheckConstantCond &&
814 CaseVals[i].first == ConstantCondValue)
815 ShouldCheckConstantCond = false;
816
817 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000818 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000819 // First, determine if either case value has a name
820 StringRef PrevString, CurrString;
821 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
822 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
823 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
824 PrevString = DeclRef->getDecl()->getName();
825 }
826 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
827 CurrString = DeclRef->getDecl()->getName();
828 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000829 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000830 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000831
832 if (PrevString == CurrString)
833 Diag(CaseVals[i].second->getLHS()->getLocStart(),
834 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000835 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000836 else
837 Diag(CaseVals[i].second->getLHS()->getLocStart(),
838 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000839 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
840 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000841 CaseValStr;
842
John McCall0fb97082010-05-18 03:19:21 +0000843 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000844 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000845 // FIXME: We really want to remove the bogus case stmt from the
846 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000847 CaseListIsErroneous = true;
848 }
849 }
850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregordbb26db2009-05-15 23:57:33 +0000852 // Detect duplicate case ranges, which usually don't exist at all in
853 // the first place.
854 if (!CaseRanges.empty()) {
855 // Sort all the case ranges by their low value so we can easily detect
856 // overlaps between ranges.
857 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregordbb26db2009-05-15 23:57:33 +0000859 // Scan the ranges, computing the high values and removing empty ranges.
860 std::vector<llvm::APSInt> HiVals;
861 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000862 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000863 CaseStmt *CR = CaseRanges[i].second;
864 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000865 llvm::APSInt HiVal;
866
Richard Smith80ad52f2013-01-02 11:42:31 +0000867 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000868 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
869 // constant expression of the promoted type of the switch condition.
870 ExprResult ConvHi =
871 CheckConvertedConstantExpression(Hi, CondType, HiVal,
872 CCEK_CaseValue);
873 if (ConvHi.isInvalid()) {
874 CaseListIsErroneous = true;
875 continue;
876 }
877 Hi = ConvHi.take();
878 } else {
879 HiVal = Hi->EvaluateKnownConstInt(Context);
880
881 // If the RHS is not the same type as the condition, insert an
882 // implicit cast.
883 Hi = DefaultLvalueConversion(Hi).take();
884 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Douglas Gregordbb26db2009-05-15 23:57:33 +0000887 // Convert the value to the same width/sign as the condition.
888 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000889 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000890 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregordbb26db2009-05-15 23:57:33 +0000892 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Douglas Gregordbb26db2009-05-15 23:57:33 +0000894 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000895 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000896 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
897 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000898 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000899 CaseRanges.erase(CaseRanges.begin()+i);
900 --i, --e;
901 continue;
902 }
John McCall0fb97082010-05-18 03:19:21 +0000903
904 if (ShouldCheckConstantCond &&
905 LoVal <= ConstantCondValue &&
906 ConstantCondValue <= HiVal)
907 ShouldCheckConstantCond = false;
908
Douglas Gregordbb26db2009-05-15 23:57:33 +0000909 HiVals.push_back(HiVal);
910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Douglas Gregordbb26db2009-05-15 23:57:33 +0000912 // Rescan the ranges, looking for overlap with singleton values and other
913 // ranges. Since the range list is sorted, we only need to compare case
914 // ranges with their neighbors.
915 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
916 llvm::APSInt &CRLo = CaseRanges[i].first;
917 llvm::APSInt &CRHi = HiVals[i];
918 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregordbb26db2009-05-15 23:57:33 +0000920 // Check to see whether the case range overlaps with any
921 // singleton cases.
922 CaseStmt *OverlapStmt = 0;
923 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Douglas Gregordbb26db2009-05-15 23:57:33 +0000925 // Find the smallest value >= the lower bound. If I is in the
926 // case range, then we have overlap.
927 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
928 CaseVals.end(), CRLo,
929 CaseCompareFunctor());
930 if (I != CaseVals.end() && I->first < CRHi) {
931 OverlapVal = I->first; // Found overlap with scalar.
932 OverlapStmt = I->second;
933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregordbb26db2009-05-15 23:57:33 +0000935 // Find the smallest value bigger than the upper bound.
936 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
937 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
938 OverlapVal = (I-1)->first; // Found overlap with scalar.
939 OverlapStmt = (I-1)->second;
940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Douglas Gregordbb26db2009-05-15 23:57:33 +0000942 // Check to see if this case stmt overlaps with the subsequent
943 // case range.
944 if (i && CRLo <= HiVals[i-1]) {
945 OverlapVal = HiVals[i-1]; // Found overlap with range.
946 OverlapStmt = CaseRanges[i-1].second;
947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Douglas Gregordbb26db2009-05-15 23:57:33 +0000949 if (OverlapStmt) {
950 // If we have a duplicate, report it.
951 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
952 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000953 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000954 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000955 // FIXME: We really want to remove the bogus case stmt from the
956 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000957 CaseListIsErroneous = true;
958 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000959 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000960 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000961
John McCall0fb97082010-05-18 03:19:21 +0000962 // Complain if we have a constant condition and we didn't find a match.
963 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
964 // TODO: it would be nice if we printed enums as enums, chars as
965 // chars, etc.
966 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
967 << ConstantCondValue.toString(10)
968 << CondExpr->getSourceRange();
969 }
970
971 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000972 // values. We only issue a warning if there is not 'default:', but
973 // we still do the analysis to preserve this information in the AST
974 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000975 //
Chris Lattnerce784612010-09-16 17:09:42 +0000976 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000977
Douglas Gregorba915af2010-02-08 22:24:16 +0000978 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000979 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000980 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000981 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000982 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000983 EnumValsTy EnumVals;
984
John McCall0fb97082010-05-18 03:19:21 +0000985 // Gather all enum values, set their type and sort them,
986 // allowing easier comparison with CaseVals.
987 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000988 EDI != ED->enumerator_end(); ++EDI) {
989 llvm::APSInt Val = EDI->getInitVal();
990 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000991 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000992 }
993 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000994 EnumValsTy::iterator EIend =
995 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000996
997 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000998 EnumValsTy::const_iterator EI = EnumVals.begin();
999 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1000 CI != CaseVals.end(); CI++) {
1001 while (EI != EIend && EI->first < CI->first)
1002 EI++;
1003 if (EI == EIend || EI->first > CI->first)
1004 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001005 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +00001006 }
1007 // See which of case ranges aren't in enum
1008 EI = EnumVals.begin();
1009 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1010 RI != CaseRanges.end() && EI != EIend; RI++) {
1011 while (EI != EIend && EI->first < RI->first)
1012 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
David Blaikie93667502012-01-22 02:31:55 +00001014 if (EI == EIend || EI->first != RI->first) {
1015 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001016 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001017 }
David Blaikie93667502012-01-22 02:31:55 +00001018
Chad Rosier1093f492012-08-10 17:56:09 +00001019 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001020 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1021 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1022 while (EI != EIend && EI->first < Hi)
1023 EI++;
1024 if (EI == EIend || EI->first != Hi)
1025 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001026 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001027 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
Ted Kremenek559fb552010-09-09 00:05:53 +00001029 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001030 CaseValsTy::const_iterator CI = CaseVals.begin();
1031 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001032 bool hasCasesNotInSwitch = false;
1033
Chris Lattner5f9e2722011-07-23 10:55:15 +00001034 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
David Blaikie93667502012-01-22 02:31:55 +00001036 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001037 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001038 llvm::APSInt CIVal;
1039 while (CI != CaseVals.end() && CI->first < EI->first)
1040 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001041
Douglas Gregorba915af2010-02-08 22:24:16 +00001042 if (CI != CaseVals.end() && CI->first == EI->first)
1043 continue;
1044
Ted Kremenek559fb552010-09-09 00:05:53 +00001045 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001046 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001047 llvm::APSInt Hi =
1048 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001049 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001050 if (EI->first <= Hi)
1051 break;
1052 }
1053
Ted Kremenek559fb552010-09-09 00:05:53 +00001054 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001055 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001056 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001057 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001058 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001059
David Blaikie585d7792012-01-23 04:46:12 +00001060 if (TheDefaultStmt && UnhandledNames.empty())
1061 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001062
Chris Lattnerce784612010-09-16 17:09:42 +00001063 // Produce a nice diagnostic if multiple values aren't handled.
1064 switch (UnhandledNames.size()) {
1065 case 0: break;
1066 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001067 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001068 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001069 << UnhandledNames[0];
1070 break;
1071 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001072 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001073 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001074 << UnhandledNames[0] << UnhandledNames[1];
1075 break;
1076 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001077 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1078 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001079 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1080 break;
1081 default:
David Blaikie585d7792012-01-23 04:46:12 +00001082 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1083 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001084 << (unsigned)UnhandledNames.size()
1085 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1086 break;
1087 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001088
1089 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001090 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001091 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001092 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001093
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001094 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1095 diag::warn_empty_switch_body);
1096
Mike Stump390b4cc2009-05-16 07:39:55 +00001097 // FIXME: If the case list was broken is some way, we don't have a good system
1098 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001099 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001100 return StmtError();
1101
Sebastian Redlde307472009-01-11 00:38:46 +00001102 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001103}
1104
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001105void
1106Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1107 Expr *SrcExpr) {
1108 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001109 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001110 == DiagnosticsEngine::Ignored)
1111 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001112
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001113 if (const EnumType *ET = DstType->getAs<EnumType>())
1114 if (!Context.hasSameType(SrcType, DstType) &&
1115 SrcType->isIntegerType()) {
1116 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1117 SrcExpr->isIntegerConstantExpr(Context)) {
1118 // Get the bitwidth of the enum value before promotions.
1119 unsigned DstWith = Context.getIntWidth(DstType);
1120 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1121
1122 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1123 const EnumDecl *ED = ET->getDecl();
1124 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1125 EnumValsTy;
1126 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001127
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001128 // Gather all enum values, set their type and sort them,
1129 // allowing easier comparison with rhs constant.
1130 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1131 EDI != ED->enumerator_end(); ++EDI) {
1132 llvm::APSInt Val = EDI->getInitVal();
1133 AdjustAPSInt(Val, DstWith, DstIsSigned);
1134 EnumVals.push_back(std::make_pair(Val, *EDI));
1135 }
1136 if (EnumVals.empty())
1137 return;
1138 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1139 EnumValsTy::iterator EIend =
1140 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001141
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001142 // See which case values aren't in enum.
1143 EnumValsTy::const_iterator EI = EnumVals.begin();
1144 while (EI != EIend && EI->first < RhsVal)
1145 EI++;
1146 if (EI == EIend || EI->first != RhsVal) {
1147 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1148 << DstType;
1149 }
1150 }
1151 }
1152}
1153
John McCall60d7b3a2010-08-24 06:29:42 +00001154StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001156 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001157 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001158
Douglas Gregor5656e142009-11-24 21:15:44 +00001159 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001160 if (CondVar) {
1161 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001162 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001163 if (CondResult.isInvalid())
1164 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001165 }
John McCall9ae2f072010-08-23 23:25:46 +00001166 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001167 if (!ConditionExpr)
1168 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001169
John McCall9ae2f072010-08-23 23:25:46 +00001170 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001172 if (isa<NullStmt>(Body))
1173 getCurCompoundScope().setHasEmptyLoopBodies();
1174
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001175 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001176 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001177}
1178
John McCall60d7b3a2010-08-24 06:29:42 +00001179StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001180Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001181 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001182 Expr *Cond, SourceLocation CondRParen) {
1183 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001184
John Wiegley429bb272011-04-08 18:41:53 +00001185 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001186 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001187 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001188 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001189
Richard Smith41956372013-01-14 22:39:08 +00001190 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001191 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001192 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001193 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194
John McCall9ae2f072010-08-23 23:25:46 +00001195 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001196
John McCall9ae2f072010-08-23 23:25:46 +00001197 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001198}
1199
Richard Trieu694e7962012-04-30 18:01:30 +00001200namespace {
1201 // This visitor will traverse a conditional statement and store all
1202 // the evaluated decls into a vector. Simple is set to true if none
1203 // of the excluded constructs are used.
1204 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1205 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001206 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001207 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001208public:
1209 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1210
1211 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001212 SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001213 Inherited(S.Context),
1214 Decls(Decls),
1215 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001216 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001217
1218 bool isSimple() { return Simple; }
1219
1220 // Replaces the method in EvaluatedExprVisitor.
1221 void VisitMemberExpr(MemberExpr* E) {
1222 Simple = false;
1223 }
1224
1225 // Any Stmt not whitelisted will cause the condition to be marked complex.
1226 void VisitStmt(Stmt *S) {
1227 Simple = false;
1228 }
1229
1230 void VisitBinaryOperator(BinaryOperator *E) {
1231 Visit(E->getLHS());
1232 Visit(E->getRHS());
1233 }
1234
1235 void VisitCastExpr(CastExpr *E) {
1236 Visit(E->getSubExpr());
1237 }
1238
1239 void VisitUnaryOperator(UnaryOperator *E) {
1240 // Skip checking conditionals with derefernces.
1241 if (E->getOpcode() == UO_Deref)
1242 Simple = false;
1243 else
1244 Visit(E->getSubExpr());
1245 }
1246
1247 void VisitConditionalOperator(ConditionalOperator *E) {
1248 Visit(E->getCond());
1249 Visit(E->getTrueExpr());
1250 Visit(E->getFalseExpr());
1251 }
1252
1253 void VisitParenExpr(ParenExpr *E) {
1254 Visit(E->getSubExpr());
1255 }
1256
1257 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1258 Visit(E->getOpaqueValue()->getSourceExpr());
1259 Visit(E->getFalseExpr());
1260 }
1261
1262 void VisitIntegerLiteral(IntegerLiteral *E) { }
1263 void VisitFloatingLiteral(FloatingLiteral *E) { }
1264 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1265 void VisitCharacterLiteral(CharacterLiteral *E) { }
1266 void VisitGNUNullExpr(GNUNullExpr *E) { }
1267 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1268
1269 void VisitDeclRefExpr(DeclRefExpr *E) {
1270 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1271 if (!VD) return;
1272
1273 Ranges.push_back(E->getSourceRange());
1274
1275 Decls.insert(VD);
1276 }
1277
1278 }; // end class DeclExtractor
1279
1280 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001281 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001282 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1283 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1284 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001285
1286public:
1287 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1288
1289 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1290 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1291 if (!Statement) return;
1292
1293 Visit(Statement);
1294 }
1295
1296 void VisitReturnStmt(ReturnStmt *S) {
1297 FoundDecl = true;
1298 }
1299
1300 void VisitBreakStmt(BreakStmt *S) {
1301 FoundDecl = true;
1302 }
1303
1304 void VisitGotoStmt(GotoStmt *S) {
1305 FoundDecl = true;
1306 }
1307
1308 void VisitCastExpr(CastExpr *E) {
1309 if (E->getCastKind() == CK_LValueToRValue)
1310 CheckLValueToRValueCast(E->getSubExpr());
1311 else
1312 Visit(E->getSubExpr());
1313 }
1314
1315 void CheckLValueToRValueCast(Expr *E) {
1316 E = E->IgnoreParenImpCasts();
1317
1318 if (isa<DeclRefExpr>(E)) {
1319 return;
1320 }
1321
1322 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1323 Visit(CO->getCond());
1324 CheckLValueToRValueCast(CO->getTrueExpr());
1325 CheckLValueToRValueCast(CO->getFalseExpr());
1326 return;
1327 }
1328
1329 if (BinaryConditionalOperator *BCO =
1330 dyn_cast<BinaryConditionalOperator>(E)) {
1331 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1332 CheckLValueToRValueCast(BCO->getFalseExpr());
1333 return;
1334 }
1335
1336 Visit(E);
1337 }
1338
1339 void VisitDeclRefExpr(DeclRefExpr *E) {
1340 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1341 if (Decls.count(VD))
1342 FoundDecl = true;
1343 }
1344
1345 bool FoundDeclInUse() { return FoundDecl; }
1346
1347 }; // end class DeclMatcher
1348
1349 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1350 Expr *Third, Stmt *Body) {
1351 // Condition is empty
1352 if (!Second) return;
1353
1354 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1355 Second->getLocStart())
1356 == DiagnosticsEngine::Ignored)
1357 return;
1358
1359 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1360 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001361 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001362 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001363 DE.Visit(Second);
1364
1365 // Don't analyze complex conditionals.
1366 if (!DE.isSimple()) return;
1367
1368 // No decls found.
1369 if (Decls.size() == 0) return;
1370
Richard Trieu90875992012-05-04 03:01:54 +00001371 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001372 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1373 E = Decls.end();
1374 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001375 if ((*I)->getType().isVolatileQualified() ||
1376 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001377
1378 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1379 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1380 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1381 return;
1382
1383 // Load decl names into diagnostic.
1384 if (Decls.size() > 4)
1385 PDiag << 0;
1386 else {
1387 PDiag << Decls.size();
1388 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1389 E = Decls.end();
1390 I != E; ++I)
1391 PDiag << (*I)->getDeclName();
1392 }
1393
1394 // Load SourceRanges into diagnostic if there is room.
1395 // Otherwise, load the SourceRange of the conditional expression.
1396 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001397 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1398 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001399 I != E; ++I)
1400 PDiag << *I;
1401 else
1402 PDiag << Second->getSourceRange();
1403
1404 S.Diag(Ranges.begin()->getBegin(), PDiag);
1405 }
1406
1407} // end namespace
1408
John McCall60d7b3a2010-08-24 06:29:42 +00001409StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001410Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001411 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001412 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001413 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001414 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001415 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001416 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1417 // declare identifiers for objects having storage class 'auto' or
1418 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001419 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1420 DI!=DE; ++DI) {
1421 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001422 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001423 VD = 0;
1424 if (VD == 0)
1425 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1426 // FIXME: mark decl erroneous!
1427 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001428 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001430
Richard Trieu694e7962012-04-30 18:01:30 +00001431 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1432
John McCall60d7b3a2010-08-24 06:29:42 +00001433 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001434 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001435 if (secondVar) {
1436 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001437 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001438 if (SecondResult.isInvalid())
1439 return StmtError();
1440 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001441
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001442 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001443
Anders Carlsson3af708f2009-08-01 01:39:59 +00001444 DiagnoseUnusedExprResult(First);
1445 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001446 DiagnoseUnusedExprResult(Body);
1447
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001448 if (isa<NullStmt>(Body))
1449 getCurCompoundScope().setHasEmptyLoopBodies();
1450
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451 return Owned(new (Context) ForStmt(Context, First,
1452 SecondResult.take(), ConditionVar,
1453 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001454 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001455}
1456
John McCallf6a16482010-12-04 03:47:34 +00001457/// In an Objective C collection iteration statement:
1458/// for (x in y)
1459/// x can be an arbitrary l-value expression. Bind it up as a
1460/// full-expression.
1461StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001462 // Reduce placeholder expressions here. Note that this rejects the
1463 // use of pseudo-object l-values in this position.
1464 ExprResult result = CheckPlaceholderExpr(E);
1465 if (result.isInvalid()) return StmtError();
1466 E = result.take();
1467
Richard Smith41956372013-01-14 22:39:08 +00001468 ExprResult FullExpr = ActOnFinishFullExpr(E);
1469 if (FullExpr.isInvalid())
1470 return StmtError();
1471 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001472}
1473
John McCall990567c2011-07-27 01:07:15 +00001474ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001475Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1476 if (!collection)
1477 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001478
John McCall990567c2011-07-27 01:07:15 +00001479 // Bail out early if we've got a type-dependent expression.
1480 if (collection->isTypeDependent()) return Owned(collection);
1481
1482 // Perform normal l-value conversion.
1483 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1484 if (result.isInvalid())
1485 return ExprError();
1486 collection = result.take();
1487
1488 // The operand needs to have object-pointer type.
1489 // TODO: should we do a contextual conversion?
1490 const ObjCObjectPointerType *pointerType =
1491 collection->getType()->getAs<ObjCObjectPointerType>();
1492 if (!pointerType)
1493 return Diag(forLoc, diag::err_collection_expr_type)
1494 << collection->getType() << collection->getSourceRange();
1495
1496 // Check that the operand provides
1497 // - countByEnumeratingWithState:objects:count:
1498 const ObjCObjectType *objectType = pointerType->getObjectType();
1499 ObjCInterfaceDecl *iface = objectType->getInterface();
1500
1501 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001502 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001503 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001504 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001505 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001506 ? diag::err_arc_collection_forward
1507 : 0,
1508 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001509 // Otherwise, if we have any useful type information, check that
1510 // the type declares the appropriate method.
1511 } else if (iface || !objectType->qual_empty()) {
1512 IdentifierInfo *selectorIdents[] = {
1513 &Context.Idents.get("countByEnumeratingWithState"),
1514 &Context.Idents.get("objects"),
1515 &Context.Idents.get("count")
1516 };
1517 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1518
1519 ObjCMethodDecl *method = 0;
1520
1521 // If there's an interface, look in both the public and private APIs.
1522 if (iface) {
1523 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001524 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001525 }
1526
1527 // Also check protocol qualifiers.
1528 if (!method)
1529 method = LookupMethodInQualifiedType(selector, pointerType,
1530 /*instance*/ true);
1531
1532 // If we didn't find it anywhere, give up.
1533 if (!method) {
1534 Diag(forLoc, diag::warn_collection_expr_type)
1535 << collection->getType() << selector << collection->getSourceRange();
1536 }
1537
1538 // TODO: check for an incompatible signature?
1539 }
1540
1541 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001542 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001543}
1544
John McCall60d7b3a2010-08-24 06:29:42 +00001545StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001546Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001547 Stmt *First, Expr *collection,
1548 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001549
1550 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001551 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001552
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001553 if (First) {
1554 QualType FirstType;
1555 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001556 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001557 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1558 diag::err_toomany_element_decls));
1559
John McCallf85e1932011-06-15 23:02:42 +00001560 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1561 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001562 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1563 // declare identifiers for objects having storage class 'auto' or
1564 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001565 if (!D->hasLocalStorage())
1566 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001567 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001568 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001569 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001570 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001571 return StmtError(Diag(First->getLocStart(),
1572 diag::err_selector_element_not_lvalue)
1573 << First->getSourceRange());
1574
Mike Stump1eb44332009-09-09 15:08:12 +00001575 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001576 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001577 if (!FirstType->isDependentType() &&
1578 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001579 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001580 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1581 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001582 }
Chad Rosier1093f492012-08-10 17:56:09 +00001583
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001584 if (CollectionExprResult.isInvalid())
1585 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001586
Richard Smith41956372013-01-14 22:39:08 +00001587 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1588 if (CollectionExprResult.isInvalid())
1589 return StmtError();
1590
Chad Rosier1093f492012-08-10 17:56:09 +00001591 return Owned(new (Context) ObjCForCollectionStmt(First,
1592 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001593 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001594}
Reid Spencer5f016e22007-07-11 17:01:13 +00001595
Richard Smithad762fc2011-04-14 22:09:26 +00001596/// Finish building a variable declaration for a for-range statement.
1597/// \return true if an error occurs.
1598static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1599 SourceLocation Loc, int diag) {
1600 // Deduce the type for the iterator variable now rather than leaving it to
1601 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1602 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001603 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001604 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1605 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001606 SemaRef.Diag(Loc, diag) << Init->getType();
1607 if (!InitTSI) {
1608 Decl->setInvalidDecl();
1609 return true;
1610 }
1611 Decl->setTypeSourceInfo(InitTSI);
1612 Decl->setType(InitTSI->getType());
1613
John McCallf85e1932011-06-15 23:02:42 +00001614 // In ARC, infer lifetime.
1615 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1616 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001617 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001618 SemaRef.inferObjCARCLifetime(Decl))
1619 Decl->setInvalidDecl();
1620
Richard Smithad762fc2011-04-14 22:09:26 +00001621 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1622 /*TypeMayContainAuto=*/false);
1623 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001624 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001625 return false;
1626}
1627
Sam Panzere1715b62012-08-21 00:52:01 +00001628namespace {
1629
Richard Smithad762fc2011-04-14 22:09:26 +00001630/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001631/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001632/// nor from the diagnostics produced when analysing the implicit expressions
1633/// required in a for-range statement.
1634void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001635 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001636 CallExpr *CE = dyn_cast<CallExpr>(E);
1637 if (!CE)
1638 return;
1639 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1640 if (!D)
1641 return;
1642 SourceLocation Loc = D->getLocation();
1643
1644 std::string Description;
1645 bool IsTemplate = false;
1646 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1647 Description = SemaRef.getTemplateArgumentBindingsText(
1648 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1649 IsTemplate = true;
1650 }
1651
1652 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1653 << BEF << IsTemplate << Description << E->getType();
1654}
1655
Sam Panzere1715b62012-08-21 00:52:01 +00001656/// Build a variable declaration for a for-range statement.
1657VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1658 QualType Type, const char *Name) {
1659 DeclContext *DC = SemaRef.CurContext;
1660 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1661 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1662 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1663 TInfo, SC_Auto, SC_None);
1664 Decl->setImplicit();
1665 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001666}
1667
1668}
1669
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001670static bool ObjCEnumerationCollection(Expr *Collection) {
1671 return !Collection->isTypeDependent()
1672 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1673}
1674
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001675/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001676///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001677/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001678/// A range-based for statement is equivalent to
1679///
1680/// {
1681/// auto && __range = range-init;
1682/// for ( auto __begin = begin-expr,
1683/// __end = end-expr;
1684/// __begin != __end;
1685/// ++__begin ) {
1686/// for-range-declaration = *__begin;
1687/// statement
1688/// }
1689/// }
1690///
1691/// The body of the loop is not available yet, since it cannot be analysed until
1692/// we have determined the type of the for-range-declaration.
1693StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001694Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001695 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001696 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001697 if (!First || !Range)
1698 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001699
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001700 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001701 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001702
1703 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1704 assert(DS && "first part of for range not a decl stmt");
1705
1706 if (!DS->isSingleDecl()) {
1707 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1708 return StmtError();
1709 }
1710 if (DS->getSingleDecl()->isInvalidDecl())
1711 return StmtError();
1712
1713 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1714 return StmtError();
1715
1716 // Build auto && __range = range-init
1717 SourceLocation RangeLoc = Range->getLocStart();
1718 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1719 Context.getAutoRRefDeductType(),
1720 "__range");
1721 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1722 diag::err_for_range_deduction_failure))
1723 return StmtError();
1724
1725 // Claim the type doesn't contain auto: we've already done the checking.
1726 DeclGroupPtrTy RangeGroup =
1727 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1728 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1729 if (RangeDecl.isInvalid())
1730 return StmtError();
1731
1732 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1733 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001734 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001735}
1736
1737/// \brief Create the initialization, compare, and increment steps for
1738/// the range-based for loop expression.
1739/// This function does not handle array-based for loops,
1740/// which are created in Sema::BuildCXXForRangeStmt.
1741///
1742/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1743/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1744/// CandidateSet and BEF are set and some non-success value is returned on
1745/// failure.
1746static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1747 Expr *BeginRange, Expr *EndRange,
1748 QualType RangeType,
1749 VarDecl *BeginVar,
1750 VarDecl *EndVar,
1751 SourceLocation ColonLoc,
1752 OverloadCandidateSet *CandidateSet,
1753 ExprResult *BeginExpr,
1754 ExprResult *EndExpr,
1755 Sema::BeginEndFunction *BEF) {
1756 DeclarationNameInfo BeginNameInfo(
1757 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1758 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1759 ColonLoc);
1760
1761 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1762 Sema::LookupMemberName);
1763 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1764
1765 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1766 // - if _RangeT is a class type, the unqualified-ids begin and end are
1767 // looked up in the scope of class _RangeT as if by class member access
1768 // lookup (3.4.5), and if either (or both) finds at least one
1769 // declaration, begin-expr and end-expr are __range.begin() and
1770 // __range.end(), respectively;
1771 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1772 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1773
1774 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1775 SourceLocation RangeLoc = BeginVar->getLocation();
1776 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1777
1778 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1779 << RangeLoc << BeginRange->getType() << *BEF;
1780 return Sema::FRS_DiagnosticIssued;
1781 }
1782 } else {
1783 // - otherwise, begin-expr and end-expr are begin(__range) and
1784 // end(__range), respectively, where begin and end are looked up with
1785 // argument-dependent lookup (3.4.2). For the purposes of this name
1786 // lookup, namespace std is an associated namespace.
1787
1788 }
1789
1790 *BEF = Sema::BEF_begin;
1791 Sema::ForRangeStatus RangeStatus =
1792 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1793 Sema::BEF_begin, BeginNameInfo,
1794 BeginMemberLookup, CandidateSet,
1795 BeginRange, BeginExpr);
1796
1797 if (RangeStatus != Sema::FRS_Success)
1798 return RangeStatus;
1799 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1800 diag::err_for_range_iter_deduction_failure)) {
1801 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1802 return Sema::FRS_DiagnosticIssued;
1803 }
1804
1805 *BEF = Sema::BEF_end;
1806 RangeStatus =
1807 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1808 Sema::BEF_end, EndNameInfo,
1809 EndMemberLookup, CandidateSet,
1810 EndRange, EndExpr);
1811 if (RangeStatus != Sema::FRS_Success)
1812 return RangeStatus;
1813 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1814 diag::err_for_range_iter_deduction_failure)) {
1815 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1816 return Sema::FRS_DiagnosticIssued;
1817 }
1818 return Sema::FRS_Success;
1819}
1820
1821/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001822/// If the attempt fails, this function will return a valid, null StmtResult
1823/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001824static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1825 SourceLocation ForLoc,
1826 Stmt *LoopVarDecl,
1827 SourceLocation ColonLoc,
1828 Expr *Range,
1829 SourceLocation RangeLoc,
1830 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001831 // Determine whether we can rebuild the for-range statement with a
1832 // dereferenced range expression.
1833 ExprResult AdjustedRange;
1834 {
1835 Sema::SFINAETrap Trap(SemaRef);
1836
1837 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1838 if (AdjustedRange.isInvalid())
1839 return StmtResult();
1840
1841 StmtResult SR =
1842 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1843 AdjustedRange.get(), RParenLoc,
1844 Sema::BFRK_Check);
1845 if (SR.isInvalid())
1846 return StmtResult();
1847 }
1848
1849 // The attempt to dereference worked well enough that it could produce a valid
1850 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1851 // case there are any other (non-fatal) problems with it.
1852 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1853 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1854 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1855 AdjustedRange.get(), RParenLoc,
1856 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001857}
1858
Richard Smith8b533d92012-09-20 21:52:32 +00001859/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001860StmtResult
1861Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1862 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1863 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001864 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001865 Scope *S = getCurScope();
1866
1867 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1868 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1869 QualType RangeVarType = RangeVar->getType();
1870
1871 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1872 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1873
1874 StmtResult BeginEndDecl = BeginEnd;
1875 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1876
1877 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1878 SourceLocation RangeLoc = RangeVar->getLocation();
1879
Ted Kremeneke50b0152011-10-10 22:36:28 +00001880 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1881
1882 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1883 VK_LValue, ColonLoc);
1884 if (BeginRangeRef.isInvalid())
1885 return StmtError();
1886
1887 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1888 VK_LValue, ColonLoc);
1889 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001890 return StmtError();
1891
1892 QualType AutoType = Context.getAutoDeductType();
1893 Expr *Range = RangeVar->getInit();
1894 if (!Range)
1895 return StmtError();
1896 QualType RangeType = Range->getType();
1897
1898 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001899 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001900 return StmtError();
1901
1902 // Build auto __begin = begin-expr, __end = end-expr.
1903 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1904 "__begin");
1905 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1906 "__end");
1907
1908 // Build begin-expr and end-expr and attach to __begin and __end variables.
1909 ExprResult BeginExpr, EndExpr;
1910 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1911 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1912 // __range + __bound, respectively, where __bound is the array bound. If
1913 // _RangeT is an array of unknown size or an array of incomplete type,
1914 // the program is ill-formed;
1915
1916 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001917 BeginExpr = BeginRangeRef;
1918 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001919 diag::err_for_range_iter_deduction_failure)) {
1920 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1921 return StmtError();
1922 }
1923
1924 // Find the array bound.
1925 ExprResult BoundExpr;
1926 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1927 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001928 Context.getPointerDiffType(),
1929 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001930 else if (const VariableArrayType *VAT =
1931 dyn_cast<VariableArrayType>(UnqAT))
1932 BoundExpr = VAT->getSizeExpr();
1933 else {
1934 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1935 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001936 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001937 }
1938
1939 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001940 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001941 BoundExpr.get());
1942 if (EndExpr.isInvalid())
1943 return StmtError();
1944 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1945 diag::err_for_range_iter_deduction_failure)) {
1946 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1947 return StmtError();
1948 }
1949 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001950 OverloadCandidateSet CandidateSet(RangeLoc);
1951 Sema::BeginEndFunction BEFFailure;
1952 ForRangeStatus RangeStatus =
1953 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1954 EndRangeRef.get(), RangeType,
1955 BeginVar, EndVar, ColonLoc, &CandidateSet,
1956 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001957
Sam Panzere1715b62012-08-21 00:52:01 +00001958 // If building the range failed, try dereferencing the range expression
1959 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001960 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001961 BEFFailure == BEF_begin) {
1962 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1963 LoopVarDecl, ColonLoc,
1964 Range, RangeLoc,
1965 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001966 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001967 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001968 }
1969
Sam Panzere1715b62012-08-21 00:52:01 +00001970 // Otherwise, emit diagnostics if we haven't already.
1971 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001972 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001973 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1974 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001975 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001976 }
1977 // Return an error if no fix was discovered.
1978 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001979 return StmtError();
1980 }
1981
Sam Panzere1715b62012-08-21 00:52:01 +00001982 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1983 "invalid range expression in for loop");
1984
1985 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001986 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1987 if (!Context.hasSameType(BeginType, EndType)) {
1988 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1989 << BeginType << EndType;
1990 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1991 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1992 }
1993
1994 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1995 // Claim the type doesn't contain auto: we've already done the checking.
1996 DeclGroupPtrTy BeginEndGroup =
1997 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1998 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1999
Ted Kremeneke50b0152011-10-10 22:36:28 +00002000 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2001 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00002002 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002003 if (BeginRef.isInvalid())
2004 return StmtError();
2005
Richard Smithad762fc2011-04-14 22:09:26 +00002006 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2007 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002008 if (EndRef.isInvalid())
2009 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00002010
2011 // Build and check __begin != __end expression.
2012 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2013 BeginRef.get(), EndRef.get());
2014 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2015 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2016 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002017 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2018 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002019 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2020 if (!Context.hasSameType(BeginType, EndType))
2021 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2022 return StmtError();
2023 }
2024
2025 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002026 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2027 VK_LValue, ColonLoc);
2028 if (BeginRef.isInvalid())
2029 return StmtError();
2030
Richard Smithad762fc2011-04-14 22:09:26 +00002031 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2032 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2033 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002034 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2035 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002036 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2037 return StmtError();
2038 }
2039
2040 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002041 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2042 VK_LValue, ColonLoc);
2043 if (BeginRef.isInvalid())
2044 return StmtError();
2045
Richard Smithad762fc2011-04-14 22:09:26 +00002046 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2047 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002048 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2049 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002050 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2051 return StmtError();
2052 }
2053
Richard Smith8b533d92012-09-20 21:52:32 +00002054 // Attach *__begin as initializer for VD. Don't touch it if we're just
2055 // trying to determine whether this would be a valid range.
2056 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002057 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2058 /*TypeMayContainAuto=*/true);
2059 if (LoopVar->isInvalidDecl())
2060 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2061 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002062 } else {
2063 // The range is implicitly used as a placeholder when it is dependent.
2064 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002065 }
2066
Richard Smith8b533d92012-09-20 21:52:32 +00002067 // Don't bother to actually allocate the result if we're just trying to
2068 // determine whether it would be valid.
2069 if (Kind == BFRK_Check)
2070 return StmtResult();
2071
Richard Smithad762fc2011-04-14 22:09:26 +00002072 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2073 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2074 NotEqExpr.take(), IncrExpr.take(),
2075 LoopVarDS, /*Body=*/0, ForLoc,
2076 ColonLoc, RParenLoc));
2077}
2078
Chad Rosier1093f492012-08-10 17:56:09 +00002079/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002080/// statement.
2081StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2082 if (!S || !B)
2083 return StmtError();
2084 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002085
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002086 ForStmt->setBody(B);
2087 return S;
2088}
2089
Richard Smithad762fc2011-04-14 22:09:26 +00002090/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2091/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2092/// body cannot be performed until after the type of the range variable is
2093/// determined.
2094StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2095 if (!S || !B)
2096 return StmtError();
2097
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002098 if (isa<ObjCForCollectionStmt>(S))
2099 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002100
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002101 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2102 ForStmt->setBody(B);
2103
2104 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2105 diag::warn_empty_range_based_for_body);
2106
Richard Smithad762fc2011-04-14 22:09:26 +00002107 return S;
2108}
2109
Chris Lattner57ad3782011-02-17 20:34:02 +00002110StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2111 SourceLocation LabelLoc,
2112 LabelDecl *TheDecl) {
2113 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002114 TheDecl->setUsed();
2115 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002116}
2117
John McCall60d7b3a2010-08-24 06:29:42 +00002118StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002119Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002120 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002121 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002122 if (!E->isTypeDependent()) {
2123 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002124 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002125 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002126 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002127 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2128 if (ExprRes.isInvalid())
2129 return StmtError();
2130 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002131 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002132 return StmtError();
2133 }
John McCallb60a77e2010-08-01 00:26:45 +00002134
Richard Smith41956372013-01-14 22:39:08 +00002135 ExprResult ExprRes = ActOnFinishFullExpr(E);
2136 if (ExprRes.isInvalid())
2137 return StmtError();
2138 E = ExprRes.take();
2139
John McCall781472f2010-08-25 08:40:02 +00002140 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002141
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002142 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002143}
2144
John McCall60d7b3a2010-08-24 06:29:42 +00002145StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002146Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 Scope *S = CurScope->getContinueParent();
2148 if (!S) {
2149 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002150 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002152
Ted Kremenek8189cde2009-02-07 01:47:29 +00002153 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002154}
2155
John McCall60d7b3a2010-08-24 06:29:42 +00002156StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002157Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 Scope *S = CurScope->getBreakParent();
2159 if (!S) {
2160 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002161 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002163
Ted Kremenek8189cde2009-02-07 01:47:29 +00002164 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002165}
2166
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002168/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002169///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002170/// \param ReturnType If we're determining the copy elision candidate for
2171/// a return statement, this is the return type of the function. If we're
2172/// determining the copy elision candidate for a throw expression, this will
2173/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002174///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002175/// \param E The expression being returned from the function or block, or
2176/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002177///
Douglas Gregor4926d832011-05-20 15:00:53 +00002178/// \param AllowFunctionParameter Whether we allow function parameters to
2179/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2180/// we re-use this logic to determine whether we should try to move as part of
2181/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002182///
2183/// \returns The NRVO candidate variable, if the return statement may use the
2184/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002185const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2186 Expr *E,
2187 bool AllowFunctionParameter) {
2188 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002189 // - in a return statement in a function with ...
2190 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002191 if (!ReturnType.isNull()) {
2192 if (!ReturnType->isRecordType())
2193 return 0;
2194 // ... the same cv-unqualified type as the function return type ...
2195 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2196 return 0;
2197 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002198
2199 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002200 // (other than a function or catch-clause parameter)) ...
2201 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002202 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002203 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002204 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2205 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002206 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207
John McCall1cd76e82011-11-11 03:57:31 +00002208 // ...object (other than a function or catch-clause parameter)...
2209 if (VD->getKind() != Decl::Var &&
2210 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2211 return 0;
2212 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002213
John McCall1cd76e82011-11-11 03:57:31 +00002214 // ...automatic...
2215 if (!VD->hasLocalStorage()) return 0;
2216
2217 // ...non-volatile...
2218 if (VD->getType().isVolatileQualified()) return 0;
2219 if (VD->getType()->isReferenceType()) return 0;
2220
2221 // __block variables can't be allocated in a way that permits NRVO.
2222 if (VD->hasAttr<BlocksAttr>()) return 0;
2223
2224 // Variables with higher required alignment than their type's ABI
2225 // alignment cannot use NRVO.
2226 if (VD->hasAttr<AlignedAttr>() &&
2227 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2228 return 0;
2229
2230 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002231}
2232
Douglas Gregor07f402c2011-01-21 21:08:57 +00002233/// \brief Perform the initialization of a potentially-movable value, which
2234/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002235///
2236/// This routine implements C++0x [class.copy]p33, which attempts to treat
2237/// returned lvalues as rvalues in certain cases (to prefer move construction),
2238/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002239ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002240Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2241 const VarDecl *NRVOCandidate,
2242 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002243 Expr *Value,
2244 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002245 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002246 // When the criteria for elision of a copy operation are met or would
2247 // be met save for the fact that the source object is a function
2248 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002249 // overload resolution to select the constructor for the copy is first
2250 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002251 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002252 if (AllowNRVO &&
2253 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002254 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002255 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002256
Douglas Gregorcc15f012011-01-21 19:38:21 +00002257 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002258 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002259 = InitializationKind::CreateCopy(Value->getLocStart(),
2260 Value->getLocStart());
2261 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002262
2263 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002264 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002265 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002266 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002267 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002268 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2269 StepEnd = Seq.step_end();
2270 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002271 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002272 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002273
2274 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002275 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002276
Douglas Gregorcc15f012011-01-21 19:38:21 +00002277 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002278 = Constructor->getParamDecl(0)->getType()
2279 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002280
Douglas Gregorcc15f012011-01-21 19:38:21 +00002281 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002282 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002283 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2284 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002285 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286
Douglas Gregorcc15f012011-01-21 19:38:21 +00002287 // Promote "AsRvalue" to the heap, since we now need this
2288 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002289 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002290 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002291
Douglas Gregorcc15f012011-01-21 19:38:21 +00002292 // Complete type-checking the initialization of the return type
2293 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002294 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002295 }
2296 }
2297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002298
Douglas Gregorcc15f012011-01-21 19:38:21 +00002299 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002300 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002301 // (again) now with the return value expression as written.
2302 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002303 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002304
Douglas Gregorcc15f012011-01-21 19:38:21 +00002305 return Res;
2306}
2307
Eli Friedman84b007f2012-01-26 03:00:14 +00002308/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2309/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002310///
John McCall60d7b3a2010-08-24 06:29:42 +00002311StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002312Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2313 // If this is the first return we've seen, infer the return type.
2314 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2315 // rules which allows multiple return statements.
2316 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002317 QualType FnRetType = CurCap->ReturnType;
2318
2319 // For blocks/lambdas with implicit return types, we check each return
2320 // statement individually, and deduce the common return type when the block
2321 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002322 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002323 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002324 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2325 if (Result.isInvalid())
2326 return StmtError();
2327 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002328
Jordan Rose7dd900e2012-07-02 21:19:23 +00002329 if (!RetValExp->isTypeDependent())
2330 FnRetType = RetValExp->getType();
2331 else
2332 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002333 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002334 if (RetValExp) {
2335 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2336 // initializer list, because it is not an expression (even
2337 // though we represent it as one). We still deduce 'void'.
2338 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2339 << RetValExp->getSourceRange();
2340 }
2341
Jordan Rose7dd900e2012-07-02 21:19:23 +00002342 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002343 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002344
2345 // Although we'll properly infer the type of the block once it's completed,
2346 // make sure we provide a return type now for better error recovery.
2347 if (CurCap->ReturnType.isNull())
2348 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002349 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002350 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002351
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002352 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002353 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2354 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2355 return StmtError();
2356 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002357 } else {
2358 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2359 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2360 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2361 return StmtError();
2362 }
2363 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002364
Steve Naroff4eb206b2008-09-03 18:15:37 +00002365 // Otherwise, verify that this result type matches the previous one. We are
2366 // pickier with blocks than for normal functions because we don't have GCC
2367 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002368 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002369 if (FnRetType->isDependentType()) {
2370 // Delay processing for now. TODO: there are lots of dependent
2371 // types we can conclusively prove aren't void.
2372 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002373 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002374 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002375 (RetValExp->isTypeDependent() ||
2376 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002377 if (!getLangOpts().CPlusPlus &&
2378 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002379 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002380 else {
2381 Diag(ReturnLoc, diag::err_return_block_has_expr);
2382 RetValExp = 0;
2383 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002384 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002385 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002386 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2387 } else if (!RetValExp->isTypeDependent()) {
2388 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002389
John McCall0a7efe12011-08-17 22:09:46 +00002390 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2391 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2392 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002393
John McCall0a7efe12011-08-17 22:09:46 +00002394 // In C++ the return statement is handled via a copy initialization.
2395 // the C version of which boils down to CheckSingleAssignmentConstraints.
2396 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2397 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2398 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002399 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002400 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2401 FnRetType, RetValExp);
2402 if (Res.isInvalid()) {
2403 // FIXME: Cleanup temporaries here, anyway?
2404 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002405 }
John McCall0a7efe12011-08-17 22:09:46 +00002406 RetValExp = Res.take();
2407 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002408 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002409
John McCalld963c372011-08-17 21:34:14 +00002410 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002411 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2412 if (ER.isInvalid())
2413 return StmtError();
2414 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002415 }
John McCall0a7efe12011-08-17 22:09:46 +00002416 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2417 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002418
Jordan Rose7dd900e2012-07-02 21:19:23 +00002419 // If we need to check for the named return value optimization,
2420 // or if we need to infer the return type,
2421 // save the return statement in our scope for later processing.
2422 if (CurCap->HasImplicitReturnType ||
2423 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2424 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002425 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002426
Douglas Gregor5077c382010-05-15 06:01:05 +00002427 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002428}
Reid Spencer5f016e22007-07-11 17:01:13 +00002429
John McCall60d7b3a2010-08-24 06:29:42 +00002430StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002431Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002432 // Check for unexpanded parameter packs.
2433 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2434 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002435
Eli Friedman84b007f2012-01-26 03:00:14 +00002436 if (isa<CapturingScopeInfo>(getCurFunction()))
2437 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002438
Chris Lattner371f2582008-12-04 23:50:19 +00002439 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002440 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002441 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002442 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002443 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002444 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002445 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002446 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002447 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002448 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2449 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002450 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002451 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002452 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2453 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002454 }
2455 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002456 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Douglas Gregor5077c382010-05-15 06:01:05 +00002458 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002459 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002460 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002461 if (isa<InitListExpr>(RetValExp)) {
2462 // We simply never allow init lists as the return value of void
2463 // functions. This is compatible because this was never allowed before,
2464 // so there's no legacy code to deal with.
2465 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2466 int FunctionKind = 0;
2467 if (isa<ObjCMethodDecl>(CurDecl))
2468 FunctionKind = 1;
2469 else if (isa<CXXConstructorDecl>(CurDecl))
2470 FunctionKind = 2;
2471 else if (isa<CXXDestructorDecl>(CurDecl))
2472 FunctionKind = 3;
2473
2474 Diag(ReturnLoc, diag::err_return_init_list)
2475 << CurDecl->getDeclName() << FunctionKind
2476 << RetValExp->getSourceRange();
2477
2478 // Drop the expression.
2479 RetValExp = 0;
2480 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002481 // C99 6.8.6.4p1 (ext_ since GCC warns)
2482 unsigned D = diag::ext_return_has_expr;
2483 if (RetValExp->getType()->isVoidType())
2484 D = diag::ext_return_has_void_expr;
2485 else {
2486 ExprResult Result = Owned(RetValExp);
2487 Result = IgnoredValueConversions(Result.take());
2488 if (Result.isInvalid())
2489 return StmtError();
2490 RetValExp = Result.take();
2491 RetValExp = ImpCastExprToType(RetValExp,
2492 Context.VoidTy, CK_ToVoid).take();
2493 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002494
Nick Lewycky8d794612011-06-01 07:44:31 +00002495 // return (some void expression); is legal in C++.
2496 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002497 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002498 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002499
2500 int FunctionKind = 0;
2501 if (isa<ObjCMethodDecl>(CurDecl))
2502 FunctionKind = 1;
2503 else if (isa<CXXConstructorDecl>(CurDecl))
2504 FunctionKind = 2;
2505 else if (isa<CXXDestructorDecl>(CurDecl))
2506 FunctionKind = 3;
2507
Nick Lewycky8d794612011-06-01 07:44:31 +00002508 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002509 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002510 << RetValExp->getSourceRange();
2511 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002512 }
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Sebastian Redl33deb352012-02-22 10:50:08 +00002514 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002515 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2516 if (ER.isInvalid())
2517 return StmtError();
2518 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002519 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002521
Douglas Gregor5077c382010-05-15 06:01:05 +00002522 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2523 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002524 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2525 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002526 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002527
2528 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002529 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002530 else
Chris Lattner08631c52008-11-23 21:45:46 +00002531 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002532 Result = new (Context) ReturnStmt(ReturnLoc);
2533 } else {
2534 const VarDecl *NRVOCandidate = 0;
2535 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2536 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002537
Eli Friedman38ac2432012-03-30 01:13:43 +00002538 if (!RelatedRetType.isNull()) {
2539 // If we have a related result type, perform an extra conversion here.
2540 // FIXME: The diagnostics here don't really describe what is happening.
2541 InitializedEntity Entity =
2542 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002543
Eli Friedman38ac2432012-03-30 01:13:43 +00002544 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2545 RetValExp);
2546 if (Res.isInvalid()) {
2547 // FIXME: Cleanup temporaries here, anyway?
2548 return StmtError();
2549 }
2550 RetValExp = Res.takeAs<Expr>();
2551 }
2552
Douglas Gregor5077c382010-05-15 06:01:05 +00002553 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2554 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2555 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002556
John McCall856d3792011-06-16 23:24:51 +00002557 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002558 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002559 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002560 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002561 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002562 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002563 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002564 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002565 if (Res.isInvalid()) {
2566 // FIXME: Cleanup temporaries here, anyway?
2567 return StmtError();
2568 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002569
Douglas Gregor5077c382010-05-15 06:01:05 +00002570 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002572 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002574
John McCallb4eb64d2010-10-08 02:01:28 +00002575 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002576 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2577 if (ER.isInvalid())
2578 return StmtError();
2579 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002580 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002581 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583
2584 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002585 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002586 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002587 !CurContext->isDependentContext())
2588 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002589
Douglas Gregor5077c382010-05-15 06:01:05 +00002590 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002591}
2592
John McCall60d7b3a2010-08-24 06:29:42 +00002593StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002594Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002595 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002596 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002597 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002598 if (Var && Var->isInvalidDecl())
2599 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002600
John McCall9ae2f072010-08-23 23:25:46 +00002601 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002602}
2603
John McCall60d7b3a2010-08-24 06:29:42 +00002604StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002605Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2606 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002607}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002608
John McCall60d7b3a2010-08-24 06:29:42 +00002609StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002610Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002611 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002612 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002613 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2614
John McCall781472f2010-08-25 08:40:02 +00002615 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002616 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002617 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002618 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002619 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002620 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002621}
2622
John McCalld1376ee2012-05-08 21:41:25 +00002623StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002624 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002625 ExprResult Result = DefaultLvalueConversion(Throw);
2626 if (Result.isInvalid())
2627 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002628
Richard Smith41956372013-01-14 22:39:08 +00002629 Result = ActOnFinishFullExpr(Result.take());
2630 if (Result.isInvalid())
2631 return StmtError();
2632 Throw = Result.take();
2633
Douglas Gregord1377b22010-04-22 21:44:01 +00002634 QualType ThrowType = Throw->getType();
2635 // Make sure the expression type is an ObjC pointer or "void *".
2636 if (!ThrowType->isDependentType() &&
2637 !ThrowType->isObjCObjectPointerType()) {
2638 const PointerType *PT = ThrowType->getAs<PointerType>();
2639 if (!PT || !PT->getPointeeType()->isVoidType())
2640 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2641 << Throw->getType() << Throw->getSourceRange());
2642 }
2643 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002644
John McCall9ae2f072010-08-23 23:25:46 +00002645 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002646}
2647
John McCall60d7b3a2010-08-24 06:29:42 +00002648StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002649Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002650 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002651 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002652 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2653
John McCall9ae2f072010-08-23 23:25:46 +00002654 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002655 // @throw without an expression designates a rethrow (which much occur
2656 // in the context of an @catch clause).
2657 Scope *AtCatchParent = CurScope;
2658 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2659 AtCatchParent = AtCatchParent->getParent();
2660 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002661 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662 }
John McCall9ae2f072010-08-23 23:25:46 +00002663 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002664}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002665
John McCall07524032011-07-27 21:50:02 +00002666ExprResult
2667Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2668 ExprResult result = DefaultLvalueConversion(operand);
2669 if (result.isInvalid())
2670 return ExprError();
2671 operand = result.take();
2672
2673 // Make sure the expression type is an ObjC pointer or "void *".
2674 QualType type = operand->getType();
2675 if (!type->isDependentType() &&
2676 !type->isObjCObjectPointerType()) {
2677 const PointerType *pointerType = type->getAs<PointerType>();
2678 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2679 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2680 << type << operand->getSourceRange();
2681 }
2682
2683 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002684 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002685}
2686
John McCall60d7b3a2010-08-24 06:29:42 +00002687StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002688Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2689 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002690 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002691 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002692 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002693}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002694
2695/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2696/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002697StmtResult
John McCalld226f652010-08-21 09:40:31 +00002698Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002699 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002700 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002701 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002702 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002703 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002704}
Sebastian Redl8351da02008-12-22 21:35:02 +00002705
John McCallf85e1932011-06-15 23:02:42 +00002706StmtResult
2707Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2708 getCurFunction()->setHasBranchProtectedScope();
2709 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2710}
2711
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002712namespace {
2713
Sebastian Redlc447aba2009-07-29 17:15:45 +00002714class TypeWithHandler {
2715 QualType t;
2716 CXXCatchStmt *stmt;
2717public:
2718 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2719 : t(type), stmt(statement) {}
2720
John McCall0953e762009-09-24 19:53:00 +00002721 // An arbitrary order is fine as long as it places identical
2722 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002723 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002724 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002725 return true;
John McCall0953e762009-09-24 19:53:00 +00002726 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002727 return false;
2728 else
2729 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2730 }
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Sebastian Redlc447aba2009-07-29 17:15:45 +00002732 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002733 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002734 }
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Sebastian Redlc447aba2009-07-29 17:15:45 +00002736 CXXCatchStmt *getCatchStmt() const { return stmt; }
2737 SourceLocation getTypeSpecStartLoc() const {
2738 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2739 }
2740};
2741
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002742}
2743
Sebastian Redl8351da02008-12-22 21:35:02 +00002744/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2745/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002746StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002747Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002748 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002749 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002750 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002751 !getSourceManager().isInSystemHeader(TryLoc))
2752 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002753
Sebastian Redl8351da02008-12-22 21:35:02 +00002754 unsigned NumHandlers = RawHandlers.size();
2755 assert(NumHandlers > 0 &&
2756 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002757 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002758
Chris Lattner5f9e2722011-07-23 10:55:15 +00002759 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002760
2761 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002762 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002763 if (!Handler->getExceptionDecl()) {
2764 if (i < NumHandlers - 1)
2765 return StmtError(Diag(Handler->getLocStart(),
2766 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Sebastian Redlc447aba2009-07-29 17:15:45 +00002768 continue;
2769 }
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Sebastian Redlc447aba2009-07-29 17:15:45 +00002771 const QualType CaughtType = Handler->getCaughtType();
2772 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2773 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002774 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002775
2776 // Detect handlers for the same type as an earlier one.
2777 if (NumHandlers > 1) {
2778 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Sebastian Redlc447aba2009-07-29 17:15:45 +00002780 TypeWithHandler prev = TypesWithHandlers[0];
2781 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2782 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Sebastian Redlc447aba2009-07-29 17:15:45 +00002784 if (curr == prev) {
2785 Diag(curr.getTypeSpecStartLoc(),
2786 diag::warn_exception_caught_by_earlier_handler)
2787 << curr.getCatchStmt()->getCaughtType().getAsString();
2788 Diag(prev.getTypeSpecStartLoc(),
2789 diag::note_previous_exception_handler)
2790 << prev.getCatchStmt()->getCaughtType().getAsString();
2791 }
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Sebastian Redlc447aba2009-07-29 17:15:45 +00002793 prev = curr;
2794 }
2795 }
Mike Stump1eb44332009-09-09 15:08:12 +00002796
John McCall781472f2010-08-25 08:40:02 +00002797 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002798
Sebastian Redl8351da02008-12-22 21:35:02 +00002799 // FIXME: We should detect handlers that cannot catch anything because an
2800 // earlier handler catches a superclass. Need to find a method that is not
2801 // quadratic for this.
2802 // Neither of these are explicitly forbidden, but every compiler detects them
2803 // and warns.
2804
John McCall9ae2f072010-08-23 23:25:46 +00002805 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002806 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002807}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002808
2809StmtResult
2810Sema::ActOnSEHTryBlock(bool IsCXXTry,
2811 SourceLocation TryLoc,
2812 Stmt *TryBlock,
2813 Stmt *Handler) {
2814 assert(TryBlock && Handler);
2815
2816 getCurFunction()->setHasBranchProtectedScope();
2817
2818 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2819}
2820
2821StmtResult
2822Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2823 Expr *FilterExpr,
2824 Stmt *Block) {
2825 assert(FilterExpr && Block);
2826
2827 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002828 return StmtError(Diag(FilterExpr->getExprLoc(),
2829 diag::err_filter_expression_integral)
2830 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002831 }
2832
2833 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2834}
2835
2836StmtResult
2837Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2838 Stmt *Block) {
2839 assert(Block);
2840 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2841}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002842
2843StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2844 bool IsIfExists,
2845 NestedNameSpecifierLoc QualifierLoc,
2846 DeclarationNameInfo NameInfo,
2847 Stmt *Nested)
2848{
2849 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002850 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002851 cast<CompoundStmt>(Nested));
2852}
2853
2854
Chad Rosier1093f492012-08-10 17:56:09 +00002855StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002856 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002857 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002858 UnqualifiedId &Name,
2859 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002860 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002861 SS.getWithLocInContext(Context),
2862 GetNameFromUnqualifiedId(Name),
2863 Nested);
2864}