blob: 88237b08b2bb5c49cd39bcab0db87dbde1756afe [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
John McCallb760f112013-03-22 02:10:40 +000057StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
59 return StmtError();
60}
61
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000062StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000063 bool HasLeadingEmptyMacro) {
64 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000065}
66
Chris Lattner337e5502011-02-18 01:27:55 +000067StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000069 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner20401692009-04-12 20:13:14 +000071 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner24e1e702009-03-04 04:23:07 +000074 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000075}
76
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000077void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
78 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Douglas Gregor12849d02013-04-08 20:52:24 +000079
80 // If we don't have a declaration, or we have an invalid declaration,
81 // just return.
82 if (DG.isNull() || !DG.isSingleDecl())
83 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000084
Douglas Gregor12849d02013-04-08 20:52:24 +000085 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
87 return;
88
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
91 if (!var) {
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
94 return;
95 }
John McCallf85e1932011-06-15 23:02:42 +000096
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000097 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000098 var->setUsed();
99
John McCall7acddac2011-06-17 06:42:21 +0000100 // foreach variables are never actually initialized in the way that
101 // the parser came up with.
102 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +0000103
John McCall7acddac2011-06-17 06:42:21 +0000104 // In ARC, we don't need to retain the iteration variable of a fast
105 // enumeration loop. Rather than actually trying to catch that
106 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +0000107 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +0000108 QualType type = var->getType();
109
110 // Only do this if we inferred the lifetime. Inferred lifetime
111 // will show up as a local qualifier because explicit lifetime
112 // should have shown up as an AttributedType instead.
113 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
114 // Add 'const' and mark the variable as pseudo-strong.
115 var->setType(type.withConst());
116 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +0000117 }
118 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +0000119}
120
Chandler Carruthec8058f2011-08-17 09:34:37 +0000121/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122///
123/// Adding a cast to void (or other expression wrappers) will prevent the
124/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000125static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000126 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000127 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000128
129 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
130 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000131 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000132
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000133 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000134 IsNotEqual = Op->getOpcode() == BO_NE;
135 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000136 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
137 if (Op->getOperator() != OO_EqualEqual &&
138 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000139 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000140
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000141 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000142 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
143 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000144 } else {
145 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000146 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000147 }
148
149 // Suppress warnings when the operator, suspicious as it may be, comes from
150 // a macro expansion.
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +0000151 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthec8058f2011-08-17 09:34:37 +0000152 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000153
Chandler Carruthec8058f2011-08-17 09:34:37 +0000154 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000155 << (unsigned)IsNotEqual << E->getSourceRange();
156
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000157 // If the LHS is a plausible entity to assign to, provide a fixit hint to
158 // correct common typos.
159 if (CanAssign) {
160 if (IsNotEqual)
161 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
162 << FixItHint::CreateReplacement(Loc, "|=");
163 else
164 S.Diag(Loc, diag::note_equality_comparison_to_assign)
165 << FixItHint::CreateReplacement(Loc, "=");
166 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000167
168 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000169}
170
Anders Carlsson636463e2009-07-30 22:17:18 +0000171void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000172 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
173 return DiagnoseUnusedExprResult(Label->getSubStmt());
174
Anders Carlsson75443112009-07-30 22:39:03 +0000175 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000176 if (!E)
177 return;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000178 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000179 // In most cases, we don't want to warn if the expression is written in a
180 // macro body, or if the macro comes from a system header. If the offending
181 // expression is a call to a function with the warn_unused_result attribute,
182 // we warn no matter the location. Because of the order in which the various
183 // checks need to happen, we factor out the macro-related test here.
184 bool ShouldSuppress =
185 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
186 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson636463e2009-07-30 22:17:18 +0000187
Eli Friedmana6115062012-05-24 00:47:05 +0000188 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000189 SourceLocation Loc;
190 SourceRange R1, R2;
Matt Beaumont-Gay87b73ba2013-01-17 02:06:08 +0000191 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000192 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner06b3a062012-08-31 22:39:21 +0000194 // If this is a GNU statement expression expanded from a macro, it is probably
195 // unused because it is a function-like macro that can be used as either an
196 // expression or statement. Don't warn, because it is almost certainly a
197 // false positive.
198 if (isa<StmtExpr>(E) && Loc.isMacroID())
199 return;
200
Chris Lattner419cfb32009-08-16 16:57:27 +0000201 // Okay, we have an unused result. Depending on what the base expression is,
202 // we might want to make a more specific diagnostic. Check for one of these
203 // cases now.
204 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000205 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000206 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000207 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
208 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000209
Chandler Carruthec8058f2011-08-17 09:34:37 +0000210 if (DiagnoseUnusedComparison(*this, E))
211 return;
212
Eli Friedmana6115062012-05-24 00:47:05 +0000213 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000214 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000215 if (E->getType()->isVoidType())
216 return;
217
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000218 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000219 // a more specific message to make it clear what is happening. If the call
220 // is written in a macro body, only warn if it has the warn_unused_result
221 // attribute.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000222 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000223 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000224 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000225 return;
226 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000227 if (ShouldSuppress)
228 return;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000229 if (FD->getAttr<PureAttr>()) {
230 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
231 return;
232 }
233 if (FD->getAttr<ConstAttr>()) {
234 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
235 return;
236 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000237 }
Matt Beaumont-Gay9016bb72013-02-26 19:34:08 +0000238 } else if (ShouldSuppress)
239 return;
240
241 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000242 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000243 Diag(Loc, diag::err_arc_unused_init_message) << R1;
244 return;
245 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000246 const ObjCMethodDecl *MD = ME->getMethodDecl();
247 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000248 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000249 return;
250 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000251 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
252 const Expr *Source = POE->getSyntacticForm();
253 if (isa<ObjCSubscriptRefExpr>(Source))
254 DiagID = diag::warn_unused_container_subscript_expr;
255 else
256 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000257 } else if (const CXXFunctionalCastExpr *FC
258 = dyn_cast<CXXFunctionalCastExpr>(E)) {
259 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
260 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
261 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000262 }
John McCall209acbd2010-04-06 22:24:14 +0000263 // Diagnose "(void*) blah" as a typo for "(void) blah".
264 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
265 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
266 QualType T = TI->getType();
267
268 // We really do want to use the non-canonical type here.
269 if (T == Context.VoidPtrTy) {
David Blaikie39e6ab42013-02-18 22:06:02 +0000270 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall209acbd2010-04-06 22:24:14 +0000271
272 Diag(Loc, diag::warn_unused_voidptr)
273 << FixItHint::CreateRemoval(TL.getStarLoc());
274 return;
275 }
276 }
277
Eli Friedmana6115062012-05-24 00:47:05 +0000278 if (E->isGLValue() && E->getType().isVolatileQualified()) {
279 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
280 return;
281 }
282
Ted Kremenek351ba912011-02-23 01:52:04 +0000283 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000284}
285
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000286void Sema::ActOnStartOfCompoundStmt() {
287 PushCompoundScope();
288}
289
290void Sema::ActOnFinishOfCompoundStmt() {
291 PopCompoundScope();
292}
293
294sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
295 return getCurFunction()->CompoundScopes.back();
296}
297
John McCall60d7b3a2010-08-24 06:29:42 +0000298StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000299Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000300 MultiStmtArg elts, bool isStmtExpr) {
301 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000302 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000303 // If we're in C89 mode, check that we don't have any decls after stmts. If
304 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000305 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000306 // Note that __extension__ can be around a decl.
307 unsigned i = 0;
308 // Skip over all declarations.
309 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
310 /*empty*/;
311
312 // We found the end of the list or a statement. Scan for another declstmt.
313 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
314 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000316 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000317 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000318 Diag(D->getLocation(), diag::ext_mixed_decls_code);
319 }
320 }
Chris Lattner98414c12007-08-31 21:49:55 +0000321 // Warn about unused expressions in statements.
322 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000323 // Ignore statements that are last in a statement expression.
324 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000325 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Anders Carlsson636463e2009-07-30 22:17:18 +0000327 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000328 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000329
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000330 // Check for suspicious empty body (null statement) in `for' and `while'
331 // statements. Don't do anything for template instantiations, this just adds
332 // noise.
333 if (NumElts != 0 && !CurrentInstantiationScope &&
334 getCurCompoundScope().HasEmptyLoopBodies) {
335 for (unsigned i = 0; i != NumElts - 1; ++i)
336 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
337 }
338
Nico Weberd36aa352012-12-29 20:03:39 +0000339 return Owned(new (Context) CompoundStmt(Context,
340 llvm::makeArrayRef(Elts, NumElts),
341 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000342}
343
John McCall60d7b3a2010-08-24 06:29:42 +0000344StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000345Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
346 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000347 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000348 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000349
John McCall781472f2010-08-25 08:40:02 +0000350 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000351 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000352 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000353 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000354
Richard Smith80ad52f2013-01-02 11:42:31 +0000355 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000356 // C99 6.8.4.2p3: The expression shall be an integer constant.
357 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000358 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
359 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
360 if (!LHSVal)
361 return StmtError();
362 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000363
364 // GCC extension: The expression shall be an integer constant.
365
Richard Smith282e7e62012-02-04 09:53:13 +0000366 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
367 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
368 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000369 }
370 }
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000371
372 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
373 getLangOpts().CPlusPlus11).take();
374 if (RHSVal)
375 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
376 getLangOpts().CPlusPlus11).take();
Richard Smith8ef7b202012-01-18 23:55:52 +0000377
Douglas Gregordbb26db2009-05-15 23:57:33 +0000378 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
379 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000380 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000381 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000382}
383
Chris Lattner24e1e702009-03-04 04:23:07 +0000384/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000385void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000386 DiagnoseUnusedExprResult(SubStmt);
387
Chris Lattner24e1e702009-03-04 04:23:07 +0000388 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000389 CS->setSubStmt(SubStmt);
390}
391
John McCall60d7b3a2010-08-24 06:29:42 +0000392StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000393Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000394 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000395 DiagnoseUnusedExprResult(SubStmt);
396
John McCall781472f2010-08-25 08:40:02 +0000397 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000398 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000399 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000400 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000401
Douglas Gregordbb26db2009-05-15 23:57:33 +0000402 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000403 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000404 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000405}
406
John McCall60d7b3a2010-08-24 06:29:42 +0000407StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000408Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
409 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000410 // If the label was multiply defined, reject it now.
411 if (TheDecl->getStmt()) {
412 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
413 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000414 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 }
Sebastian Redlde307472009-01-11 00:38:46 +0000416
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000417 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000418 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
419 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000420 if (!TheDecl->isGnuLocal()) {
421 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000422 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000423 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000424 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000425}
426
Richard Smith534986f2012-04-14 00:33:13 +0000427StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000428 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000429 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000430 // Fill in the declaration and return it.
431 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000432 return Owned(LS);
433}
434
John McCall60d7b3a2010-08-24 06:29:42 +0000435StmtResult
John McCalld226f652010-08-21 09:40:31 +0000436Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000437 Stmt *thenStmt, SourceLocation ElseLoc,
438 Stmt *elseStmt) {
Argyrios Kyrtzidis820b23d2013-02-15 18:34:13 +0000439 // If the condition was invalid, discard the if statement. We could recover
440 // better by replacing it with a valid expr, but don't do that yet.
441 if (!CondVal.get() && !CondVar) {
442 getCurFunction()->setHasDroppedStmt();
443 return StmtError();
444 }
445
John McCall60d7b3a2010-08-24 06:29:42 +0000446 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000448 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000449 if (CondVar) {
450 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000451 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000452 if (CondResult.isInvalid())
453 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000454 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000455 Expr *ConditionExpr = CondResult.takeAs<Expr>();
456 if (!ConditionExpr)
457 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000458
Anders Carlsson75443112009-07-30 22:39:03 +0000459 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000460
John McCall9ae2f072010-08-23 23:25:46 +0000461 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000462 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
463 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000464 }
465
Anders Carlsson75443112009-07-30 22:39:03 +0000466 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000467
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000469 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000470}
471
Chris Lattnerf4021e72007-08-23 05:46:52 +0000472/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
473/// the specified width and sign. If an overflow occurs, detect it and emit
474/// the specified diagnostic.
475void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
476 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000477 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000478 unsigned DiagID) {
479 // Perform a conversion to the promoted condition type if needed.
480 if (NewWidth > Val.getBitWidth()) {
481 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000482 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000483 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000484
485 // If the input was signed and negative and the output is
486 // unsigned, don't bother to warn: this is implementation-defined
487 // behavior.
488 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000489 } else if (NewWidth < Val.getBitWidth()) {
490 // If this is a truncation, check for overflow.
491 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000492 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000493 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000494 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000495 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000496 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000497 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattnerf4021e72007-08-23 05:46:52 +0000499 // Regardless of whether a diagnostic was emitted, really do the
500 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000501 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000502 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000503 } else if (NewSign != Val.isSigned()) {
504 // Convert the sign to match the sign of the condition. This can cause
505 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000506 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000507 // behavior.
508 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000509 llvm::APSInt OldVal(Val);
510 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000511 }
512}
513
Chris Lattner0471f5b2007-08-23 18:29:20 +0000514namespace {
515 struct CaseCompareFunctor {
516 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
517 const llvm::APSInt &RHS) {
518 return LHS.first < RHS;
519 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000520 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
521 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
522 return LHS.first < RHS.first;
523 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000524 bool operator()(const llvm::APSInt &LHS,
525 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
526 return LHS < RHS.first;
527 }
528 };
529}
530
Chris Lattner764a7ce2007-09-21 18:15:22 +0000531/// CmpCaseVals - Comparison predicate for sorting case values.
532///
533static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
534 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
535 if (lhs.first < rhs.first)
536 return true;
537
538 if (lhs.first == rhs.first &&
539 lhs.second->getCaseLoc().getRawEncoding()
540 < rhs.second->getCaseLoc().getRawEncoding())
541 return true;
542 return false;
543}
544
Douglas Gregorba915af2010-02-08 22:24:16 +0000545/// CmpEnumVals - Comparison predicate for sorting enumeration values.
546///
547static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
548 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
549{
550 return lhs.first < rhs.first;
551}
552
553/// EqEnumVals - Comparison preficate for uniqing enumeration values.
554///
555static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
556 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
557{
558 return lhs.first == rhs.first;
559}
560
Chris Lattner5f048812009-10-16 16:45:22 +0000561/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
562/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000563static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
564 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
565 expr = cleanups->getSubExpr();
566 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
567 if (impcast->getCastKind() != CK_IntegralCast) break;
568 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000569 }
570 return expr->getType();
571}
572
John McCall60d7b3a2010-08-24 06:29:42 +0000573StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000575 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000576 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000577
Douglas Gregor586596f2010-05-06 17:25:47 +0000578 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000579 if (CondVar) {
580 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000581 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
582 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000583 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
John McCall9ae2f072010-08-23 23:25:46 +0000585 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000586 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000587
John McCall9ae2f072010-08-23 23:25:46 +0000588 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000589 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregorab41fe92012-05-04 22:38:52 +0000591 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
592 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000593
Douglas Gregorab41fe92012-05-04 22:38:52 +0000594 public:
595 SwitchConvertDiagnoser(Expr *Cond)
596 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000597
Douglas Gregorab41fe92012-05-04 22:38:52 +0000598 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
599 QualType T) {
600 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
601 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000602
Douglas Gregorab41fe92012-05-04 22:38:52 +0000603 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
604 QualType T) {
605 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
606 << T << Cond->getSourceRange();
607 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000608
Douglas Gregorab41fe92012-05-04 22:38:52 +0000609 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
610 QualType T,
611 QualType ConvTy) {
612 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
613 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000614
Douglas Gregorab41fe92012-05-04 22:38:52 +0000615 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
616 QualType ConvTy) {
617 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
618 << ConvTy->isEnumeralType() << ConvTy;
619 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000620
Douglas Gregorab41fe92012-05-04 22:38:52 +0000621 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
622 QualType T) {
623 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
624 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000625
Douglas Gregorab41fe92012-05-04 22:38:52 +0000626 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
627 QualType ConvTy) {
628 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
629 << ConvTy->isEnumeralType() << ConvTy;
630 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000631
Douglas Gregorab41fe92012-05-04 22:38:52 +0000632 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
633 QualType T,
634 QualType ConvTy) {
635 return DiagnosticBuilder::getEmpty();
636 }
637 } SwitchDiagnoser(Cond);
638
John McCall9ae2f072010-08-23 23:25:46 +0000639 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000640 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000641 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000642 if (CondResult.isInvalid()) return StmtError();
643 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000644
John McCalla8e0cd82011-08-06 07:30:58 +0000645 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
646 CondResult = UsualUnaryConversions(Cond);
647 if (CondResult.isInvalid()) return StmtError();
648 Cond = CondResult.take();
649
John McCalld226f652010-08-21 09:40:31 +0000650 if (!CondVar) {
Richard Smith41956372013-01-14 22:39:08 +0000651 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCall9ae2f072010-08-23 23:25:46 +0000652 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000653 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000654 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000655 }
John McCallb60a77e2010-08-01 00:26:45 +0000656
John McCall781472f2010-08-25 08:40:02 +0000657 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000658
John McCall9ae2f072010-08-23 23:25:46 +0000659 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000660 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000661 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000662}
663
Gabor Greif28164ab2010-10-01 22:05:14 +0000664static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
665 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000666 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000667 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000668 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000669 Val.setIsSigned(IsSigned);
670}
671
John McCall60d7b3a2010-08-24 06:29:42 +0000672StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000673Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
674 Stmt *BodyStmt) {
675 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000676 assert(SS == getCurFunction()->SwitchStack.back() &&
677 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000678
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000679 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000680 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000681
Chris Lattnerf4021e72007-08-23 05:46:52 +0000682 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000683 if (!CondExpr) return StmtError();
684
685 QualType CondType = CondExpr->getType();
686
John McCall0fb97082010-05-18 03:19:21 +0000687 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000688 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000689 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000690
Chris Lattner5f048812009-10-16 16:45:22 +0000691 // C++ 6.4.2.p2:
692 // Integral promotions are performed (on the switch condition).
693 //
694 // A case value unrepresentable by the original switch condition
695 // type (before the promotion) doesn't make sense, even when it can
696 // be represented by the promoted type. Therefore we need to find
697 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000698 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000699 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000700 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000701 // appropriate type now, just return an error.
702 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000703 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000704
Chris Lattner2b334bb2010-04-16 23:34:13 +0000705 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000706 // switch(bool_expr) {...} is often a programmer error, e.g.
707 // switch(n && mask) { ... } // Doh - should be "n & mask".
708 // One can always use an if statement instead of switch(bool_expr).
709 Diag(SwitchLoc, diag::warn_bool_switch_condition)
710 << CondExpr->getSourceRange();
711 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000712 }
Sebastian Redlde307472009-01-11 00:38:46 +0000713
Chris Lattnerf4021e72007-08-23 05:46:52 +0000714 // Get the bitwidth of the switched-on value before promotions. We must
715 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000716 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000717 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000718 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000719 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000720 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000721 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattnerf4021e72007-08-23 05:46:52 +0000723 // Accumulate all of the case values in a vector so that we can sort them
724 // and detect duplicates. This vector contains the APInt for the case after
725 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000726 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000727 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Chris Lattnerf4021e72007-08-23 05:46:52 +0000729 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000730 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
731 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattnerf4021e72007-08-23 05:46:52 +0000733 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000735 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Douglas Gregordbb26db2009-05-15 23:57:33 +0000737 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000738 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000740 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000741 if (TheDefaultStmt) {
742 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000743 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000744
Chris Lattnerf4021e72007-08-23 05:46:52 +0000745 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000746 // we'll return a valid AST. This requires recursing down the AST and
747 // finding it, not something we are set up to do right now. For now,
748 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000749 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000750 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000751 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattnerf4021e72007-08-23 05:46:52 +0000753 } else {
754 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattner1e0a3902008-01-16 19:17:22 +0000756 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000757
758 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
759 HasDependentValue = true;
760 break;
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Richard Smith8ef7b202012-01-18 23:55:52 +0000763 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Richard Smith80ad52f2013-01-02 11:42:31 +0000765 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000766 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
767 // constant expression of the promoted type of the switch condition.
768 ExprResult ConvLo =
769 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
770 if (ConvLo.isInvalid()) {
771 CaseListIsErroneous = true;
772 continue;
773 }
774 Lo = ConvLo.take();
775 } else {
776 // We already verified that the expression has a i-c-e value (C99
777 // 6.8.4.2p3) - get that value now.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000778 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smith8ef7b202012-01-18 23:55:52 +0000779
780 // If the LHS is not the same type as the condition, insert an implicit
781 // cast.
782 Lo = DefaultLvalueConversion(Lo).take();
783 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
784 }
785
786 // Convert the value to the same width/sign as the condition had prior to
787 // integral promotions.
788 //
789 // FIXME: This causes us to reject valid code:
790 // switch ((char)c) { case 256: case 0: return 0; }
791 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000792 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000793 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000794 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000795
Chris Lattner1e0a3902008-01-16 19:17:22 +0000796 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000798 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000799 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000800 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000801 CS->getRHS()->isValueDependent()) {
802 HasDependentValue = true;
803 break;
804 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000805 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000806 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000807 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000808 }
809 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000810
811 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000812 // If we don't have a default statement, check whether the
813 // condition is constant.
814 llvm::APSInt ConstantCondValue;
815 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000816 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000817 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000818 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
819 Expr::SE_AllowSideEffects);
820 assert(!HasConstantCond ||
821 (ConstantCondValue.getBitWidth() == CondWidth &&
822 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000823 }
Richard Smith80d4b552011-12-28 19:48:30 +0000824 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000825
Douglas Gregordbb26db2009-05-15 23:57:33 +0000826 // Sort all the scalar case values so we can easily detect duplicates.
827 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
828
829 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000830 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
831 if (ShouldCheckConstantCond &&
832 CaseVals[i].first == ConstantCondValue)
833 ShouldCheckConstantCond = false;
834
835 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000836 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000837 // First, determine if either case value has a name
838 StringRef PrevString, CurrString;
839 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
840 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
841 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
842 PrevString = DeclRef->getDecl()->getName();
843 }
844 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
845 CurrString = DeclRef->getDecl()->getName();
846 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000847 SmallString<16> CaseValStr;
Douglas Gregor50de5e32012-05-16 16:11:17 +0000848 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000849
850 if (PrevString == CurrString)
851 Diag(CaseVals[i].second->getLHS()->getLocStart(),
852 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000853 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000854 else
855 Diag(CaseVals[i].second->getLHS()->getLocStart(),
856 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000857 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
858 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000859 CaseValStr;
860
John McCall0fb97082010-05-18 03:19:21 +0000861 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000862 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000863 // FIXME: We really want to remove the bogus case stmt from the
864 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000865 CaseListIsErroneous = true;
866 }
867 }
868 }
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregordbb26db2009-05-15 23:57:33 +0000870 // Detect duplicate case ranges, which usually don't exist at all in
871 // the first place.
872 if (!CaseRanges.empty()) {
873 // Sort all the case ranges by their low value so we can easily detect
874 // overlaps between ranges.
875 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Douglas Gregordbb26db2009-05-15 23:57:33 +0000877 // Scan the ranges, computing the high values and removing empty ranges.
878 std::vector<llvm::APSInt> HiVals;
879 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000880 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000881 CaseStmt *CR = CaseRanges[i].second;
882 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000883 llvm::APSInt HiVal;
884
Richard Smith80ad52f2013-01-02 11:42:31 +0000885 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000886 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
887 // constant expression of the promoted type of the switch condition.
888 ExprResult ConvHi =
889 CheckConvertedConstantExpression(Hi, CondType, HiVal,
890 CCEK_CaseValue);
891 if (ConvHi.isInvalid()) {
892 CaseListIsErroneous = true;
893 continue;
894 }
895 Hi = ConvHi.take();
896 } else {
897 HiVal = Hi->EvaluateKnownConstInt(Context);
898
899 // If the RHS is not the same type as the condition, insert an
900 // implicit cast.
901 Hi = DefaultLvalueConversion(Hi).take();
902 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
903 }
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Douglas Gregordbb26db2009-05-15 23:57:33 +0000905 // Convert the value to the same width/sign as the condition.
906 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000907 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000908 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Douglas Gregordbb26db2009-05-15 23:57:33 +0000910 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Douglas Gregordbb26db2009-05-15 23:57:33 +0000912 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000913 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000914 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
915 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000916 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000917 CaseRanges.erase(CaseRanges.begin()+i);
918 --i, --e;
919 continue;
920 }
John McCall0fb97082010-05-18 03:19:21 +0000921
922 if (ShouldCheckConstantCond &&
923 LoVal <= ConstantCondValue &&
924 ConstantCondValue <= HiVal)
925 ShouldCheckConstantCond = false;
926
Douglas Gregordbb26db2009-05-15 23:57:33 +0000927 HiVals.push_back(HiVal);
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregordbb26db2009-05-15 23:57:33 +0000930 // Rescan the ranges, looking for overlap with singleton values and other
931 // ranges. Since the range list is sorted, we only need to compare case
932 // ranges with their neighbors.
933 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
934 llvm::APSInt &CRLo = CaseRanges[i].first;
935 llvm::APSInt &CRHi = HiVals[i];
936 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Douglas Gregordbb26db2009-05-15 23:57:33 +0000938 // Check to see whether the case range overlaps with any
939 // singleton cases.
940 CaseStmt *OverlapStmt = 0;
941 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregordbb26db2009-05-15 23:57:33 +0000943 // Find the smallest value >= the lower bound. If I is in the
944 // case range, then we have overlap.
945 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
946 CaseVals.end(), CRLo,
947 CaseCompareFunctor());
948 if (I != CaseVals.end() && I->first < CRHi) {
949 OverlapVal = I->first; // Found overlap with scalar.
950 OverlapStmt = I->second;
951 }
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Douglas Gregordbb26db2009-05-15 23:57:33 +0000953 // Find the smallest value bigger than the upper bound.
954 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
955 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
956 OverlapVal = (I-1)->first; // Found overlap with scalar.
957 OverlapStmt = (I-1)->second;
958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Douglas Gregordbb26db2009-05-15 23:57:33 +0000960 // Check to see if this case stmt overlaps with the subsequent
961 // case range.
962 if (i && CRLo <= HiVals[i-1]) {
963 OverlapVal = HiVals[i-1]; // Found overlap with range.
964 OverlapStmt = CaseRanges[i-1].second;
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Douglas Gregordbb26db2009-05-15 23:57:33 +0000967 if (OverlapStmt) {
968 // If we have a duplicate, report it.
969 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
970 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000971 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000972 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000973 // FIXME: We really want to remove the bogus case stmt from the
974 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000975 CaseListIsErroneous = true;
976 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000977 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000978 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000979
John McCall0fb97082010-05-18 03:19:21 +0000980 // Complain if we have a constant condition and we didn't find a match.
981 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
982 // TODO: it would be nice if we printed enums as enums, chars as
983 // chars, etc.
984 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
985 << ConstantCondValue.toString(10)
986 << CondExpr->getSourceRange();
987 }
988
989 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000990 // values. We only issue a warning if there is not 'default:', but
991 // we still do the analysis to preserve this information in the AST
992 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000993 //
Chris Lattnerce784612010-09-16 17:09:42 +0000994 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000995
Douglas Gregorba915af2010-02-08 22:24:16 +0000996 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000997 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000998 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000999 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +00001000 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +00001001 EnumValsTy EnumVals;
1002
John McCall0fb97082010-05-18 03:19:21 +00001003 // Gather all enum values, set their type and sort them,
1004 // allowing easier comparison with CaseVals.
1005 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +00001006 EDI != ED->enumerator_end(); ++EDI) {
1007 llvm::APSInt Val = EDI->getInitVal();
1008 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +00001009 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +00001010 }
1011 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +00001012 EnumValsTy::iterator EIend =
1013 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +00001014
1015 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +00001016 EnumValsTy::const_iterator EI = EnumVals.begin();
1017 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1018 CI != CaseVals.end(); CI++) {
1019 while (EI != EIend && EI->first < CI->first)
1020 EI++;
1021 if (EI == EIend || EI->first > CI->first)
1022 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001023 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +00001024 }
1025 // See which of case ranges aren't in enum
1026 EI = EnumVals.begin();
1027 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1028 RI != CaseRanges.end() && EI != EIend; RI++) {
1029 while (EI != EIend && EI->first < RI->first)
1030 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001031
David Blaikie93667502012-01-22 02:31:55 +00001032 if (EI == EIend || EI->first != RI->first) {
1033 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001034 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001035 }
David Blaikie93667502012-01-22 02:31:55 +00001036
Chad Rosier1093f492012-08-10 17:56:09 +00001037 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +00001038 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1039 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1040 while (EI != EIend && EI->first < Hi)
1041 EI++;
1042 if (EI == EIend || EI->first != Hi)
1043 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001044 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001045 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001046
Ted Kremenek559fb552010-09-09 00:05:53 +00001047 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001048 CaseValsTy::const_iterator CI = CaseVals.begin();
1049 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001050 bool hasCasesNotInSwitch = false;
1051
Chris Lattner5f9e2722011-07-23 10:55:15 +00001052 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
David Blaikie93667502012-01-22 02:31:55 +00001054 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001055 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001056 llvm::APSInt CIVal;
1057 while (CI != CaseVals.end() && CI->first < EI->first)
1058 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001059
Douglas Gregorba915af2010-02-08 22:24:16 +00001060 if (CI != CaseVals.end() && CI->first == EI->first)
1061 continue;
1062
Ted Kremenek559fb552010-09-09 00:05:53 +00001063 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001064 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001065 llvm::APSInt Hi =
1066 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001067 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001068 if (EI->first <= Hi)
1069 break;
1070 }
1071
Ted Kremenek559fb552010-09-09 00:05:53 +00001072 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001073 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001074 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001075 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001077
David Blaikie585d7792012-01-23 04:46:12 +00001078 if (TheDefaultStmt && UnhandledNames.empty())
1079 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001080
Chris Lattnerce784612010-09-16 17:09:42 +00001081 // Produce a nice diagnostic if multiple values aren't handled.
1082 switch (UnhandledNames.size()) {
1083 case 0: break;
1084 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001085 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001086 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001087 << UnhandledNames[0];
1088 break;
1089 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001090 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001091 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001092 << UnhandledNames[0] << UnhandledNames[1];
1093 break;
1094 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001095 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1096 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001097 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1098 break;
1099 default:
David Blaikie585d7792012-01-23 04:46:12 +00001100 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1101 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001102 << (unsigned)UnhandledNames.size()
1103 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1104 break;
1105 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001106
1107 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001108 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001109 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001110 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001111
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001112 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1113 diag::warn_empty_switch_body);
1114
Mike Stump390b4cc2009-05-16 07:39:55 +00001115 // FIXME: If the case list was broken is some way, we don't have a good system
1116 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001117 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001118 return StmtError();
1119
Sebastian Redlde307472009-01-11 00:38:46 +00001120 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001121}
1122
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001123void
1124Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1125 Expr *SrcExpr) {
1126 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001127 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001128 == DiagnosticsEngine::Ignored)
1129 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001130
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001131 if (const EnumType *ET = DstType->getAs<EnumType>())
1132 if (!Context.hasSameType(SrcType, DstType) &&
1133 SrcType->isIntegerType()) {
1134 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1135 SrcExpr->isIntegerConstantExpr(Context)) {
1136 // Get the bitwidth of the enum value before promotions.
1137 unsigned DstWith = Context.getIntWidth(DstType);
1138 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1139
1140 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1141 const EnumDecl *ED = ET->getDecl();
1142 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1143 EnumValsTy;
1144 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001145
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001146 // Gather all enum values, set their type and sort them,
1147 // allowing easier comparison with rhs constant.
1148 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1149 EDI != ED->enumerator_end(); ++EDI) {
1150 llvm::APSInt Val = EDI->getInitVal();
1151 AdjustAPSInt(Val, DstWith, DstIsSigned);
1152 EnumVals.push_back(std::make_pair(Val, *EDI));
1153 }
1154 if (EnumVals.empty())
1155 return;
1156 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1157 EnumValsTy::iterator EIend =
1158 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001159
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001160 // See which case values aren't in enum.
1161 EnumValsTy::const_iterator EI = EnumVals.begin();
1162 while (EI != EIend && EI->first < RhsVal)
1163 EI++;
1164 if (EI == EIend || EI->first != RhsVal) {
1165 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1166 << DstType;
1167 }
1168 }
1169 }
1170}
1171
John McCall60d7b3a2010-08-24 06:29:42 +00001172StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001173Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001174 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001175 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001176
Douglas Gregor5656e142009-11-24 21:15:44 +00001177 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001178 if (CondVar) {
1179 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001180 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001181 if (CondResult.isInvalid())
1182 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001183 }
John McCall9ae2f072010-08-23 23:25:46 +00001184 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001185 if (!ConditionExpr)
1186 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001187
John McCall9ae2f072010-08-23 23:25:46 +00001188 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001190 if (isa<NullStmt>(Body))
1191 getCurCompoundScope().setHasEmptyLoopBodies();
1192
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001193 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001194 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001195}
1196
John McCall60d7b3a2010-08-24 06:29:42 +00001197StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001198Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001199 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001200 Expr *Cond, SourceLocation CondRParen) {
1201 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001202
John Wiegley429bb272011-04-08 18:41:53 +00001203 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001204 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001205 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001206 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001207
Richard Smith41956372013-01-14 22:39:08 +00001208 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCall9ae2f072010-08-23 23:25:46 +00001209 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001210 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001211 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001212
John McCall9ae2f072010-08-23 23:25:46 +00001213 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001214
John McCall9ae2f072010-08-23 23:25:46 +00001215 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001216}
1217
Richard Trieu694e7962012-04-30 18:01:30 +00001218namespace {
1219 // This visitor will traverse a conditional statement and store all
1220 // the evaluated decls into a vector. Simple is set to true if none
1221 // of the excluded constructs are used.
1222 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1223 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001224 SmallVector<SourceRange, 10> &Ranges;
Richard Trieu694e7962012-04-30 18:01:30 +00001225 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001226public:
1227 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1228
1229 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001230 SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001231 Inherited(S.Context),
1232 Decls(Decls),
1233 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001234 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001235
1236 bool isSimple() { return Simple; }
1237
1238 // Replaces the method in EvaluatedExprVisitor.
1239 void VisitMemberExpr(MemberExpr* E) {
1240 Simple = false;
1241 }
1242
1243 // Any Stmt not whitelisted will cause the condition to be marked complex.
1244 void VisitStmt(Stmt *S) {
1245 Simple = false;
1246 }
1247
1248 void VisitBinaryOperator(BinaryOperator *E) {
1249 Visit(E->getLHS());
1250 Visit(E->getRHS());
1251 }
1252
1253 void VisitCastExpr(CastExpr *E) {
1254 Visit(E->getSubExpr());
1255 }
1256
1257 void VisitUnaryOperator(UnaryOperator *E) {
1258 // Skip checking conditionals with derefernces.
1259 if (E->getOpcode() == UO_Deref)
1260 Simple = false;
1261 else
1262 Visit(E->getSubExpr());
1263 }
1264
1265 void VisitConditionalOperator(ConditionalOperator *E) {
1266 Visit(E->getCond());
1267 Visit(E->getTrueExpr());
1268 Visit(E->getFalseExpr());
1269 }
1270
1271 void VisitParenExpr(ParenExpr *E) {
1272 Visit(E->getSubExpr());
1273 }
1274
1275 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1276 Visit(E->getOpaqueValue()->getSourceExpr());
1277 Visit(E->getFalseExpr());
1278 }
1279
1280 void VisitIntegerLiteral(IntegerLiteral *E) { }
1281 void VisitFloatingLiteral(FloatingLiteral *E) { }
1282 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1283 void VisitCharacterLiteral(CharacterLiteral *E) { }
1284 void VisitGNUNullExpr(GNUNullExpr *E) { }
1285 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1286
1287 void VisitDeclRefExpr(DeclRefExpr *E) {
1288 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1289 if (!VD) return;
1290
1291 Ranges.push_back(E->getSourceRange());
1292
1293 Decls.insert(VD);
1294 }
1295
1296 }; // end class DeclExtractor
1297
1298 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001299 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001300 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1301 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1302 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001303
1304public:
1305 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1306
1307 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1308 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1309 if (!Statement) return;
1310
1311 Visit(Statement);
1312 }
1313
1314 void VisitReturnStmt(ReturnStmt *S) {
1315 FoundDecl = true;
1316 }
1317
1318 void VisitBreakStmt(BreakStmt *S) {
1319 FoundDecl = true;
1320 }
1321
1322 void VisitGotoStmt(GotoStmt *S) {
1323 FoundDecl = true;
1324 }
1325
1326 void VisitCastExpr(CastExpr *E) {
1327 if (E->getCastKind() == CK_LValueToRValue)
1328 CheckLValueToRValueCast(E->getSubExpr());
1329 else
1330 Visit(E->getSubExpr());
1331 }
1332
1333 void CheckLValueToRValueCast(Expr *E) {
1334 E = E->IgnoreParenImpCasts();
1335
1336 if (isa<DeclRefExpr>(E)) {
1337 return;
1338 }
1339
1340 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1341 Visit(CO->getCond());
1342 CheckLValueToRValueCast(CO->getTrueExpr());
1343 CheckLValueToRValueCast(CO->getFalseExpr());
1344 return;
1345 }
1346
1347 if (BinaryConditionalOperator *BCO =
1348 dyn_cast<BinaryConditionalOperator>(E)) {
1349 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1350 CheckLValueToRValueCast(BCO->getFalseExpr());
1351 return;
1352 }
1353
1354 Visit(E);
1355 }
1356
1357 void VisitDeclRefExpr(DeclRefExpr *E) {
1358 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1359 if (Decls.count(VD))
1360 FoundDecl = true;
1361 }
1362
1363 bool FoundDeclInUse() { return FoundDecl; }
1364
1365 }; // end class DeclMatcher
1366
1367 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1368 Expr *Third, Stmt *Body) {
1369 // Condition is empty
1370 if (!Second) return;
1371
1372 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1373 Second->getLocStart())
1374 == DiagnosticsEngine::Ignored)
1375 return;
1376
1377 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1378 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001379 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001380 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001381 DE.Visit(Second);
1382
1383 // Don't analyze complex conditionals.
1384 if (!DE.isSimple()) return;
1385
1386 // No decls found.
1387 if (Decls.size() == 0) return;
1388
Richard Trieu90875992012-05-04 03:01:54 +00001389 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001390 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1391 E = Decls.end();
1392 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001393 if ((*I)->getType().isVolatileQualified() ||
1394 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001395
1396 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1397 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1398 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1399 return;
1400
1401 // Load decl names into diagnostic.
1402 if (Decls.size() > 4)
1403 PDiag << 0;
1404 else {
1405 PDiag << Decls.size();
1406 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1407 E = Decls.end();
1408 I != E; ++I)
1409 PDiag << (*I)->getDeclName();
1410 }
1411
1412 // Load SourceRanges into diagnostic if there is room.
1413 // Otherwise, load the SourceRange of the conditional expression.
1414 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001415 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1416 E = Ranges.end();
Richard Trieu694e7962012-04-30 18:01:30 +00001417 I != E; ++I)
1418 PDiag << *I;
1419 else
1420 PDiag << Second->getSourceRange();
1421
1422 S.Diag(Ranges.begin()->getBegin(), PDiag);
1423 }
1424
1425} // end namespace
1426
John McCall60d7b3a2010-08-24 06:29:42 +00001427StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001428Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001429 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001430 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001431 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001432 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001433 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001434 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1435 // declare identifiers for objects having storage class 'auto' or
1436 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001437 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1438 DI!=DE; ++DI) {
1439 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001440 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001441 VD = 0;
Douglas Gregor12849d02013-04-08 20:52:24 +00001442 if (VD == 0) {
1443 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1444 (*DI)->setInvalidDecl();
1445 }
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001446 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001447 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001449
Richard Trieu694e7962012-04-30 18:01:30 +00001450 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1451
John McCall60d7b3a2010-08-24 06:29:42 +00001452 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001453 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001454 if (secondVar) {
1455 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001456 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001457 if (SecondResult.isInvalid())
1458 return StmtError();
1459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001461 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462
Anders Carlsson3af708f2009-08-01 01:39:59 +00001463 DiagnoseUnusedExprResult(First);
1464 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001465 DiagnoseUnusedExprResult(Body);
1466
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001467 if (isa<NullStmt>(Body))
1468 getCurCompoundScope().setHasEmptyLoopBodies();
1469
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470 return Owned(new (Context) ForStmt(Context, First,
1471 SecondResult.take(), ConditionVar,
1472 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001473 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001474}
1475
John McCallf6a16482010-12-04 03:47:34 +00001476/// In an Objective C collection iteration statement:
1477/// for (x in y)
1478/// x can be an arbitrary l-value expression. Bind it up as a
1479/// full-expression.
1480StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001481 // Reduce placeholder expressions here. Note that this rejects the
1482 // use of pseudo-object l-values in this position.
1483 ExprResult result = CheckPlaceholderExpr(E);
1484 if (result.isInvalid()) return StmtError();
1485 E = result.take();
1486
Richard Smith41956372013-01-14 22:39:08 +00001487 ExprResult FullExpr = ActOnFinishFullExpr(E);
1488 if (FullExpr.isInvalid())
1489 return StmtError();
1490 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
John McCallf6a16482010-12-04 03:47:34 +00001491}
1492
John McCall990567c2011-07-27 01:07:15 +00001493ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001494Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1495 if (!collection)
1496 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001497
John McCall990567c2011-07-27 01:07:15 +00001498 // Bail out early if we've got a type-dependent expression.
1499 if (collection->isTypeDependent()) return Owned(collection);
1500
1501 // Perform normal l-value conversion.
1502 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1503 if (result.isInvalid())
1504 return ExprError();
1505 collection = result.take();
1506
1507 // The operand needs to have object-pointer type.
1508 // TODO: should we do a contextual conversion?
1509 const ObjCObjectPointerType *pointerType =
1510 collection->getType()->getAs<ObjCObjectPointerType>();
1511 if (!pointerType)
1512 return Diag(forLoc, diag::err_collection_expr_type)
1513 << collection->getType() << collection->getSourceRange();
1514
1515 // Check that the operand provides
1516 // - countByEnumeratingWithState:objects:count:
1517 const ObjCObjectType *objectType = pointerType->getObjectType();
1518 ObjCInterfaceDecl *iface = objectType->getInterface();
1519
1520 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001521 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001522 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001523 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001524 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001525 ? diag::err_arc_collection_forward
1526 : 0,
1527 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001528 // Otherwise, if we have any useful type information, check that
1529 // the type declares the appropriate method.
1530 } else if (iface || !objectType->qual_empty()) {
1531 IdentifierInfo *selectorIdents[] = {
1532 &Context.Idents.get("countByEnumeratingWithState"),
1533 &Context.Idents.get("objects"),
1534 &Context.Idents.get("count")
1535 };
1536 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1537
1538 ObjCMethodDecl *method = 0;
1539
1540 // If there's an interface, look in both the public and private APIs.
1541 if (iface) {
1542 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001543 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001544 }
1545
1546 // Also check protocol qualifiers.
1547 if (!method)
1548 method = LookupMethodInQualifiedType(selector, pointerType,
1549 /*instance*/ true);
1550
1551 // If we didn't find it anywhere, give up.
1552 if (!method) {
1553 Diag(forLoc, diag::warn_collection_expr_type)
1554 << collection->getType() << selector << collection->getSourceRange();
1555 }
1556
1557 // TODO: check for an incompatible signature?
1558 }
1559
1560 // Wrap up any cleanups in the expression.
Richard Smith41956372013-01-14 22:39:08 +00001561 return Owned(collection);
John McCall990567c2011-07-27 01:07:15 +00001562}
1563
John McCall60d7b3a2010-08-24 06:29:42 +00001564StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001565Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001566 Stmt *First, Expr *collection,
1567 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001568
1569 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001570 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001571
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001572 if (First) {
1573 QualType FirstType;
1574 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001575 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001576 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1577 diag::err_toomany_element_decls));
1578
Douglas Gregor12849d02013-04-08 20:52:24 +00001579 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1580 if (!D || D->isInvalidDecl())
1581 return StmtError();
1582
John McCallf85e1932011-06-15 23:02:42 +00001583 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001584 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1585 // declare identifiers for objects having storage class 'auto' or
1586 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001587 if (!D->hasLocalStorage())
1588 return StmtError(Diag(D->getLocation(),
Douglas Gregor12849d02013-04-08 20:52:24 +00001589 diag::err_non_local_variable_decl_in_for));
Douglas Gregor1cd1f732013-04-08 18:25:02 +00001590
1591 // If the type contained 'auto', deduce the 'auto' to 'id'.
1592 if (FirstType->getContainedAutoType()) {
1593 TypeSourceInfo *DeducedType = 0;
1594 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1595 VK_RValue);
1596 Expr *DeducedInit = &OpaqueId;
1597 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, DeducedType)
1598 == DAR_Failed) {
1599 DiagnoseAutoDeductionFailure(D, DeducedInit);
1600 }
1601 if (!DeducedType) {
1602 D->setInvalidDecl();
1603 return StmtError();
1604 }
1605
1606 D->setTypeSourceInfo(DeducedType);
1607 D->setType(DeducedType->getType());
1608 FirstType = DeducedType->getType();
1609
1610 if (ActiveTemplateInstantiations.empty()) {
1611 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
1612 Diag(Loc, diag::warn_auto_var_is_id)
1613 << D->getDeclName();
1614 }
1615 }
1616
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001617 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001618 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001619 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001620 return StmtError(Diag(First->getLocStart(),
1621 diag::err_selector_element_not_lvalue)
1622 << First->getSourceRange());
1623
Mike Stump1eb44332009-09-09 15:08:12 +00001624 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001625 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001626 if (!FirstType->isDependentType() &&
1627 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001628 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001629 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1630 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001631 }
Chad Rosier1093f492012-08-10 17:56:09 +00001632
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001633 if (CollectionExprResult.isInvalid())
1634 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001635
Richard Smith41956372013-01-14 22:39:08 +00001636 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1637 if (CollectionExprResult.isInvalid())
1638 return StmtError();
1639
Chad Rosier1093f492012-08-10 17:56:09 +00001640 return Owned(new (Context) ObjCForCollectionStmt(First,
1641 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001642 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001643}
Reid Spencer5f016e22007-07-11 17:01:13 +00001644
Richard Smithad762fc2011-04-14 22:09:26 +00001645/// Finish building a variable declaration for a for-range statement.
1646/// \return true if an error occurs.
1647static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1648 SourceLocation Loc, int diag) {
1649 // Deduce the type for the iterator variable now rather than leaving it to
1650 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1651 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001652 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001653 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1654 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001655 SemaRef.Diag(Loc, diag) << Init->getType();
1656 if (!InitTSI) {
1657 Decl->setInvalidDecl();
1658 return true;
1659 }
1660 Decl->setTypeSourceInfo(InitTSI);
1661 Decl->setType(InitTSI->getType());
1662
John McCallf85e1932011-06-15 23:02:42 +00001663 // In ARC, infer lifetime.
1664 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1665 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001666 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001667 SemaRef.inferObjCARCLifetime(Decl))
1668 Decl->setInvalidDecl();
1669
Richard Smithad762fc2011-04-14 22:09:26 +00001670 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1671 /*TypeMayContainAuto=*/false);
1672 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001673 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001674 return false;
1675}
1676
Sam Panzere1715b62012-08-21 00:52:01 +00001677namespace {
1678
Richard Smithad762fc2011-04-14 22:09:26 +00001679/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001680/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001681/// nor from the diagnostics produced when analysing the implicit expressions
1682/// required in a for-range statement.
1683void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001684 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001685 CallExpr *CE = dyn_cast<CallExpr>(E);
1686 if (!CE)
1687 return;
1688 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1689 if (!D)
1690 return;
1691 SourceLocation Loc = D->getLocation();
1692
1693 std::string Description;
1694 bool IsTemplate = false;
1695 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1696 Description = SemaRef.getTemplateArgumentBindingsText(
1697 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1698 IsTemplate = true;
1699 }
1700
1701 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1702 << BEF << IsTemplate << Description << E->getType();
1703}
1704
Sam Panzere1715b62012-08-21 00:52:01 +00001705/// Build a variable declaration for a for-range statement.
1706VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1707 QualType Type, const char *Name) {
1708 DeclContext *DC = SemaRef.CurContext;
1709 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1710 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1711 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001712 TInfo, SC_None);
Sam Panzere1715b62012-08-21 00:52:01 +00001713 Decl->setImplicit();
1714 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001715}
1716
1717}
1718
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001719static bool ObjCEnumerationCollection(Expr *Collection) {
1720 return !Collection->isTypeDependent()
1721 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1722}
1723
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001724/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001725///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001726/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001727/// A range-based for statement is equivalent to
1728///
1729/// {
1730/// auto && __range = range-init;
1731/// for ( auto __begin = begin-expr,
1732/// __end = end-expr;
1733/// __begin != __end;
1734/// ++__begin ) {
1735/// for-range-declaration = *__begin;
1736/// statement
1737/// }
1738/// }
1739///
1740/// The body of the loop is not available yet, since it cannot be analysed until
1741/// we have determined the type of the for-range-declaration.
1742StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001743Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001744 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001745 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001746 if (!First || !Range)
1747 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001748
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001749 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001750 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001751
1752 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1753 assert(DS && "first part of for range not a decl stmt");
1754
1755 if (!DS->isSingleDecl()) {
1756 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1757 return StmtError();
1758 }
1759 if (DS->getSingleDecl()->isInvalidDecl())
1760 return StmtError();
1761
1762 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1763 return StmtError();
1764
1765 // Build auto && __range = range-init
1766 SourceLocation RangeLoc = Range->getLocStart();
1767 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1768 Context.getAutoRRefDeductType(),
1769 "__range");
1770 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1771 diag::err_for_range_deduction_failure))
1772 return StmtError();
1773
1774 // Claim the type doesn't contain auto: we've already done the checking.
1775 DeclGroupPtrTy RangeGroup =
1776 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1777 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1778 if (RangeDecl.isInvalid())
1779 return StmtError();
1780
1781 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1782 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001783 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001784}
1785
1786/// \brief Create the initialization, compare, and increment steps for
1787/// the range-based for loop expression.
1788/// This function does not handle array-based for loops,
1789/// which are created in Sema::BuildCXXForRangeStmt.
1790///
1791/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1792/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1793/// CandidateSet and BEF are set and some non-success value is returned on
1794/// failure.
1795static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1796 Expr *BeginRange, Expr *EndRange,
1797 QualType RangeType,
1798 VarDecl *BeginVar,
1799 VarDecl *EndVar,
1800 SourceLocation ColonLoc,
1801 OverloadCandidateSet *CandidateSet,
1802 ExprResult *BeginExpr,
1803 ExprResult *EndExpr,
1804 Sema::BeginEndFunction *BEF) {
1805 DeclarationNameInfo BeginNameInfo(
1806 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1807 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1808 ColonLoc);
1809
1810 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1811 Sema::LookupMemberName);
1812 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1813
1814 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1815 // - if _RangeT is a class type, the unqualified-ids begin and end are
1816 // looked up in the scope of class _RangeT as if by class member access
1817 // lookup (3.4.5), and if either (or both) finds at least one
1818 // declaration, begin-expr and end-expr are __range.begin() and
1819 // __range.end(), respectively;
1820 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1821 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1822
1823 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1824 SourceLocation RangeLoc = BeginVar->getLocation();
1825 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1826
1827 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1828 << RangeLoc << BeginRange->getType() << *BEF;
1829 return Sema::FRS_DiagnosticIssued;
1830 }
1831 } else {
1832 // - otherwise, begin-expr and end-expr are begin(__range) and
1833 // end(__range), respectively, where begin and end are looked up with
1834 // argument-dependent lookup (3.4.2). For the purposes of this name
1835 // lookup, namespace std is an associated namespace.
1836
1837 }
1838
1839 *BEF = Sema::BEF_begin;
1840 Sema::ForRangeStatus RangeStatus =
1841 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1842 Sema::BEF_begin, BeginNameInfo,
1843 BeginMemberLookup, CandidateSet,
1844 BeginRange, BeginExpr);
1845
1846 if (RangeStatus != Sema::FRS_Success)
1847 return RangeStatus;
1848 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1849 diag::err_for_range_iter_deduction_failure)) {
1850 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1851 return Sema::FRS_DiagnosticIssued;
1852 }
1853
1854 *BEF = Sema::BEF_end;
1855 RangeStatus =
1856 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1857 Sema::BEF_end, EndNameInfo,
1858 EndMemberLookup, CandidateSet,
1859 EndRange, EndExpr);
1860 if (RangeStatus != Sema::FRS_Success)
1861 return RangeStatus;
1862 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1863 diag::err_for_range_iter_deduction_failure)) {
1864 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1865 return Sema::FRS_DiagnosticIssued;
1866 }
1867 return Sema::FRS_Success;
1868}
1869
1870/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001871/// If the attempt fails, this function will return a valid, null StmtResult
1872/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001873static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1874 SourceLocation ForLoc,
1875 Stmt *LoopVarDecl,
1876 SourceLocation ColonLoc,
1877 Expr *Range,
1878 SourceLocation RangeLoc,
1879 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001880 // Determine whether we can rebuild the for-range statement with a
1881 // dereferenced range expression.
1882 ExprResult AdjustedRange;
1883 {
1884 Sema::SFINAETrap Trap(SemaRef);
1885
1886 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1887 if (AdjustedRange.isInvalid())
1888 return StmtResult();
1889
1890 StmtResult SR =
1891 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1892 AdjustedRange.get(), RParenLoc,
1893 Sema::BFRK_Check);
1894 if (SR.isInvalid())
1895 return StmtResult();
1896 }
1897
1898 // The attempt to dereference worked well enough that it could produce a valid
1899 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1900 // case there are any other (non-fatal) problems with it.
1901 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1902 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1903 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1904 AdjustedRange.get(), RParenLoc,
1905 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001906}
1907
Richard Smith8b533d92012-09-20 21:52:32 +00001908/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001909StmtResult
1910Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1911 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1912 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001913 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001914 Scope *S = getCurScope();
1915
1916 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1917 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1918 QualType RangeVarType = RangeVar->getType();
1919
1920 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1921 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1922
1923 StmtResult BeginEndDecl = BeginEnd;
1924 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1925
1926 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1927 SourceLocation RangeLoc = RangeVar->getLocation();
1928
Ted Kremeneke50b0152011-10-10 22:36:28 +00001929 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1930
1931 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1932 VK_LValue, ColonLoc);
1933 if (BeginRangeRef.isInvalid())
1934 return StmtError();
1935
1936 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1937 VK_LValue, ColonLoc);
1938 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001939 return StmtError();
1940
1941 QualType AutoType = Context.getAutoDeductType();
1942 Expr *Range = RangeVar->getInit();
1943 if (!Range)
1944 return StmtError();
1945 QualType RangeType = Range->getType();
1946
1947 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001948 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001949 return StmtError();
1950
1951 // Build auto __begin = begin-expr, __end = end-expr.
1952 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1953 "__begin");
1954 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1955 "__end");
1956
1957 // Build begin-expr and end-expr and attach to __begin and __end variables.
1958 ExprResult BeginExpr, EndExpr;
1959 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1960 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1961 // __range + __bound, respectively, where __bound is the array bound. If
1962 // _RangeT is an array of unknown size or an array of incomplete type,
1963 // the program is ill-formed;
1964
1965 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001966 BeginExpr = BeginRangeRef;
1967 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001968 diag::err_for_range_iter_deduction_failure)) {
1969 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1970 return StmtError();
1971 }
1972
1973 // Find the array bound.
1974 ExprResult BoundExpr;
1975 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1976 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001977 Context.getPointerDiffType(),
1978 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001979 else if (const VariableArrayType *VAT =
1980 dyn_cast<VariableArrayType>(UnqAT))
1981 BoundExpr = VAT->getSizeExpr();
1982 else {
1983 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1984 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001985 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001986 }
1987
1988 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001989 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001990 BoundExpr.get());
1991 if (EndExpr.isInvalid())
1992 return StmtError();
1993 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1994 diag::err_for_range_iter_deduction_failure)) {
1995 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1996 return StmtError();
1997 }
1998 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001999 OverloadCandidateSet CandidateSet(RangeLoc);
2000 Sema::BeginEndFunction BEFFailure;
2001 ForRangeStatus RangeStatus =
2002 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2003 EndRangeRef.get(), RangeType,
2004 BeginVar, EndVar, ColonLoc, &CandidateSet,
2005 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00002006
Sam Panzere1715b62012-08-21 00:52:01 +00002007 // If building the range failed, try dereferencing the range expression
2008 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00002009 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00002010 BEFFailure == BEF_begin) {
2011 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2012 LoopVarDecl, ColonLoc,
2013 Range, RangeLoc,
2014 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00002015 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00002016 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00002017 }
2018
Sam Panzere1715b62012-08-21 00:52:01 +00002019 // Otherwise, emit diagnostics if we haven't already.
2020 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00002021 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00002022 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2023 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00002024 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00002025 }
2026 // Return an error if no fix was discovered.
2027 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00002028 return StmtError();
2029 }
2030
Sam Panzere1715b62012-08-21 00:52:01 +00002031 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2032 "invalid range expression in for loop");
2033
2034 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00002035 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2036 if (!Context.hasSameType(BeginType, EndType)) {
2037 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2038 << BeginType << EndType;
2039 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2040 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2041 }
2042
2043 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2044 // Claim the type doesn't contain auto: we've already done the checking.
2045 DeclGroupPtrTy BeginEndGroup =
2046 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
2047 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2048
Ted Kremeneke50b0152011-10-10 22:36:28 +00002049 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2050 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00002051 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002052 if (BeginRef.isInvalid())
2053 return StmtError();
2054
Richard Smithad762fc2011-04-14 22:09:26 +00002055 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2056 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00002057 if (EndRef.isInvalid())
2058 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00002059
2060 // Build and check __begin != __end expression.
2061 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2062 BeginRef.get(), EndRef.get());
2063 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2064 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2065 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002066 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2067 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002068 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2069 if (!Context.hasSameType(BeginType, EndType))
2070 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2071 return StmtError();
2072 }
2073
2074 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002075 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2076 VK_LValue, ColonLoc);
2077 if (BeginRef.isInvalid())
2078 return StmtError();
2079
Richard Smithad762fc2011-04-14 22:09:26 +00002080 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2081 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2082 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002083 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2084 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002085 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2086 return StmtError();
2087 }
2088
2089 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002090 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2091 VK_LValue, ColonLoc);
2092 if (BeginRef.isInvalid())
2093 return StmtError();
2094
Richard Smithad762fc2011-04-14 22:09:26 +00002095 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2096 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002097 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2098 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002099 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2100 return StmtError();
2101 }
2102
Richard Smith8b533d92012-09-20 21:52:32 +00002103 // Attach *__begin as initializer for VD. Don't touch it if we're just
2104 // trying to determine whether this would be a valid range.
2105 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002106 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2107 /*TypeMayContainAuto=*/true);
2108 if (LoopVar->isInvalidDecl())
2109 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2110 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002111 } else {
2112 // The range is implicitly used as a placeholder when it is dependent.
2113 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002114 }
2115
Richard Smith8b533d92012-09-20 21:52:32 +00002116 // Don't bother to actually allocate the result if we're just trying to
2117 // determine whether it would be valid.
2118 if (Kind == BFRK_Check)
2119 return StmtResult();
2120
Richard Smithad762fc2011-04-14 22:09:26 +00002121 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2122 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2123 NotEqExpr.take(), IncrExpr.take(),
2124 LoopVarDS, /*Body=*/0, ForLoc,
2125 ColonLoc, RParenLoc));
2126}
2127
Chad Rosier1093f492012-08-10 17:56:09 +00002128/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002129/// statement.
2130StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2131 if (!S || !B)
2132 return StmtError();
2133 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002134
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002135 ForStmt->setBody(B);
2136 return S;
2137}
2138
Richard Smithad762fc2011-04-14 22:09:26 +00002139/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2140/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2141/// body cannot be performed until after the type of the range variable is
2142/// determined.
2143StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2144 if (!S || !B)
2145 return StmtError();
2146
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002147 if (isa<ObjCForCollectionStmt>(S))
2148 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002149
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002150 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2151 ForStmt->setBody(B);
2152
2153 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2154 diag::warn_empty_range_based_for_body);
2155
Richard Smithad762fc2011-04-14 22:09:26 +00002156 return S;
2157}
2158
Chris Lattner57ad3782011-02-17 20:34:02 +00002159StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2160 SourceLocation LabelLoc,
2161 LabelDecl *TheDecl) {
2162 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002163 TheDecl->setUsed();
2164 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002165}
2166
John McCall60d7b3a2010-08-24 06:29:42 +00002167StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002168Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002169 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002170 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002171 if (!E->isTypeDependent()) {
2172 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002173 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002174 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002175 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002176 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2177 if (ExprRes.isInvalid())
2178 return StmtError();
2179 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002180 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002181 return StmtError();
2182 }
John McCallb60a77e2010-08-01 00:26:45 +00002183
Richard Smith41956372013-01-14 22:39:08 +00002184 ExprResult ExprRes = ActOnFinishFullExpr(E);
2185 if (ExprRes.isInvalid())
2186 return StmtError();
2187 E = ExprRes.take();
2188
John McCall781472f2010-08-25 08:40:02 +00002189 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002190
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002191 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002192}
2193
John McCall60d7b3a2010-08-24 06:29:42 +00002194StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002195Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 Scope *S = CurScope->getContinueParent();
2197 if (!S) {
2198 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002199 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002201
Ted Kremenek8189cde2009-02-07 01:47:29 +00002202 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002203}
2204
John McCall60d7b3a2010-08-24 06:29:42 +00002205StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002206Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 Scope *S = CurScope->getBreakParent();
2208 if (!S) {
2209 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002210 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002212
Ted Kremenek8189cde2009-02-07 01:47:29 +00002213 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002214}
2215
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002216/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002217/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002218///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002219/// \param ReturnType If we're determining the copy elision candidate for
2220/// a return statement, this is the return type of the function. If we're
2221/// determining the copy elision candidate for a throw expression, this will
2222/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002223///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002224/// \param E The expression being returned from the function or block, or
2225/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002226///
Douglas Gregor4926d832011-05-20 15:00:53 +00002227/// \param AllowFunctionParameter Whether we allow function parameters to
2228/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2229/// we re-use this logic to determine whether we should try to move as part of
2230/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002231///
2232/// \returns The NRVO candidate variable, if the return statement may use the
2233/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002234const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2235 Expr *E,
2236 bool AllowFunctionParameter) {
2237 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002238 // - in a return statement in a function with ...
2239 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002240 if (!ReturnType.isNull()) {
2241 if (!ReturnType->isRecordType())
2242 return 0;
2243 // ... the same cv-unqualified type as the function return type ...
2244 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2245 return 0;
2246 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002247
2248 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002249 // (other than a function or catch-clause parameter)) ...
2250 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002251 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002252 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002253 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2254 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002255 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002256
John McCall1cd76e82011-11-11 03:57:31 +00002257 // ...object (other than a function or catch-clause parameter)...
2258 if (VD->getKind() != Decl::Var &&
2259 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2260 return 0;
2261 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002262
John McCall1cd76e82011-11-11 03:57:31 +00002263 // ...automatic...
2264 if (!VD->hasLocalStorage()) return 0;
2265
2266 // ...non-volatile...
2267 if (VD->getType().isVolatileQualified()) return 0;
2268 if (VD->getType()->isReferenceType()) return 0;
2269
2270 // __block variables can't be allocated in a way that permits NRVO.
2271 if (VD->hasAttr<BlocksAttr>()) return 0;
2272
2273 // Variables with higher required alignment than their type's ABI
2274 // alignment cannot use NRVO.
2275 if (VD->hasAttr<AlignedAttr>() &&
2276 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2277 return 0;
2278
2279 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002280}
2281
Douglas Gregor07f402c2011-01-21 21:08:57 +00002282/// \brief Perform the initialization of a potentially-movable value, which
2283/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002284///
2285/// This routine implements C++0x [class.copy]p33, which attempts to treat
2286/// returned lvalues as rvalues in certain cases (to prefer move construction),
2287/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002288ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002289Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2290 const VarDecl *NRVOCandidate,
2291 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002292 Expr *Value,
2293 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002294 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002295 // When the criteria for elision of a copy operation are met or would
2296 // be met save for the fact that the source object is a function
2297 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002298 // overload resolution to select the constructor for the copy is first
2299 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002300 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002301 if (AllowNRVO &&
2302 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002303 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002304 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002305
Douglas Gregorcc15f012011-01-21 19:38:21 +00002306 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002307 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002308 = InitializationKind::CreateCopy(Value->getLocStart(),
2309 Value->getLocStart());
2310 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002311
2312 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002313 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002314 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002315 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002316 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002317 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2318 StepEnd = Seq.step_end();
2319 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002320 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002321 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002322
2323 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002324 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002325
Douglas Gregorcc15f012011-01-21 19:38:21 +00002326 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002327 = Constructor->getParamDecl(0)->getType()
2328 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002329
Douglas Gregorcc15f012011-01-21 19:38:21 +00002330 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002331 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002332 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2333 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002334 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335
Douglas Gregorcc15f012011-01-21 19:38:21 +00002336 // Promote "AsRvalue" to the heap, since we now need this
2337 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002338 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002339 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002340
Douglas Gregorcc15f012011-01-21 19:38:21 +00002341 // Complete type-checking the initialization of the return type
2342 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002343 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002344 }
2345 }
2346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002347
Douglas Gregorcc15f012011-01-21 19:38:21 +00002348 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002350 // (again) now with the return value expression as written.
2351 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002352 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002353
Douglas Gregorcc15f012011-01-21 19:38:21 +00002354 return Res;
2355}
2356
Eli Friedman84b007f2012-01-26 03:00:14 +00002357/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2358/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002359///
John McCall60d7b3a2010-08-24 06:29:42 +00002360StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002361Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2362 // If this is the first return we've seen, infer the return type.
2363 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2364 // rules which allows multiple return statements.
2365 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002366 QualType FnRetType = CurCap->ReturnType;
2367
2368 // For blocks/lambdas with implicit return types, we check each return
2369 // statement individually, and deduce the common return type when the block
2370 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002371 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002372 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002373 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2374 if (Result.isInvalid())
2375 return StmtError();
2376 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002377
Jordan Rose7dd900e2012-07-02 21:19:23 +00002378 if (!RetValExp->isTypeDependent())
2379 FnRetType = RetValExp->getType();
2380 else
2381 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002382 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002383 if (RetValExp) {
2384 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2385 // initializer list, because it is not an expression (even
2386 // though we represent it as one). We still deduce 'void'.
2387 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2388 << RetValExp->getSourceRange();
2389 }
2390
Jordan Rose7dd900e2012-07-02 21:19:23 +00002391 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002392 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002393
2394 // Although we'll properly infer the type of the block once it's completed,
2395 // make sure we provide a return type now for better error recovery.
2396 if (CurCap->ReturnType.isNull())
2397 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002398 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002399 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002400
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002401 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002402 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2403 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2404 return StmtError();
2405 }
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00002406 } else if (CapturedRegionScopeInfo *CurRegion =
2407 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2408 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2409 return StmtError();
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002410 } else {
2411 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2412 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2413 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2414 return StmtError();
2415 }
2416 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002417
Steve Naroff4eb206b2008-09-03 18:15:37 +00002418 // Otherwise, verify that this result type matches the previous one. We are
2419 // pickier with blocks than for normal functions because we don't have GCC
2420 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002421 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002422 if (FnRetType->isDependentType()) {
2423 // Delay processing for now. TODO: there are lots of dependent
2424 // types we can conclusively prove aren't void.
2425 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002426 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002427 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002428 (RetValExp->isTypeDependent() ||
2429 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002430 if (!getLangOpts().CPlusPlus &&
2431 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002432 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002433 else {
2434 Diag(ReturnLoc, diag::err_return_block_has_expr);
2435 RetValExp = 0;
2436 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002437 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002438 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002439 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2440 } else if (!RetValExp->isTypeDependent()) {
2441 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002442
John McCall0a7efe12011-08-17 22:09:46 +00002443 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2444 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2445 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002446
John McCall0a7efe12011-08-17 22:09:46 +00002447 // In C++ the return statement is handled via a copy initialization.
2448 // the C version of which boils down to CheckSingleAssignmentConstraints.
2449 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2450 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2451 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002452 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002453 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2454 FnRetType, RetValExp);
2455 if (Res.isInvalid()) {
2456 // FIXME: Cleanup temporaries here, anyway?
2457 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002458 }
John McCall0a7efe12011-08-17 22:09:46 +00002459 RetValExp = Res.take();
2460 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002461 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002462
John McCalld963c372011-08-17 21:34:14 +00002463 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002464 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2465 if (ER.isInvalid())
2466 return StmtError();
2467 RetValExp = ER.take();
John McCalld963c372011-08-17 21:34:14 +00002468 }
John McCall0a7efe12011-08-17 22:09:46 +00002469 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2470 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002471
Jordan Rose7dd900e2012-07-02 21:19:23 +00002472 // If we need to check for the named return value optimization,
2473 // or if we need to infer the return type,
2474 // save the return statement in our scope for later processing.
2475 if (CurCap->HasImplicitReturnType ||
2476 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2477 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002478 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002479
Douglas Gregor5077c382010-05-15 06:01:05 +00002480 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002481}
Reid Spencer5f016e22007-07-11 17:01:13 +00002482
John McCall60d7b3a2010-08-24 06:29:42 +00002483StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002484Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002485 // Check for unexpanded parameter packs.
2486 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2487 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002488
Eli Friedman84b007f2012-01-26 03:00:14 +00002489 if (isa<CapturingScopeInfo>(getCurFunction()))
2490 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002491
Chris Lattner371f2582008-12-04 23:50:19 +00002492 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002493 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002494 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002495 FnRetType = FD->getResultType();
Richard Smithcd8ab512013-01-17 01:30:42 +00002496 if (FD->isNoReturn())
Chris Lattner86625872009-05-31 19:32:13 +00002497 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002498 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002499 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002500 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002501 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2502 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002503 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002504 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002505 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2506 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002507 }
2508 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002509 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Douglas Gregor5077c382010-05-15 06:01:05 +00002511 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002512 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002513 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002514 if (isa<InitListExpr>(RetValExp)) {
2515 // We simply never allow init lists as the return value of void
2516 // functions. This is compatible because this was never allowed before,
2517 // so there's no legacy code to deal with.
2518 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2519 int FunctionKind = 0;
2520 if (isa<ObjCMethodDecl>(CurDecl))
2521 FunctionKind = 1;
2522 else if (isa<CXXConstructorDecl>(CurDecl))
2523 FunctionKind = 2;
2524 else if (isa<CXXDestructorDecl>(CurDecl))
2525 FunctionKind = 3;
2526
2527 Diag(ReturnLoc, diag::err_return_init_list)
2528 << CurDecl->getDeclName() << FunctionKind
2529 << RetValExp->getSourceRange();
2530
2531 // Drop the expression.
2532 RetValExp = 0;
2533 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002534 // C99 6.8.6.4p1 (ext_ since GCC warns)
2535 unsigned D = diag::ext_return_has_expr;
2536 if (RetValExp->getType()->isVoidType())
2537 D = diag::ext_return_has_void_expr;
2538 else {
2539 ExprResult Result = Owned(RetValExp);
2540 Result = IgnoredValueConversions(Result.take());
2541 if (Result.isInvalid())
2542 return StmtError();
2543 RetValExp = Result.take();
2544 RetValExp = ImpCastExprToType(RetValExp,
2545 Context.VoidTy, CK_ToVoid).take();
2546 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002547
Nick Lewycky8d794612011-06-01 07:44:31 +00002548 // return (some void expression); is legal in C++.
2549 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002550 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002551 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002552
2553 int FunctionKind = 0;
2554 if (isa<ObjCMethodDecl>(CurDecl))
2555 FunctionKind = 1;
2556 else if (isa<CXXConstructorDecl>(CurDecl))
2557 FunctionKind = 2;
2558 else if (isa<CXXDestructorDecl>(CurDecl))
2559 FunctionKind = 3;
2560
Nick Lewycky8d794612011-06-01 07:44:31 +00002561 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002562 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002563 << RetValExp->getSourceRange();
2564 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002565 }
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Sebastian Redl33deb352012-02-22 10:50:08 +00002567 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002568 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2569 if (ER.isInvalid())
2570 return StmtError();
2571 RetValExp = ER.take();
Sebastian Redl33deb352012-02-22 10:50:08 +00002572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002574
Douglas Gregor5077c382010-05-15 06:01:05 +00002575 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2576 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002577 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2578 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002579 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002580
2581 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002582 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002583 else
Chris Lattner08631c52008-11-23 21:45:46 +00002584 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002585 Result = new (Context) ReturnStmt(ReturnLoc);
2586 } else {
Jordan Rose41f3f3a2013-03-05 01:27:54 +00002587 assert(RetValExp || FnRetType->isDependentType());
Douglas Gregor5077c382010-05-15 06:01:05 +00002588 const VarDecl *NRVOCandidate = 0;
2589 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2590 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002591
John McCall7cca8212013-03-19 07:04:25 +00002592 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
Eli Friedman38ac2432012-03-30 01:13:43 +00002593
Douglas Gregor5077c382010-05-15 06:01:05 +00002594 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2595 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2596 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002597
John McCall856d3792011-06-16 23:24:51 +00002598 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002599 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002600 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002601 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall7cca8212013-03-19 07:04:25 +00002602 RetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002603 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002604 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall7cca8212013-03-19 07:04:25 +00002605 RetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002606 if (Res.isInvalid()) {
John McCall7cca8212013-03-19 07:04:25 +00002607 // FIXME: Clean up temporaries here anyway?
Douglas Gregor5077c382010-05-15 06:01:05 +00002608 return StmtError();
2609 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002610 RetValExp = Res.takeAs<Expr>();
John McCall7cca8212013-03-19 07:04:25 +00002611
2612 // If we have a related result type, we need to implicitly
2613 // convert back to the formal result type. We can't pretend to
2614 // initialize the result again --- we might end double-retaining
2615 // --- so instead we initialize a notional temporary; this can
2616 // lead to less-than-great diagnostics, but this stage is much
2617 // less likely to fail than the previous stage.
2618 if (!RelatedRetType.isNull()) {
2619 Entity = InitializedEntity::InitializeTemporary(FnRetType);
2620 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2621 if (Res.isInvalid()) {
2622 // FIXME: Clean up temporaries here anyway?
2623 return StmtError();
2624 }
2625 RetValExp = Res.takeAs<Expr>();
2626 }
2627
2628 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630
John McCallb4eb64d2010-10-08 02:01:28 +00002631 if (RetValExp) {
Richard Smith41956372013-01-14 22:39:08 +00002632 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2633 if (ER.isInvalid())
2634 return StmtError();
2635 RetValExp = ER.take();
John McCallb4eb64d2010-10-08 02:01:28 +00002636 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002637 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002638 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002639
2640 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002641 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002642 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002643 !CurContext->isDependentContext())
2644 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002645
Douglas Gregor5077c382010-05-15 06:01:05 +00002646 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002647}
2648
John McCall60d7b3a2010-08-24 06:29:42 +00002649StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002650Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002651 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002652 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002653 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002654 if (Var && Var->isInvalidDecl())
2655 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656
John McCall9ae2f072010-08-23 23:25:46 +00002657 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002658}
2659
John McCall60d7b3a2010-08-24 06:29:42 +00002660StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002661Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2662 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002663}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002664
John McCall60d7b3a2010-08-24 06:29:42 +00002665StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002666Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002667 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002668 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002669 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2670
John McCall781472f2010-08-25 08:40:02 +00002671 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002672 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002673 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002674 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002675 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002676 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002677}
2678
John McCalld1376ee2012-05-08 21:41:25 +00002679StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002680 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002681 ExprResult Result = DefaultLvalueConversion(Throw);
2682 if (Result.isInvalid())
2683 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002684
Richard Smith41956372013-01-14 22:39:08 +00002685 Result = ActOnFinishFullExpr(Result.take());
2686 if (Result.isInvalid())
2687 return StmtError();
2688 Throw = Result.take();
2689
Douglas Gregord1377b22010-04-22 21:44:01 +00002690 QualType ThrowType = Throw->getType();
2691 // Make sure the expression type is an ObjC pointer or "void *".
2692 if (!ThrowType->isDependentType() &&
2693 !ThrowType->isObjCObjectPointerType()) {
2694 const PointerType *PT = ThrowType->getAs<PointerType>();
2695 if (!PT || !PT->getPointeeType()->isVoidType())
2696 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2697 << Throw->getType() << Throw->getSourceRange());
2698 }
2699 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700
John McCall9ae2f072010-08-23 23:25:46 +00002701 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002702}
2703
John McCall60d7b3a2010-08-24 06:29:42 +00002704StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002705Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002706 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002707 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002708 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2709
John McCall9ae2f072010-08-23 23:25:46 +00002710 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002711 // @throw without an expression designates a rethrow (which much occur
2712 // in the context of an @catch clause).
2713 Scope *AtCatchParent = CurScope;
2714 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2715 AtCatchParent = AtCatchParent->getParent();
2716 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002717 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002718 }
John McCall9ae2f072010-08-23 23:25:46 +00002719 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002720}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002721
John McCall07524032011-07-27 21:50:02 +00002722ExprResult
2723Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2724 ExprResult result = DefaultLvalueConversion(operand);
2725 if (result.isInvalid())
2726 return ExprError();
2727 operand = result.take();
2728
2729 // Make sure the expression type is an ObjC pointer or "void *".
2730 QualType type = operand->getType();
2731 if (!type->isDependentType() &&
2732 !type->isObjCObjectPointerType()) {
2733 const PointerType *pointerType = type->getAs<PointerType>();
2734 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2735 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2736 << type << operand->getSourceRange();
2737 }
2738
2739 // The operand to @synchronized is a full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002740 return ActOnFinishFullExpr(operand);
John McCall07524032011-07-27 21:50:02 +00002741}
2742
John McCall60d7b3a2010-08-24 06:29:42 +00002743StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002744Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2745 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002746 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002747 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002748 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002749}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002750
2751/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2752/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002753StmtResult
John McCalld226f652010-08-21 09:40:31 +00002754Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002755 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002756 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002757 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002758 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002759 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002760}
Sebastian Redl8351da02008-12-22 21:35:02 +00002761
John McCallf85e1932011-06-15 23:02:42 +00002762StmtResult
2763Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2764 getCurFunction()->setHasBranchProtectedScope();
2765 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2766}
2767
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002768namespace {
2769
Sebastian Redlc447aba2009-07-29 17:15:45 +00002770class TypeWithHandler {
2771 QualType t;
2772 CXXCatchStmt *stmt;
2773public:
2774 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2775 : t(type), stmt(statement) {}
2776
John McCall0953e762009-09-24 19:53:00 +00002777 // An arbitrary order is fine as long as it places identical
2778 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002779 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002780 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002781 return true;
John McCall0953e762009-09-24 19:53:00 +00002782 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002783 return false;
2784 else
2785 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2786 }
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Sebastian Redlc447aba2009-07-29 17:15:45 +00002788 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002789 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002790 }
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Sebastian Redlc447aba2009-07-29 17:15:45 +00002792 CXXCatchStmt *getCatchStmt() const { return stmt; }
2793 SourceLocation getTypeSpecStartLoc() const {
2794 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2795 }
2796};
2797
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002798}
2799
Sebastian Redl8351da02008-12-22 21:35:02 +00002800/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2801/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002802StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002803Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002804 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002805 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002806 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002807 !getSourceManager().isInSystemHeader(TryLoc))
2808 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002809
Sebastian Redl8351da02008-12-22 21:35:02 +00002810 unsigned NumHandlers = RawHandlers.size();
2811 assert(NumHandlers > 0 &&
2812 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002813 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002814
Chris Lattner5f9e2722011-07-23 10:55:15 +00002815 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002816
2817 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002818 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002819 if (!Handler->getExceptionDecl()) {
2820 if (i < NumHandlers - 1)
2821 return StmtError(Diag(Handler->getLocStart(),
2822 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Sebastian Redlc447aba2009-07-29 17:15:45 +00002824 continue;
2825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Sebastian Redlc447aba2009-07-29 17:15:45 +00002827 const QualType CaughtType = Handler->getCaughtType();
2828 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2829 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002830 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002831
2832 // Detect handlers for the same type as an earlier one.
2833 if (NumHandlers > 1) {
2834 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Sebastian Redlc447aba2009-07-29 17:15:45 +00002836 TypeWithHandler prev = TypesWithHandlers[0];
2837 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2838 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Sebastian Redlc447aba2009-07-29 17:15:45 +00002840 if (curr == prev) {
2841 Diag(curr.getTypeSpecStartLoc(),
2842 diag::warn_exception_caught_by_earlier_handler)
2843 << curr.getCatchStmt()->getCaughtType().getAsString();
2844 Diag(prev.getTypeSpecStartLoc(),
2845 diag::note_previous_exception_handler)
2846 << prev.getCatchStmt()->getCaughtType().getAsString();
2847 }
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Sebastian Redlc447aba2009-07-29 17:15:45 +00002849 prev = curr;
2850 }
2851 }
Mike Stump1eb44332009-09-09 15:08:12 +00002852
John McCall781472f2010-08-25 08:40:02 +00002853 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002854
Sebastian Redl8351da02008-12-22 21:35:02 +00002855 // FIXME: We should detect handlers that cannot catch anything because an
2856 // earlier handler catches a superclass. Need to find a method that is not
2857 // quadratic for this.
2858 // Neither of these are explicitly forbidden, but every compiler detects them
2859 // and warns.
2860
John McCall9ae2f072010-08-23 23:25:46 +00002861 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002862 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002863}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002864
2865StmtResult
2866Sema::ActOnSEHTryBlock(bool IsCXXTry,
2867 SourceLocation TryLoc,
2868 Stmt *TryBlock,
2869 Stmt *Handler) {
2870 assert(TryBlock && Handler);
2871
2872 getCurFunction()->setHasBranchProtectedScope();
2873
2874 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2875}
2876
2877StmtResult
2878Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2879 Expr *FilterExpr,
2880 Stmt *Block) {
2881 assert(FilterExpr && Block);
2882
2883 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002884 return StmtError(Diag(FilterExpr->getExprLoc(),
2885 diag::err_filter_expression_integral)
2886 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002887 }
2888
2889 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2890}
2891
2892StmtResult
2893Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2894 Stmt *Block) {
2895 assert(Block);
2896 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2897}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002898
2899StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2900 bool IsIfExists,
2901 NestedNameSpecifierLoc QualifierLoc,
2902 DeclarationNameInfo NameInfo,
2903 Stmt *Nested)
2904{
2905 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002906 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002907 cast<CompoundStmt>(Nested));
2908}
2909
2910
Chad Rosier1093f492012-08-10 17:56:09 +00002911StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002912 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002913 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002914 UnqualifiedId &Name,
2915 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002916 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002917 SS.getWithLocInContext(Context),
2918 GetNameFromUnqualifiedId(Name),
2919 Nested);
2920}
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00002921
2922RecordDecl*
2923Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc)
2924{
2925 DeclContext *DC = CurContext;
2926 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
2927 DC = DC->getParent();
2928
2929 RecordDecl *RD = 0;
2930 if (getLangOpts().CPlusPlus)
2931 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
2932 else
2933 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
2934
2935 DC->addDecl(RD);
2936 RD->setImplicit();
2937 RD->startDefinition();
2938
2939 CD = CapturedDecl::Create(Context, CurContext);
2940 DC->addDecl(CD);
2941
2942 return RD;
2943}
2944
2945static void buildCapturedStmtCaptureList(
2946 SmallVectorImpl<CapturedStmt::Capture> &Captures,
2947 SmallVectorImpl<Expr *> &CaptureInits,
2948 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
2949
2950 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
2951 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
2952
2953 if (Cap->isThisCapture()) {
2954 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
2955 CapturedStmt::VCK_This));
2956 CaptureInits.push_back(Cap->getCopyExpr());
2957 continue;
2958 }
2959
2960 assert(Cap->isReferenceCapture() &&
2961 "non-reference capture not yet implemented");
2962
2963 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
2964 CapturedStmt::VCK_ByRef,
2965 Cap->getVariable()));
2966 CaptureInits.push_back(Cap->getCopyExpr());
2967 }
2968}
2969
2970void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
2971 CapturedRegionScopeInfo::CapturedRegionKind Kind) {
2972 CapturedDecl *CD = 0;
2973 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc);
2974
2975 // Enter the capturing scope for this captured region.
2976 PushCapturedRegionScope(CurScope, CD, RD, Kind);
2977
2978 if (CurScope)
2979 PushDeclContext(CurScope, CD);
2980 else
2981 CurContext = CD;
2982
2983 PushExpressionEvaluationContext(PotentiallyEvaluated);
2984}
2985
2986void Sema::ActOnCapturedRegionError(bool IsInstantiation) {
2987 DiscardCleanupsInEvaluationContext();
2988 PopExpressionEvaluationContext();
2989
2990 if (!IsInstantiation)
2991 PopDeclContext();
2992
2993 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
2994 RecordDecl *Record = RSI->TheRecordDecl;
2995 Record->setInvalidDecl();
2996
2997 SmallVector<Decl*, 4> Fields;
2998 for (RecordDecl::field_iterator I = Record->field_begin(),
2999 E = Record->field_end(); I != E; ++I)
3000 Fields.push_back(*I);
3001 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3002 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3003
3004 PopFunctionScopeInfo();
3005}
3006
3007StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3008 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3009
3010 SmallVector<CapturedStmt::Capture, 4> Captures;
3011 SmallVector<Expr *, 4> CaptureInits;
3012 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3013
3014 CapturedDecl *CD = RSI->TheCapturedDecl;
3015 RecordDecl *RD = RSI->TheRecordDecl;
3016
3017 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S, Captures,
3018 CaptureInits, CD, RD);
3019
3020 CD->setBody(Res->getCapturedStmt());
3021 RD->completeDefinition();
3022
3023 PopDeclContext();
3024 PopFunctionScopeInfo();
3025
3026 return Owned(Res);
3027}