blob: fb828909c3d5d1b818a578e3519947de2235f17b [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Richard Smithad762fc2011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
John McCall1cd76e82011-11-11 03:57:31 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000024#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
John McCall209acbd2010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000028#include "clang/Lex/Preprocessor.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000029#include "clang/Basic/TargetInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCall60d7b3a2010-08-24 06:29:42 +000038StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000039 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000040 if (!E) // FIXME: FullExprArg has no error state?
41 return StmtError();
42
Chris Lattner834a72a2008-07-25 23:18:17 +000043 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
44 // void expression for its side effects. Conversion to void allows any
45 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000046
Chris Lattner834a72a2008-07-25 23:18:17 +000047 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000048 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000049}
50
51
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000052StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000053 bool HasLeadingEmptyMacro) {
54 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Chris Lattner337e5502011-02-18 01:27:55 +000057StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000059 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner20401692009-04-12 20:13:14 +000061 // If we have an invalid decl, just return an error.
62 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner24e1e702009-03-04 04:23:07 +000064 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000065}
66
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000067void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000069
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000070 // If we have an invalid decl, just return.
71 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000072 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
73
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000074 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000075 var->setUsed();
76
John McCall7acddac2011-06-17 06:42:21 +000077 // foreach variables are never actually initialized in the way that
78 // the parser came up with.
79 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000080
John McCall7acddac2011-06-17 06:42:21 +000081 // In ARC, we don't need to retain the iteration variable of a fast
82 // enumeration loop. Rather than actually trying to catch that
83 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000084 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000085 QualType type = var->getType();
86
87 // Only do this if we inferred the lifetime. Inferred lifetime
88 // will show up as a local qualifier because explicit lifetime
89 // should have shown up as an AttributedType instead.
90 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
91 // Add 'const' and mark the variable as pseudo-strong.
92 var->setType(type.withConst());
93 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000094 }
95 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000096}
97
Chandler Carruthec8058f2011-08-17 09:34:37 +000098/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +000099///
100/// Adding a cast to void (or other expression wrappers) will prevent the
101/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000102static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000103 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000104 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000105
106 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
107 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000108 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000109
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000111 IsNotEqual = Op->getOpcode() == BO_NE;
112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000113 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
114 if (Op->getOperator() != OO_EqualEqual &&
115 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000116 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000117
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000121 } else {
122 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000123 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000124 }
125
126 // Suppress warnings when the operator, suspicious as it may be, comes from
127 // a macro expansion.
128 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000129 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000130
Chandler Carruthec8058f2011-08-17 09:34:37 +0000131 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000132 << (unsigned)IsNotEqual << E->getSourceRange();
133
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000134 // If the LHS is a plausible entity to assign to, provide a fixit hint to
135 // correct common typos.
136 if (CanAssign) {
137 if (IsNotEqual)
138 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
139 << FixItHint::CreateReplacement(Loc, "|=");
140 else
141 S.Diag(Loc, diag::note_equality_comparison_to_assign)
142 << FixItHint::CreateReplacement(Loc, "=");
143 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000144
145 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000146}
147
Anders Carlsson636463e2009-07-30 22:17:18 +0000148void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150 return DiagnoseUnusedExprResult(Label->getSubStmt());
151
Anders Carlsson75443112009-07-30 22:39:03 +0000152 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000153 if (!E)
154 return;
155
Eli Friedmana6115062012-05-24 00:47:05 +0000156 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000157 SourceLocation Loc;
158 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000159 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000160 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000161 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner419cfb32009-08-16 16:57:27 +0000163 // Okay, we have an unused result. Depending on what the base expression is,
164 // we might want to make a more specific diagnostic. Check for one of these
165 // cases now.
166 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000167 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000168 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000169 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
170 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000171
Chandler Carruthec8058f2011-08-17 09:34:37 +0000172 if (DiagnoseUnusedComparison(*this, E))
173 return;
174
Eli Friedmana6115062012-05-24 00:47:05 +0000175 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000176 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000177 if (E->getType()->isVoidType())
178 return;
179
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000180 // If the callee has attribute pure, const, or warn_unused_result, warn with
181 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000182 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000183 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000184 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000185 return;
186 }
187 if (FD->getAttr<PureAttr>()) {
188 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
189 return;
190 }
191 if (FD->getAttr<ConstAttr>()) {
192 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
193 return;
194 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000195 }
John McCall12f78a62010-12-02 01:19:52 +0000196 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000197 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000198 Diag(Loc, diag::err_arc_unused_init_message) << R1;
199 return;
200 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000201 const ObjCMethodDecl *MD = ME->getMethodDecl();
202 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000203 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000204 return;
205 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000206 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
207 const Expr *Source = POE->getSyntacticForm();
208 if (isa<ObjCSubscriptRefExpr>(Source))
209 DiagID = diag::warn_unused_container_subscript_expr;
210 else
211 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000212 } else if (const CXXFunctionalCastExpr *FC
213 = dyn_cast<CXXFunctionalCastExpr>(E)) {
214 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
215 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
216 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000217 }
John McCall209acbd2010-04-06 22:24:14 +0000218 // Diagnose "(void*) blah" as a typo for "(void) blah".
219 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
220 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
221 QualType T = TI->getType();
222
223 // We really do want to use the non-canonical type here.
224 if (T == Context.VoidPtrTy) {
225 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
226
227 Diag(Loc, diag::warn_unused_voidptr)
228 << FixItHint::CreateRemoval(TL.getStarLoc());
229 return;
230 }
231 }
232
Eli Friedmana6115062012-05-24 00:47:05 +0000233 if (E->isGLValue() && E->getType().isVolatileQualified()) {
234 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
235 return;
236 }
237
Ted Kremenek351ba912011-02-23 01:52:04 +0000238 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000239}
240
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000241void Sema::ActOnStartOfCompoundStmt() {
242 PushCompoundScope();
243}
244
245void Sema::ActOnFinishOfCompoundStmt() {
246 PopCompoundScope();
247}
248
249sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
250 return getCurFunction()->CompoundScopes.back();
251}
252
John McCall60d7b3a2010-08-24 06:29:42 +0000253StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000254Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000255 MultiStmtArg elts, bool isStmtExpr) {
256 unsigned NumElts = elts.size();
257 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000258 // If we're in C89 mode, check that we don't have any decls after stmts. If
259 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000260 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000261 // Note that __extension__ can be around a decl.
262 unsigned i = 0;
263 // Skip over all declarations.
264 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
265 /*empty*/;
266
267 // We found the end of the list or a statement. Scan for another declstmt.
268 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
269 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000271 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000272 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000273 Diag(D->getLocation(), diag::ext_mixed_decls_code);
274 }
275 }
Chris Lattner98414c12007-08-31 21:49:55 +0000276 // Warn about unused expressions in statements.
277 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000278 // Ignore statements that are last in a statement expression.
279 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000280 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Anders Carlsson636463e2009-07-30 22:17:18 +0000282 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000283 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000284
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000285 // Check for suspicious empty body (null statement) in `for' and `while'
286 // statements. Don't do anything for template instantiations, this just adds
287 // noise.
288 if (NumElts != 0 && !CurrentInstantiationScope &&
289 getCurCompoundScope().HasEmptyLoopBodies) {
290 for (unsigned i = 0; i != NumElts - 1; ++i)
291 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
292 }
293
Ted Kremenek8189cde2009-02-07 01:47:29 +0000294 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000295}
296
John McCall60d7b3a2010-08-24 06:29:42 +0000297StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000298Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
299 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000300 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000301 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000302
John McCall781472f2010-08-25 08:40:02 +0000303 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000304 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000305 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000306 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000307
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000309 // C99 6.8.4.2p3: The expression shall be an integer constant.
310 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000311 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
312 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
313 if (!LHSVal)
314 return StmtError();
315 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000316
317 // GCC extension: The expression shall be an integer constant.
318
Richard Smith282e7e62012-02-04 09:53:13 +0000319 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
320 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
321 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000322 }
323 }
324
Douglas Gregordbb26db2009-05-15 23:57:33 +0000325 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
326 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000327 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000328 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000329}
330
Chris Lattner24e1e702009-03-04 04:23:07 +0000331/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000332void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000333 DiagnoseUnusedExprResult(SubStmt);
334
Chris Lattner24e1e702009-03-04 04:23:07 +0000335 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000336 CS->setSubStmt(SubStmt);
337}
338
John McCall60d7b3a2010-08-24 06:29:42 +0000339StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000340Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000341 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000342 DiagnoseUnusedExprResult(SubStmt);
343
John McCall781472f2010-08-25 08:40:02 +0000344 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000345 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000346 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000347 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000348
Douglas Gregordbb26db2009-05-15 23:57:33 +0000349 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000350 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000351 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
John McCall60d7b3a2010-08-24 06:29:42 +0000354StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000355Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
356 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000357 // If the label was multiply defined, reject it now.
358 if (TheDecl->getStmt()) {
359 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
360 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000361 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 }
Sebastian Redlde307472009-01-11 00:38:46 +0000363
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000364 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000365 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
366 TheDecl->setStmt(LS);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000367 if (!TheDecl->isGnuLocal())
368 TheDecl->setLocation(IdentLoc);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000369 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370}
371
Richard Smith534986f2012-04-14 00:33:13 +0000372StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
373 const AttrVec &Attrs,
374 Stmt *SubStmt) {
375 // Fill in the declaration and return it. Variable length will require to
376 // change this to AttributedStmt::Create(Context, ....);
377 // and probably using ArrayRef
378 AttributedStmt *LS = new (Context) AttributedStmt(AttrLoc, Attrs, SubStmt);
379 return Owned(LS);
380}
381
John McCall60d7b3a2010-08-24 06:29:42 +0000382StmtResult
John McCalld226f652010-08-21 09:40:31 +0000383Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000384 Stmt *thenStmt, SourceLocation ElseLoc,
385 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000386 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000388 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000389 if (CondVar) {
390 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000391 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000392 if (CondResult.isInvalid())
393 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000394 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000395 Expr *ConditionExpr = CondResult.takeAs<Expr>();
396 if (!ConditionExpr)
397 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398
Anders Carlsson75443112009-07-30 22:39:03 +0000399 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000400
John McCall9ae2f072010-08-23 23:25:46 +0000401 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000402 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
403 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000404 }
405
Anders Carlsson75443112009-07-30 22:39:03 +0000406 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000409 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000410}
411
Chris Lattnerf4021e72007-08-23 05:46:52 +0000412/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
413/// the specified width and sign. If an overflow occurs, detect it and emit
414/// the specified diagnostic.
415void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
416 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000417 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000418 unsigned DiagID) {
419 // Perform a conversion to the promoted condition type if needed.
420 if (NewWidth > Val.getBitWidth()) {
421 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000422 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000423 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000424
425 // If the input was signed and negative and the output is
426 // unsigned, don't bother to warn: this is implementation-defined
427 // behavior.
428 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000429 } else if (NewWidth < Val.getBitWidth()) {
430 // If this is a truncation, check for overflow.
431 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000432 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000433 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000434 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000435 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000436 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000437 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattnerf4021e72007-08-23 05:46:52 +0000439 // Regardless of whether a diagnostic was emitted, really do the
440 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000441 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000442 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000443 } else if (NewSign != Val.isSigned()) {
444 // Convert the sign to match the sign of the condition. This can cause
445 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000446 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000447 // behavior.
448 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000449 llvm::APSInt OldVal(Val);
450 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000451 }
452}
453
Chris Lattner0471f5b2007-08-23 18:29:20 +0000454namespace {
455 struct CaseCompareFunctor {
456 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
457 const llvm::APSInt &RHS) {
458 return LHS.first < RHS;
459 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000460 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
461 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
462 return LHS.first < RHS.first;
463 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000464 bool operator()(const llvm::APSInt &LHS,
465 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
466 return LHS < RHS.first;
467 }
468 };
469}
470
Chris Lattner764a7ce2007-09-21 18:15:22 +0000471/// CmpCaseVals - Comparison predicate for sorting case values.
472///
473static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
474 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
475 if (lhs.first < rhs.first)
476 return true;
477
478 if (lhs.first == rhs.first &&
479 lhs.second->getCaseLoc().getRawEncoding()
480 < rhs.second->getCaseLoc().getRawEncoding())
481 return true;
482 return false;
483}
484
Douglas Gregorba915af2010-02-08 22:24:16 +0000485/// CmpEnumVals - Comparison predicate for sorting enumeration values.
486///
487static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
488 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
489{
490 return lhs.first < rhs.first;
491}
492
493/// EqEnumVals - Comparison preficate for uniqing enumeration values.
494///
495static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
496 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
497{
498 return lhs.first == rhs.first;
499}
500
Chris Lattner5f048812009-10-16 16:45:22 +0000501/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
502/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000503static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
504 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
505 expr = cleanups->getSubExpr();
506 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
507 if (impcast->getCastKind() != CK_IntegralCast) break;
508 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000509 }
510 return expr->getType();
511}
512
John McCall60d7b3a2010-08-24 06:29:42 +0000513StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000514Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000515 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000516 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000517
Douglas Gregor586596f2010-05-06 17:25:47 +0000518 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000519 if (CondVar) {
520 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000521 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
522 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000523 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
John McCall9ae2f072010-08-23 23:25:46 +0000525 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000526 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000527
John McCall9ae2f072010-08-23 23:25:46 +0000528 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000529 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000530
Douglas Gregorab41fe92012-05-04 22:38:52 +0000531 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
532 Expr *Cond;
533
534 public:
535 SwitchConvertDiagnoser(Expr *Cond)
536 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
537
538 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
539 QualType T) {
540 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
541 }
542
543 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
544 QualType T) {
545 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
546 << T << Cond->getSourceRange();
547 }
548
549 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
550 QualType T,
551 QualType ConvTy) {
552 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
553 }
554
555 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
556 QualType ConvTy) {
557 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
558 << ConvTy->isEnumeralType() << ConvTy;
559 }
560
561 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
562 QualType T) {
563 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
564 }
565
566 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
567 QualType ConvTy) {
568 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
569 << ConvTy->isEnumeralType() << ConvTy;
570 }
571
572 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
573 QualType T,
574 QualType ConvTy) {
575 return DiagnosticBuilder::getEmpty();
576 }
577 } SwitchDiagnoser(Cond);
578
John McCall9ae2f072010-08-23 23:25:46 +0000579 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000580 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000581 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000582 if (CondResult.isInvalid()) return StmtError();
583 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
John McCalla8e0cd82011-08-06 07:30:58 +0000585 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
586 CondResult = UsualUnaryConversions(Cond);
587 if (CondResult.isInvalid()) return StmtError();
588 Cond = CondResult.take();
589
John McCalld226f652010-08-21 09:40:31 +0000590 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000591 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000592 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000593 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000594 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000595 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000596 }
John McCallb60a77e2010-08-01 00:26:45 +0000597
John McCall781472f2010-08-25 08:40:02 +0000598 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
John McCall9ae2f072010-08-23 23:25:46 +0000600 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000601 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000602 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000603}
604
Gabor Greif28164ab2010-10-01 22:05:14 +0000605static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
606 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000607 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000608 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000609 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000610 Val.setIsSigned(IsSigned);
611}
612
John McCall60d7b3a2010-08-24 06:29:42 +0000613StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000614Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
615 Stmt *BodyStmt) {
616 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000617 assert(SS == getCurFunction()->SwitchStack.back() &&
618 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000619
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000620 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000621 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000622
Chris Lattnerf4021e72007-08-23 05:46:52 +0000623 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000624 if (!CondExpr) return StmtError();
625
626 QualType CondType = CondExpr->getType();
627
John McCall0fb97082010-05-18 03:19:21 +0000628 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000629 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000630 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000631
Chris Lattner5f048812009-10-16 16:45:22 +0000632 // C++ 6.4.2.p2:
633 // Integral promotions are performed (on the switch condition).
634 //
635 // A case value unrepresentable by the original switch condition
636 // type (before the promotion) doesn't make sense, even when it can
637 // be represented by the promoted type. Therefore we need to find
638 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000639 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000640 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000642 // appropriate type now, just return an error.
643 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000644 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000645
Chris Lattner2b334bb2010-04-16 23:34:13 +0000646 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000647 // switch(bool_expr) {...} is often a programmer error, e.g.
648 // switch(n && mask) { ... } // Doh - should be "n & mask".
649 // One can always use an if statement instead of switch(bool_expr).
650 Diag(SwitchLoc, diag::warn_bool_switch_condition)
651 << CondExpr->getSourceRange();
652 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000653 }
Sebastian Redlde307472009-01-11 00:38:46 +0000654
Chris Lattnerf4021e72007-08-23 05:46:52 +0000655 // Get the bitwidth of the switched-on value before promotions. We must
656 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000657 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000658 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000659 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000660 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000661 bool CondIsSigned
662 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Chris Lattnerf4021e72007-08-23 05:46:52 +0000664 // Accumulate all of the case values in a vector so that we can sort them
665 // and detect duplicates. This vector contains the APInt for the case after
666 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000667 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000668 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000669
Chris Lattnerf4021e72007-08-23 05:46:52 +0000670 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000671 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
672 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattnerf4021e72007-08-23 05:46:52 +0000674 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000676 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Douglas Gregordbb26db2009-05-15 23:57:33 +0000678 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000679 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000681 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000682 if (TheDefaultStmt) {
683 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000684 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000685
Chris Lattnerf4021e72007-08-23 05:46:52 +0000686 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000687 // we'll return a valid AST. This requires recursing down the AST and
688 // finding it, not something we are set up to do right now. For now,
689 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000690 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000691 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000692 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattnerf4021e72007-08-23 05:46:52 +0000694 } else {
695 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner1e0a3902008-01-16 19:17:22 +0000697 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000698
699 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
700 HasDependentValue = true;
701 break;
702 }
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Richard Smith8ef7b202012-01-18 23:55:52 +0000704 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000705
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000707 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
708 // constant expression of the promoted type of the switch condition.
709 ExprResult ConvLo =
710 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
711 if (ConvLo.isInvalid()) {
712 CaseListIsErroneous = true;
713 continue;
714 }
715 Lo = ConvLo.take();
716 } else {
717 // We already verified that the expression has a i-c-e value (C99
718 // 6.8.4.2p3) - get that value now.
719 LoVal = Lo->EvaluateKnownConstInt(Context);
720
721 // If the LHS is not the same type as the condition, insert an implicit
722 // cast.
723 Lo = DefaultLvalueConversion(Lo).take();
724 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
725 }
726
727 // Convert the value to the same width/sign as the condition had prior to
728 // integral promotions.
729 //
730 // FIXME: This causes us to reject valid code:
731 // switch ((char)c) { case 256: case 0: return 0; }
732 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000733 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000734 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000735 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000736
Chris Lattner1e0a3902008-01-16 19:17:22 +0000737 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000739 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000740 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000741 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000742 CS->getRHS()->isValueDependent()) {
743 HasDependentValue = true;
744 break;
745 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000746 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000747 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000748 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000749 }
750 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000751
752 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000753 // If we don't have a default statement, check whether the
754 // condition is constant.
755 llvm::APSInt ConstantCondValue;
756 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000757 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000758 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000759 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
760 Expr::SE_AllowSideEffects);
761 assert(!HasConstantCond ||
762 (ConstantCondValue.getBitWidth() == CondWidth &&
763 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000764 }
Richard Smith80d4b552011-12-28 19:48:30 +0000765 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000766
Douglas Gregordbb26db2009-05-15 23:57:33 +0000767 // Sort all the scalar case values so we can easily detect duplicates.
768 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
769
770 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000771 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
772 if (ShouldCheckConstantCond &&
773 CaseVals[i].first == ConstantCondValue)
774 ShouldCheckConstantCond = false;
775
776 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000777 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000778 // First, determine if either case value has a name
779 StringRef PrevString, CurrString;
780 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
781 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
782 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
783 PrevString = DeclRef->getDecl()->getName();
784 }
785 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
786 CurrString = DeclRef->getDecl()->getName();
787 }
Douglas Gregor50de5e32012-05-16 16:11:17 +0000788 llvm::SmallString<16> CaseValStr;
789 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000790
791 if (PrevString == CurrString)
792 Diag(CaseVals[i].second->getLHS()->getLocStart(),
793 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000794 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000795 else
796 Diag(CaseVals[i].second->getLHS()->getLocStart(),
797 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000798 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
799 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000800 CaseValStr;
801
John McCall0fb97082010-05-18 03:19:21 +0000802 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000803 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000804 // FIXME: We really want to remove the bogus case stmt from the
805 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000806 CaseListIsErroneous = true;
807 }
808 }
809 }
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Douglas Gregordbb26db2009-05-15 23:57:33 +0000811 // Detect duplicate case ranges, which usually don't exist at all in
812 // the first place.
813 if (!CaseRanges.empty()) {
814 // Sort all the case ranges by their low value so we can easily detect
815 // overlaps between ranges.
816 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregordbb26db2009-05-15 23:57:33 +0000818 // Scan the ranges, computing the high values and removing empty ranges.
819 std::vector<llvm::APSInt> HiVals;
820 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000821 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000822 CaseStmt *CR = CaseRanges[i].second;
823 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000824 llvm::APSInt HiVal;
825
David Blaikie4e4d0842012-03-11 07:00:24 +0000826 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000827 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
828 // constant expression of the promoted type of the switch condition.
829 ExprResult ConvHi =
830 CheckConvertedConstantExpression(Hi, CondType, HiVal,
831 CCEK_CaseValue);
832 if (ConvHi.isInvalid()) {
833 CaseListIsErroneous = true;
834 continue;
835 }
836 Hi = ConvHi.take();
837 } else {
838 HiVal = Hi->EvaluateKnownConstInt(Context);
839
840 // If the RHS is not the same type as the condition, insert an
841 // implicit cast.
842 Hi = DefaultLvalueConversion(Hi).take();
843 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Douglas Gregordbb26db2009-05-15 23:57:33 +0000846 // Convert the value to the same width/sign as the condition.
847 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000848 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000849 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregordbb26db2009-05-15 23:57:33 +0000851 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregordbb26db2009-05-15 23:57:33 +0000853 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000854 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000855 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
856 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000857 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000858 CaseRanges.erase(CaseRanges.begin()+i);
859 --i, --e;
860 continue;
861 }
John McCall0fb97082010-05-18 03:19:21 +0000862
863 if (ShouldCheckConstantCond &&
864 LoVal <= ConstantCondValue &&
865 ConstantCondValue <= HiVal)
866 ShouldCheckConstantCond = false;
867
Douglas Gregordbb26db2009-05-15 23:57:33 +0000868 HiVals.push_back(HiVal);
869 }
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregordbb26db2009-05-15 23:57:33 +0000871 // Rescan the ranges, looking for overlap with singleton values and other
872 // ranges. Since the range list is sorted, we only need to compare case
873 // ranges with their neighbors.
874 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
875 llvm::APSInt &CRLo = CaseRanges[i].first;
876 llvm::APSInt &CRHi = HiVals[i];
877 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Douglas Gregordbb26db2009-05-15 23:57:33 +0000879 // Check to see whether the case range overlaps with any
880 // singleton cases.
881 CaseStmt *OverlapStmt = 0;
882 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Douglas Gregordbb26db2009-05-15 23:57:33 +0000884 // Find the smallest value >= the lower bound. If I is in the
885 // case range, then we have overlap.
886 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
887 CaseVals.end(), CRLo,
888 CaseCompareFunctor());
889 if (I != CaseVals.end() && I->first < CRHi) {
890 OverlapVal = I->first; // Found overlap with scalar.
891 OverlapStmt = I->second;
892 }
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Douglas Gregordbb26db2009-05-15 23:57:33 +0000894 // Find the smallest value bigger than the upper bound.
895 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
896 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
897 OverlapVal = (I-1)->first; // Found overlap with scalar.
898 OverlapStmt = (I-1)->second;
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregordbb26db2009-05-15 23:57:33 +0000901 // Check to see if this case stmt overlaps with the subsequent
902 // case range.
903 if (i && CRLo <= HiVals[i-1]) {
904 OverlapVal = HiVals[i-1]; // Found overlap with range.
905 OverlapStmt = CaseRanges[i-1].second;
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Douglas Gregordbb26db2009-05-15 23:57:33 +0000908 if (OverlapStmt) {
909 // If we have a duplicate, report it.
910 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
911 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000912 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000913 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000914 // FIXME: We really want to remove the bogus case stmt from the
915 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000916 CaseListIsErroneous = true;
917 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000918 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000919 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000920
John McCall0fb97082010-05-18 03:19:21 +0000921 // Complain if we have a constant condition and we didn't find a match.
922 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
923 // TODO: it would be nice if we printed enums as enums, chars as
924 // chars, etc.
925 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
926 << ConstantCondValue.toString(10)
927 << CondExpr->getSourceRange();
928 }
929
930 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000931 // values. We only issue a warning if there is not 'default:', but
932 // we still do the analysis to preserve this information in the AST
933 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000934 //
Chris Lattnerce784612010-09-16 17:09:42 +0000935 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000936
Douglas Gregorba915af2010-02-08 22:24:16 +0000937 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000938 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000939 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000940 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000941 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000942 EnumValsTy EnumVals;
943
John McCall0fb97082010-05-18 03:19:21 +0000944 // Gather all enum values, set their type and sort them,
945 // allowing easier comparison with CaseVals.
946 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000947 EDI != ED->enumerator_end(); ++EDI) {
948 llvm::APSInt Val = EDI->getInitVal();
949 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000950 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000951 }
952 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000953 EnumValsTy::iterator EIend =
954 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000955
956 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000957 EnumValsTy::const_iterator EI = EnumVals.begin();
958 for (CaseValsTy::const_iterator CI = CaseVals.begin();
959 CI != CaseVals.end(); CI++) {
960 while (EI != EIend && EI->first < CI->first)
961 EI++;
962 if (EI == EIend || EI->first > CI->first)
963 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000964 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000965 }
966 // See which of case ranges aren't in enum
967 EI = EnumVals.begin();
968 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
969 RI != CaseRanges.end() && EI != EIend; RI++) {
970 while (EI != EIend && EI->first < RI->first)
971 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972
David Blaikie93667502012-01-22 02:31:55 +0000973 if (EI == EIend || EI->first != RI->first) {
974 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000975 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000976 }
David Blaikie93667502012-01-22 02:31:55 +0000977
978 llvm::APSInt Hi =
979 RI->second->getRHS()->EvaluateKnownConstInt(Context);
980 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
981 while (EI != EIend && EI->first < Hi)
982 EI++;
983 if (EI == EIend || EI->first != Hi)
984 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000985 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +0000986 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000987
Ted Kremenek559fb552010-09-09 00:05:53 +0000988 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000989 CaseValsTy::const_iterator CI = CaseVals.begin();
990 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +0000991 bool hasCasesNotInSwitch = false;
992
Chris Lattner5f9e2722011-07-23 10:55:15 +0000993 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000994
David Blaikie93667502012-01-22 02:31:55 +0000995 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +0000996 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +0000997 llvm::APSInt CIVal;
998 while (CI != CaseVals.end() && CI->first < EI->first)
999 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001000
Douglas Gregorba915af2010-02-08 22:24:16 +00001001 if (CI != CaseVals.end() && CI->first == EI->first)
1002 continue;
1003
Ted Kremenek559fb552010-09-09 00:05:53 +00001004 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001005 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001006 llvm::APSInt Hi =
1007 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001008 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001009 if (EI->first <= Hi)
1010 break;
1011 }
1012
Ted Kremenek559fb552010-09-09 00:05:53 +00001013 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001014 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001015 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001016 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001017 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001018
David Blaikie585d7792012-01-23 04:46:12 +00001019 if (TheDefaultStmt && UnhandledNames.empty())
1020 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001021
Chris Lattnerce784612010-09-16 17:09:42 +00001022 // Produce a nice diagnostic if multiple values aren't handled.
1023 switch (UnhandledNames.size()) {
1024 case 0: break;
1025 case 1:
David Blaikie585d7792012-01-23 04:46:12 +00001026 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1027 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001028 << UnhandledNames[0];
1029 break;
1030 case 2:
David Blaikie585d7792012-01-23 04:46:12 +00001031 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1032 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001033 << UnhandledNames[0] << UnhandledNames[1];
1034 break;
1035 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001036 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1037 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001038 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1039 break;
1040 default:
David Blaikie585d7792012-01-23 04:46:12 +00001041 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1042 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001043 << (unsigned)UnhandledNames.size()
1044 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1045 break;
1046 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001047
1048 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001049 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001050 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001051 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001052
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001053 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1054 diag::warn_empty_switch_body);
1055
Mike Stump390b4cc2009-05-16 07:39:55 +00001056 // FIXME: If the case list was broken is some way, we don't have a good system
1057 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001058 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001059 return StmtError();
1060
Sebastian Redlde307472009-01-11 00:38:46 +00001061 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001062}
1063
John McCall60d7b3a2010-08-24 06:29:42 +00001064StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001065Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001066 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001067 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
Douglas Gregor5656e142009-11-24 21:15:44 +00001069 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001070 if (CondVar) {
1071 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001072 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001073 if (CondResult.isInvalid())
1074 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001075 }
John McCall9ae2f072010-08-23 23:25:46 +00001076 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001077 if (!ConditionExpr)
1078 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001079
John McCall9ae2f072010-08-23 23:25:46 +00001080 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001082 if (isa<NullStmt>(Body))
1083 getCurCompoundScope().setHasEmptyLoopBodies();
1084
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001085 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001086 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001087}
1088
John McCall60d7b3a2010-08-24 06:29:42 +00001089StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001090Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001091 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001092 Expr *Cond, SourceLocation CondRParen) {
1093 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001094
John Wiegley429bb272011-04-08 18:41:53 +00001095 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1096 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001097 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001098 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001099
John McCallb4eb64d2010-10-08 02:01:28 +00001100 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +00001101 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +00001102 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001103 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001104 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105
John McCall9ae2f072010-08-23 23:25:46 +00001106 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001107
John McCall9ae2f072010-08-23 23:25:46 +00001108 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001109}
1110
Richard Trieu694e7962012-04-30 18:01:30 +00001111namespace {
1112 // This visitor will traverse a conditional statement and store all
1113 // the evaluated decls into a vector. Simple is set to true if none
1114 // of the excluded constructs are used.
1115 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1116 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1117 llvm::SmallVector<SourceRange, 10> &Ranges;
1118 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001119public:
1120 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1121
1122 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerfacde172012-06-06 17:32:50 +00001123 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001124 Inherited(S.Context),
1125 Decls(Decls),
1126 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001127 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001128
1129 bool isSimple() { return Simple; }
1130
1131 // Replaces the method in EvaluatedExprVisitor.
1132 void VisitMemberExpr(MemberExpr* E) {
1133 Simple = false;
1134 }
1135
1136 // Any Stmt not whitelisted will cause the condition to be marked complex.
1137 void VisitStmt(Stmt *S) {
1138 Simple = false;
1139 }
1140
1141 void VisitBinaryOperator(BinaryOperator *E) {
1142 Visit(E->getLHS());
1143 Visit(E->getRHS());
1144 }
1145
1146 void VisitCastExpr(CastExpr *E) {
1147 Visit(E->getSubExpr());
1148 }
1149
1150 void VisitUnaryOperator(UnaryOperator *E) {
1151 // Skip checking conditionals with derefernces.
1152 if (E->getOpcode() == UO_Deref)
1153 Simple = false;
1154 else
1155 Visit(E->getSubExpr());
1156 }
1157
1158 void VisitConditionalOperator(ConditionalOperator *E) {
1159 Visit(E->getCond());
1160 Visit(E->getTrueExpr());
1161 Visit(E->getFalseExpr());
1162 }
1163
1164 void VisitParenExpr(ParenExpr *E) {
1165 Visit(E->getSubExpr());
1166 }
1167
1168 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1169 Visit(E->getOpaqueValue()->getSourceExpr());
1170 Visit(E->getFalseExpr());
1171 }
1172
1173 void VisitIntegerLiteral(IntegerLiteral *E) { }
1174 void VisitFloatingLiteral(FloatingLiteral *E) { }
1175 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1176 void VisitCharacterLiteral(CharacterLiteral *E) { }
1177 void VisitGNUNullExpr(GNUNullExpr *E) { }
1178 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1179
1180 void VisitDeclRefExpr(DeclRefExpr *E) {
1181 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1182 if (!VD) return;
1183
1184 Ranges.push_back(E->getSourceRange());
1185
1186 Decls.insert(VD);
1187 }
1188
1189 }; // end class DeclExtractor
1190
1191 // DeclMatcher checks to see if the decls are used in a non-evauluated
1192 // context.
1193 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1194 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1195 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001196
1197public:
1198 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1199
1200 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1201 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1202 if (!Statement) return;
1203
1204 Visit(Statement);
1205 }
1206
1207 void VisitReturnStmt(ReturnStmt *S) {
1208 FoundDecl = true;
1209 }
1210
1211 void VisitBreakStmt(BreakStmt *S) {
1212 FoundDecl = true;
1213 }
1214
1215 void VisitGotoStmt(GotoStmt *S) {
1216 FoundDecl = true;
1217 }
1218
1219 void VisitCastExpr(CastExpr *E) {
1220 if (E->getCastKind() == CK_LValueToRValue)
1221 CheckLValueToRValueCast(E->getSubExpr());
1222 else
1223 Visit(E->getSubExpr());
1224 }
1225
1226 void CheckLValueToRValueCast(Expr *E) {
1227 E = E->IgnoreParenImpCasts();
1228
1229 if (isa<DeclRefExpr>(E)) {
1230 return;
1231 }
1232
1233 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1234 Visit(CO->getCond());
1235 CheckLValueToRValueCast(CO->getTrueExpr());
1236 CheckLValueToRValueCast(CO->getFalseExpr());
1237 return;
1238 }
1239
1240 if (BinaryConditionalOperator *BCO =
1241 dyn_cast<BinaryConditionalOperator>(E)) {
1242 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1243 CheckLValueToRValueCast(BCO->getFalseExpr());
1244 return;
1245 }
1246
1247 Visit(E);
1248 }
1249
1250 void VisitDeclRefExpr(DeclRefExpr *E) {
1251 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1252 if (Decls.count(VD))
1253 FoundDecl = true;
1254 }
1255
1256 bool FoundDeclInUse() { return FoundDecl; }
1257
1258 }; // end class DeclMatcher
1259
1260 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1261 Expr *Third, Stmt *Body) {
1262 // Condition is empty
1263 if (!Second) return;
1264
1265 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1266 Second->getLocStart())
1267 == DiagnosticsEngine::Ignored)
1268 return;
1269
1270 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1271 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1272 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001273 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001274 DE.Visit(Second);
1275
1276 // Don't analyze complex conditionals.
1277 if (!DE.isSimple()) return;
1278
1279 // No decls found.
1280 if (Decls.size() == 0) return;
1281
Richard Trieu90875992012-05-04 03:01:54 +00001282 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001283 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1284 E = Decls.end();
1285 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001286 if ((*I)->getType().isVolatileQualified() ||
1287 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001288
1289 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1290 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1291 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1292 return;
1293
1294 // Load decl names into diagnostic.
1295 if (Decls.size() > 4)
1296 PDiag << 0;
1297 else {
1298 PDiag << Decls.size();
1299 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1300 E = Decls.end();
1301 I != E; ++I)
1302 PDiag << (*I)->getDeclName();
1303 }
1304
1305 // Load SourceRanges into diagnostic if there is room.
1306 // Otherwise, load the SourceRange of the conditional expression.
1307 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1308 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1309 E = Ranges.end();
1310 I != E; ++I)
1311 PDiag << *I;
1312 else
1313 PDiag << Second->getSourceRange();
1314
1315 S.Diag(Ranges.begin()->getBegin(), PDiag);
1316 }
1317
1318} // end namespace
1319
John McCall60d7b3a2010-08-24 06:29:42 +00001320StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001321Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001322 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001323 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001324 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001325 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001326 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001327 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1328 // declare identifiers for objects having storage class 'auto' or
1329 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001330 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1331 DI!=DE; ++DI) {
1332 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001333 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001334 VD = 0;
1335 if (VD == 0)
1336 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1337 // FIXME: mark decl erroneous!
1338 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001339 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001341
Richard Trieu694e7962012-04-30 18:01:30 +00001342 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1343
John McCall60d7b3a2010-08-24 06:29:42 +00001344 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001345 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001346 if (secondVar) {
1347 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001348 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001349 if (SecondResult.isInvalid())
1350 return StmtError();
1351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001352
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001353 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001354
Anders Carlsson3af708f2009-08-01 01:39:59 +00001355 DiagnoseUnusedExprResult(First);
1356 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001357 DiagnoseUnusedExprResult(Body);
1358
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001359 if (isa<NullStmt>(Body))
1360 getCurCompoundScope().setHasEmptyLoopBodies();
1361
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001362 return Owned(new (Context) ForStmt(Context, First,
1363 SecondResult.take(), ConditionVar,
1364 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001365 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001366}
1367
John McCallf6a16482010-12-04 03:47:34 +00001368/// In an Objective C collection iteration statement:
1369/// for (x in y)
1370/// x can be an arbitrary l-value expression. Bind it up as a
1371/// full-expression.
1372StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001373 // Reduce placeholder expressions here. Note that this rejects the
1374 // use of pseudo-object l-values in this position.
1375 ExprResult result = CheckPlaceholderExpr(E);
1376 if (result.isInvalid()) return StmtError();
1377 E = result.take();
1378
John McCallf6a16482010-12-04 03:47:34 +00001379 CheckImplicitConversions(E);
John McCall29bbd1a2012-03-30 05:43:39 +00001380
1381 result = MaybeCreateExprWithCleanups(E);
1382 if (result.isInvalid()) return StmtError();
1383
1384 return Owned(static_cast<Stmt*>(result.take()));
John McCallf6a16482010-12-04 03:47:34 +00001385}
1386
John McCall990567c2011-07-27 01:07:15 +00001387ExprResult
1388Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1389 assert(collection);
1390
1391 // Bail out early if we've got a type-dependent expression.
1392 if (collection->isTypeDependent()) return Owned(collection);
1393
1394 // Perform normal l-value conversion.
1395 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1396 if (result.isInvalid())
1397 return ExprError();
1398 collection = result.take();
1399
1400 // The operand needs to have object-pointer type.
1401 // TODO: should we do a contextual conversion?
1402 const ObjCObjectPointerType *pointerType =
1403 collection->getType()->getAs<ObjCObjectPointerType>();
1404 if (!pointerType)
1405 return Diag(forLoc, diag::err_collection_expr_type)
1406 << collection->getType() << collection->getSourceRange();
1407
1408 // Check that the operand provides
1409 // - countByEnumeratingWithState:objects:count:
1410 const ObjCObjectType *objectType = pointerType->getObjectType();
1411 ObjCInterfaceDecl *iface = objectType->getInterface();
1412
1413 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001414 // Under ARC, it is an error not to have a forward-declared class.
1415 if (iface &&
1416 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001417 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001418 ? diag::err_arc_collection_forward
1419 : 0,
1420 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001421 // Otherwise, if we have any useful type information, check that
1422 // the type declares the appropriate method.
1423 } else if (iface || !objectType->qual_empty()) {
1424 IdentifierInfo *selectorIdents[] = {
1425 &Context.Idents.get("countByEnumeratingWithState"),
1426 &Context.Idents.get("objects"),
1427 &Context.Idents.get("count")
1428 };
1429 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1430
1431 ObjCMethodDecl *method = 0;
1432
1433 // If there's an interface, look in both the public and private APIs.
1434 if (iface) {
1435 method = iface->lookupInstanceMethod(selector);
1436 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1437 }
1438
1439 // Also check protocol qualifiers.
1440 if (!method)
1441 method = LookupMethodInQualifiedType(selector, pointerType,
1442 /*instance*/ true);
1443
1444 // If we didn't find it anywhere, give up.
1445 if (!method) {
1446 Diag(forLoc, diag::warn_collection_expr_type)
1447 << collection->getType() << selector << collection->getSourceRange();
1448 }
1449
1450 // TODO: check for an incompatible signature?
1451 }
1452
1453 // Wrap up any cleanups in the expression.
1454 return Owned(MaybeCreateExprWithCleanups(collection));
1455}
1456
John McCall60d7b3a2010-08-24 06:29:42 +00001457StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001458Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1459 SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001460 Stmt *First, Expr *Second,
1461 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001462 if (First) {
1463 QualType FirstType;
1464 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001465 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001466 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1467 diag::err_toomany_element_decls));
1468
John McCallf85e1932011-06-15 23:02:42 +00001469 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1470 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001471 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1472 // declare identifiers for objects having storage class 'auto' or
1473 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001474 if (!D->hasLocalStorage())
1475 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001476 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001477 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001478 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001479 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001480 return StmtError(Diag(First->getLocStart(),
1481 diag::err_selector_element_not_lvalue)
1482 << First->getSourceRange());
1483
Mike Stump1eb44332009-09-09 15:08:12 +00001484 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001485 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001486 if (!FirstType->isDependentType() &&
1487 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001488 !FirstType->isBlockPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001489 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00001490 << FirstType << First->getSourceRange();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001491 }
John McCall990567c2011-07-27 01:07:15 +00001492
Ted Kremenek8189cde2009-02-07 01:47:29 +00001493 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1494 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001495}
Reid Spencer5f016e22007-07-11 17:01:13 +00001496
Richard Smithad762fc2011-04-14 22:09:26 +00001497namespace {
1498
1499enum BeginEndFunction {
1500 BEF_begin,
1501 BEF_end
1502};
1503
1504/// Build a variable declaration for a for-range statement.
1505static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1506 QualType Type, const char *Name) {
1507 DeclContext *DC = SemaRef.CurContext;
1508 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1509 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1510 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1511 TInfo, SC_Auto, SC_None);
Richard Smithb403d6d2011-04-18 15:49:25 +00001512 Decl->setImplicit();
Richard Smithad762fc2011-04-14 22:09:26 +00001513 return Decl;
1514}
1515
1516/// Finish building a variable declaration for a for-range statement.
1517/// \return true if an error occurs.
1518static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1519 SourceLocation Loc, int diag) {
1520 // Deduce the type for the iterator variable now rather than leaving it to
1521 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1522 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001523 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001524 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1525 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001526 SemaRef.Diag(Loc, diag) << Init->getType();
1527 if (!InitTSI) {
1528 Decl->setInvalidDecl();
1529 return true;
1530 }
1531 Decl->setTypeSourceInfo(InitTSI);
1532 Decl->setType(InitTSI->getType());
1533
John McCallf85e1932011-06-15 23:02:42 +00001534 // In ARC, infer lifetime.
1535 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1536 // we're doing the equivalent of fast iteration.
David Blaikie4e4d0842012-03-11 07:00:24 +00001537 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001538 SemaRef.inferObjCARCLifetime(Decl))
1539 Decl->setInvalidDecl();
1540
Richard Smithad762fc2011-04-14 22:09:26 +00001541 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1542 /*TypeMayContainAuto=*/false);
1543 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001544 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001545 return false;
1546}
1547
1548/// Produce a note indicating which begin/end function was implicitly called
1549/// by a C++0x for-range statement. This is often not obvious from the code,
1550/// nor from the diagnostics produced when analysing the implicit expressions
1551/// required in a for-range statement.
1552void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1553 BeginEndFunction BEF) {
1554 CallExpr *CE = dyn_cast<CallExpr>(E);
1555 if (!CE)
1556 return;
1557 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1558 if (!D)
1559 return;
1560 SourceLocation Loc = D->getLocation();
1561
1562 std::string Description;
1563 bool IsTemplate = false;
1564 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1565 Description = SemaRef.getTemplateArgumentBindingsText(
1566 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1567 IsTemplate = true;
1568 }
1569
1570 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1571 << BEF << IsTemplate << Description << E->getType();
1572}
1573
1574/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1575/// given LookupResult is non-empty, it is assumed to describe a member which
1576/// will be invoked. Otherwise, the function will be found via argument
1577/// dependent lookup.
1578static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1579 SourceLocation Loc,
1580 VarDecl *Decl,
1581 BeginEndFunction BEF,
1582 const DeclarationNameInfo &NameInfo,
1583 LookupResult &MemberLookup,
1584 Expr *Range) {
1585 ExprResult CallExpr;
1586 if (!MemberLookup.empty()) {
1587 ExprResult MemberRef =
1588 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1589 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001590 /*TemplateKWLoc=*/SourceLocation(),
1591 /*FirstQualifierInScope=*/0,
1592 MemberLookup,
Richard Smithad762fc2011-04-14 22:09:26 +00001593 /*TemplateArgs=*/0);
1594 if (MemberRef.isInvalid())
1595 return ExprError();
1596 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1597 Loc, 0);
1598 if (CallExpr.isInvalid())
1599 return ExprError();
1600 } else {
1601 UnresolvedSet<0> FoundNames;
1602 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1603 // std is an associated namespace.
1604 UnresolvedLookupExpr *Fn =
1605 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1606 NestedNameSpecifierLoc(), NameInfo,
1607 /*NeedsADL=*/true, /*Overloaded=*/false,
1608 FoundNames.begin(), FoundNames.end(),
1609 /*LookInStdNamespace=*/true);
1610 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00001611 0, /*AllowTypoCorrection=*/false);
Richard Smithad762fc2011-04-14 22:09:26 +00001612 if (CallExpr.isInvalid()) {
1613 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1614 << Range->getType();
1615 return ExprError();
1616 }
1617 }
1618 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1619 diag::err_for_range_iter_deduction_failure)) {
1620 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1621 return ExprError();
1622 }
1623 return CallExpr;
1624}
1625
1626}
1627
1628/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1629///
1630/// C++0x [stmt.ranged]:
1631/// A range-based for statement is equivalent to
1632///
1633/// {
1634/// auto && __range = range-init;
1635/// for ( auto __begin = begin-expr,
1636/// __end = end-expr;
1637/// __begin != __end;
1638/// ++__begin ) {
1639/// for-range-declaration = *__begin;
1640/// statement
1641/// }
1642/// }
1643///
1644/// The body of the loop is not available yet, since it cannot be analysed until
1645/// we have determined the type of the for-range-declaration.
1646StmtResult
1647Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1648 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1649 SourceLocation RParenLoc) {
1650 if (!First || !Range)
1651 return StmtError();
1652
1653 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1654 assert(DS && "first part of for range not a decl stmt");
1655
1656 if (!DS->isSingleDecl()) {
1657 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1658 return StmtError();
1659 }
1660 if (DS->getSingleDecl()->isInvalidDecl())
1661 return StmtError();
1662
1663 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1664 return StmtError();
1665
1666 // Build auto && __range = range-init
1667 SourceLocation RangeLoc = Range->getLocStart();
1668 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1669 Context.getAutoRRefDeductType(),
1670 "__range");
1671 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1672 diag::err_for_range_deduction_failure))
1673 return StmtError();
1674
1675 // Claim the type doesn't contain auto: we've already done the checking.
1676 DeclGroupPtrTy RangeGroup =
1677 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1678 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1679 if (RangeDecl.isInvalid())
1680 return StmtError();
1681
1682 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1683 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1684 RParenLoc);
1685}
1686
1687/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1688StmtResult
1689Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1690 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1691 Expr *Inc, Stmt *LoopVarDecl,
1692 SourceLocation RParenLoc) {
1693 Scope *S = getCurScope();
1694
1695 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1696 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1697 QualType RangeVarType = RangeVar->getType();
1698
1699 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1700 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1701
1702 StmtResult BeginEndDecl = BeginEnd;
1703 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1704
1705 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1706 SourceLocation RangeLoc = RangeVar->getLocation();
1707
Ted Kremeneke50b0152011-10-10 22:36:28 +00001708 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1709
1710 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1711 VK_LValue, ColonLoc);
1712 if (BeginRangeRef.isInvalid())
1713 return StmtError();
1714
1715 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1716 VK_LValue, ColonLoc);
1717 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001718 return StmtError();
1719
1720 QualType AutoType = Context.getAutoDeductType();
1721 Expr *Range = RangeVar->getInit();
1722 if (!Range)
1723 return StmtError();
1724 QualType RangeType = Range->getType();
1725
1726 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001727 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001728 return StmtError();
1729
1730 // Build auto __begin = begin-expr, __end = end-expr.
1731 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1732 "__begin");
1733 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1734 "__end");
1735
1736 // Build begin-expr and end-expr and attach to __begin and __end variables.
1737 ExprResult BeginExpr, EndExpr;
1738 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1739 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1740 // __range + __bound, respectively, where __bound is the array bound. If
1741 // _RangeT is an array of unknown size or an array of incomplete type,
1742 // the program is ill-formed;
1743
1744 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001745 BeginExpr = BeginRangeRef;
1746 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001747 diag::err_for_range_iter_deduction_failure)) {
1748 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1749 return StmtError();
1750 }
1751
1752 // Find the array bound.
1753 ExprResult BoundExpr;
1754 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1755 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001756 Context.getPointerDiffType(),
1757 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001758 else if (const VariableArrayType *VAT =
1759 dyn_cast<VariableArrayType>(UnqAT))
1760 BoundExpr = VAT->getSizeExpr();
1761 else {
1762 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1763 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001764 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001765 }
1766
1767 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001768 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001769 BoundExpr.get());
1770 if (EndExpr.isInvalid())
1771 return StmtError();
1772 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1773 diag::err_for_range_iter_deduction_failure)) {
1774 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1775 return StmtError();
1776 }
1777 } else {
1778 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1779 ColonLoc);
1780 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1781 ColonLoc);
1782
1783 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1784 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1785
1786 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1787 // - if _RangeT is a class type, the unqualified-ids begin and end are
1788 // looked up in the scope of class _RangeT as if by class member access
1789 // lookup (3.4.5), and if either (or both) finds at least one
1790 // declaration, begin-expr and end-expr are __range.begin() and
1791 // __range.end(), respectively;
1792 LookupQualifiedName(BeginMemberLookup, D);
1793 LookupQualifiedName(EndMemberLookup, D);
1794
1795 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1796 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1797 << RangeType << BeginMemberLookup.empty();
1798 return StmtError();
1799 }
1800 } else {
1801 // - otherwise, begin-expr and end-expr are begin(__range) and
1802 // end(__range), respectively, where begin and end are looked up with
1803 // argument-dependent lookup (3.4.2). For the purposes of this name
1804 // lookup, namespace std is an associated namespace.
1805 }
1806
1807 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1808 BEF_begin, BeginNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001809 BeginMemberLookup,
1810 BeginRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001811 if (BeginExpr.isInvalid())
1812 return StmtError();
1813
1814 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1815 BEF_end, EndNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001816 EndMemberLookup, EndRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001817 if (EndExpr.isInvalid())
1818 return StmtError();
1819 }
1820
1821 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1822 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1823 if (!Context.hasSameType(BeginType, EndType)) {
1824 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1825 << BeginType << EndType;
1826 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1827 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1828 }
1829
1830 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1831 // Claim the type doesn't contain auto: we've already done the checking.
1832 DeclGroupPtrTy BeginEndGroup =
1833 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1834 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1835
Ted Kremeneke50b0152011-10-10 22:36:28 +00001836 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1837 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001838 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001839 if (BeginRef.isInvalid())
1840 return StmtError();
1841
Richard Smithad762fc2011-04-14 22:09:26 +00001842 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1843 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001844 if (EndRef.isInvalid())
1845 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001846
1847 // Build and check __begin != __end expression.
1848 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1849 BeginRef.get(), EndRef.get());
1850 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1851 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1852 if (NotEqExpr.isInvalid()) {
1853 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1854 if (!Context.hasSameType(BeginType, EndType))
1855 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1856 return StmtError();
1857 }
1858
1859 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001860 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1861 VK_LValue, ColonLoc);
1862 if (BeginRef.isInvalid())
1863 return StmtError();
1864
Richard Smithad762fc2011-04-14 22:09:26 +00001865 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1866 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1867 if (IncrExpr.isInvalid()) {
1868 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1869 return StmtError();
1870 }
1871
1872 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001873 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1874 VK_LValue, ColonLoc);
1875 if (BeginRef.isInvalid())
1876 return StmtError();
1877
Richard Smithad762fc2011-04-14 22:09:26 +00001878 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1879 if (DerefExpr.isInvalid()) {
1880 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1881 return StmtError();
1882 }
1883
1884 // Attach *__begin as initializer for VD.
1885 if (!LoopVar->isInvalidDecl()) {
1886 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1887 /*TypeMayContainAuto=*/true);
1888 if (LoopVar->isInvalidDecl())
1889 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1890 }
Richard Smithcd6f3662011-06-21 23:07:19 +00001891 } else {
1892 // The range is implicitly used as a placeholder when it is dependent.
1893 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00001894 }
1895
1896 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1897 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1898 NotEqExpr.take(), IncrExpr.take(),
1899 LoopVarDS, /*Body=*/0, ForLoc,
1900 ColonLoc, RParenLoc));
1901}
1902
1903/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1904/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1905/// body cannot be performed until after the type of the range variable is
1906/// determined.
1907StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1908 if (!S || !B)
1909 return StmtError();
1910
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001911 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1912 ForStmt->setBody(B);
1913
1914 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1915 diag::warn_empty_range_based_for_body);
1916
Richard Smithad762fc2011-04-14 22:09:26 +00001917 return S;
1918}
1919
Chris Lattner57ad3782011-02-17 20:34:02 +00001920StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1921 SourceLocation LabelLoc,
1922 LabelDecl *TheDecl) {
1923 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001924 TheDecl->setUsed();
1925 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001926}
1927
John McCall60d7b3a2010-08-24 06:29:42 +00001928StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00001929Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001930 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00001931 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001932 if (!E->isTypeDependent()) {
1933 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00001934 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00001935 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001936 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00001937 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1938 if (ExprRes.isInvalid())
1939 return StmtError();
1940 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00001941 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001942 return StmtError();
Eli Friedmand29975f2012-01-31 22:47:07 +00001943 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001944 }
John McCallb60a77e2010-08-01 00:26:45 +00001945
John McCall781472f2010-08-25 08:40:02 +00001946 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00001947
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001948 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001949}
1950
John McCall60d7b3a2010-08-24 06:29:42 +00001951StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001952Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 Scope *S = CurScope->getContinueParent();
1954 if (!S) {
1955 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001956 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001958
Ted Kremenek8189cde2009-02-07 01:47:29 +00001959 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001960}
1961
John McCall60d7b3a2010-08-24 06:29:42 +00001962StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001963Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 Scope *S = CurScope->getBreakParent();
1965 if (!S) {
1966 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001967 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001969
Ted Kremenek8189cde2009-02-07 01:47:29 +00001970 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001971}
1972
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001973/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001974/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00001975///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001976/// \param ReturnType If we're determining the copy elision candidate for
1977/// a return statement, this is the return type of the function. If we're
1978/// determining the copy elision candidate for a throw expression, this will
1979/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00001980///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001981/// \param E The expression being returned from the function or block, or
1982/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00001983///
Douglas Gregor4926d832011-05-20 15:00:53 +00001984/// \param AllowFunctionParameter Whether we allow function parameters to
1985/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1986/// we re-use this logic to determine whether we should try to move as part of
1987/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00001988///
1989/// \returns The NRVO candidate variable, if the return statement may use the
1990/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001991const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1992 Expr *E,
1993 bool AllowFunctionParameter) {
1994 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001995 // - in a return statement in a function with ...
1996 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001997 if (!ReturnType.isNull()) {
1998 if (!ReturnType->isRecordType())
1999 return 0;
2000 // ... the same cv-unqualified type as the function return type ...
2001 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2002 return 0;
2003 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002004
2005 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002006 // (other than a function or catch-clause parameter)) ...
2007 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002008 if (!DR)
Douglas Gregor5077c382010-05-15 06:01:05 +00002009 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002010 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2011 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002012 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002013
John McCall1cd76e82011-11-11 03:57:31 +00002014 // ...object (other than a function or catch-clause parameter)...
2015 if (VD->getKind() != Decl::Var &&
2016 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2017 return 0;
2018 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002019
John McCall1cd76e82011-11-11 03:57:31 +00002020 // ...automatic...
2021 if (!VD->hasLocalStorage()) return 0;
2022
2023 // ...non-volatile...
2024 if (VD->getType().isVolatileQualified()) return 0;
2025 if (VD->getType()->isReferenceType()) return 0;
2026
2027 // __block variables can't be allocated in a way that permits NRVO.
2028 if (VD->hasAttr<BlocksAttr>()) return 0;
2029
2030 // Variables with higher required alignment than their type's ABI
2031 // alignment cannot use NRVO.
2032 if (VD->hasAttr<AlignedAttr>() &&
2033 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2034 return 0;
2035
2036 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002037}
2038
Douglas Gregor07f402c2011-01-21 21:08:57 +00002039/// \brief Perform the initialization of a potentially-movable value, which
2040/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002041///
2042/// This routine implements C++0x [class.copy]p33, which attempts to treat
2043/// returned lvalues as rvalues in certain cases (to prefer move construction),
2044/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002045ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002046Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2047 const VarDecl *NRVOCandidate,
2048 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002049 Expr *Value,
2050 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002051 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002052 // When the criteria for elision of a copy operation are met or would
2053 // be met save for the fact that the source object is a function
2054 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002055 // overload resolution to select the constructor for the copy is first
2056 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002057 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002058 if (AllowNRVO &&
2059 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002061 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002062
Douglas Gregorcc15f012011-01-21 19:38:21 +00002063 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002064 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002065 = InitializationKind::CreateCopy(Value->getLocStart(),
2066 Value->getLocStart());
2067 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002068
2069 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002070 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002071 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002072 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002073 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002074 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2075 StepEnd = Seq.step_end();
2076 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002077 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002078 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079
2080 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002081 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002082
Douglas Gregorcc15f012011-01-21 19:38:21 +00002083 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002084 = Constructor->getParamDecl(0)->getType()
2085 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002086
Douglas Gregorcc15f012011-01-21 19:38:21 +00002087 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002088 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002089 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2090 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002091 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002092
Douglas Gregorcc15f012011-01-21 19:38:21 +00002093 // Promote "AsRvalue" to the heap, since we now need this
2094 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002095 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002096 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002097
Douglas Gregorcc15f012011-01-21 19:38:21 +00002098 // Complete type-checking the initialization of the return type
2099 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002100 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002101 }
2102 }
2103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002104
Douglas Gregorcc15f012011-01-21 19:38:21 +00002105 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002106 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002107 // (again) now with the return value expression as written.
2108 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002109 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002110
Douglas Gregorcc15f012011-01-21 19:38:21 +00002111 return Res;
2112}
2113
Eli Friedman84b007f2012-01-26 03:00:14 +00002114/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2115/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002116///
John McCall60d7b3a2010-08-24 06:29:42 +00002117StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002118Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2119 // If this is the first return we've seen, infer the return type.
2120 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2121 // rules which allows multiple return statements.
2122 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2123 if (CurCap->HasImplicitReturnType) {
2124 QualType ReturnT;
Douglas Gregora0c2b212012-02-09 18:40:39 +00002125 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002126 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2127 if (Result.isInvalid())
2128 return StmtError();
2129 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002130
Eli Friedman84b007f2012-01-26 03:00:14 +00002131 if (!RetValExp->isTypeDependent())
2132 ReturnT = RetValExp->getType();
2133 else
2134 ReturnT = Context.DependentTy;
Douglas Gregora0c2b212012-02-09 18:40:39 +00002135 } else {
2136 if (RetValExp) {
2137 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2138 // initializer list, because it is not an expression (even
2139 // though we represent it as one). We still deduce 'void'.
2140 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2141 << RetValExp->getSourceRange();
2142 }
2143
Eli Friedman84b007f2012-01-26 03:00:14 +00002144 ReturnT = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002145 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002146 // We require the return types to strictly match here.
2147 if (!CurCap->ReturnType.isNull() &&
2148 !CurCap->ReturnType->isDependentType() &&
2149 !ReturnT->isDependentType() &&
2150 !Context.hasSameType(ReturnT, CurCap->ReturnType)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002151 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Douglas Gregor4e88df72012-02-15 15:57:22 +00002152 << ReturnT << CurCap->ReturnType
Douglas Gregor0bcc3d82012-02-15 15:59:09 +00002153 << (getCurLambda() != 0);
Eli Friedman84b007f2012-01-26 03:00:14 +00002154 return StmtError();
2155 }
2156 CurCap->ReturnType = ReturnT;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002157 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002158 QualType FnRetType = CurCap->ReturnType;
2159 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002160
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002161 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002162 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2163 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2164 return StmtError();
2165 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002166 } else {
2167 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2168 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2169 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2170 return StmtError();
2171 }
2172 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002173
Steve Naroff4eb206b2008-09-03 18:15:37 +00002174 // Otherwise, verify that this result type matches the previous one. We are
2175 // pickier with blocks than for normal functions because we don't have GCC
2176 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002177 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002178 if (FnRetType->isDependentType()) {
2179 // Delay processing for now. TODO: there are lots of dependent
2180 // types we can conclusively prove aren't void.
2181 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002182 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002183 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002184 (RetValExp->isTypeDependent() ||
2185 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002186 if (!getLangOpts().CPlusPlus &&
2187 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002188 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002189 else {
2190 Diag(ReturnLoc, diag::err_return_block_has_expr);
2191 RetValExp = 0;
2192 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002193 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002194 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002195 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2196 } else if (!RetValExp->isTypeDependent()) {
2197 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002198
John McCall0a7efe12011-08-17 22:09:46 +00002199 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2200 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2201 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002202
John McCall0a7efe12011-08-17 22:09:46 +00002203 // In C++ the return statement is handled via a copy initialization.
2204 // the C version of which boils down to CheckSingleAssignmentConstraints.
2205 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2206 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2207 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002208 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002209 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2210 FnRetType, RetValExp);
2211 if (Res.isInvalid()) {
2212 // FIXME: Cleanup temporaries here, anyway?
2213 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002214 }
John McCall0a7efe12011-08-17 22:09:46 +00002215 RetValExp = Res.take();
2216 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002217 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002218
John McCalld963c372011-08-17 21:34:14 +00002219 if (RetValExp) {
2220 CheckImplicitConversions(RetValExp, ReturnLoc);
2221 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2222 }
John McCall0a7efe12011-08-17 22:09:46 +00002223 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2224 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002225
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002226 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002227 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002228 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002229 !CurContext->isDependentContext())
2230 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002231
Douglas Gregor5077c382010-05-15 06:01:05 +00002232 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002233}
Reid Spencer5f016e22007-07-11 17:01:13 +00002234
John McCall60d7b3a2010-08-24 06:29:42 +00002235StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002236Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002237 // Check for unexpanded parameter packs.
2238 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2239 return StmtError();
2240
Eli Friedman84b007f2012-01-26 03:00:14 +00002241 if (isa<CapturingScopeInfo>(getCurFunction()))
2242 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002243
Chris Lattner371f2582008-12-04 23:50:19 +00002244 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002245 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002246 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002247 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002248 if (FD->hasAttr<NoReturnAttr>() ||
2249 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002250 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002251 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002252 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002253 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002254 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2255 // In the implementation of a method with a related return type, the
2256 // type used to type-check the validity of return statements within the
2257 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002258 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2259 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002260 }
2261 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002262 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Douglas Gregor5077c382010-05-15 06:01:05 +00002264 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002265 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002266 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002267 if (isa<InitListExpr>(RetValExp)) {
2268 // We simply never allow init lists as the return value of void
2269 // functions. This is compatible because this was never allowed before,
2270 // so there's no legacy code to deal with.
2271 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2272 int FunctionKind = 0;
2273 if (isa<ObjCMethodDecl>(CurDecl))
2274 FunctionKind = 1;
2275 else if (isa<CXXConstructorDecl>(CurDecl))
2276 FunctionKind = 2;
2277 else if (isa<CXXDestructorDecl>(CurDecl))
2278 FunctionKind = 3;
2279
2280 Diag(ReturnLoc, diag::err_return_init_list)
2281 << CurDecl->getDeclName() << FunctionKind
2282 << RetValExp->getSourceRange();
2283
2284 // Drop the expression.
2285 RetValExp = 0;
2286 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002287 // C99 6.8.6.4p1 (ext_ since GCC warns)
2288 unsigned D = diag::ext_return_has_expr;
2289 if (RetValExp->getType()->isVoidType())
2290 D = diag::ext_return_has_void_expr;
2291 else {
2292 ExprResult Result = Owned(RetValExp);
2293 Result = IgnoredValueConversions(Result.take());
2294 if (Result.isInvalid())
2295 return StmtError();
2296 RetValExp = Result.take();
2297 RetValExp = ImpCastExprToType(RetValExp,
2298 Context.VoidTy, CK_ToVoid).take();
2299 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002300
Nick Lewycky8d794612011-06-01 07:44:31 +00002301 // return (some void expression); is legal in C++.
2302 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002303 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002304 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002305
2306 int FunctionKind = 0;
2307 if (isa<ObjCMethodDecl>(CurDecl))
2308 FunctionKind = 1;
2309 else if (isa<CXXConstructorDecl>(CurDecl))
2310 FunctionKind = 2;
2311 else if (isa<CXXDestructorDecl>(CurDecl))
2312 FunctionKind = 3;
2313
Nick Lewycky8d794612011-06-01 07:44:31 +00002314 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002315 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002316 << RetValExp->getSourceRange();
2317 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002318 }
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Sebastian Redl33deb352012-02-22 10:50:08 +00002320 if (RetValExp) {
2321 CheckImplicitConversions(RetValExp, ReturnLoc);
2322 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2323 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002325
Douglas Gregor5077c382010-05-15 06:01:05 +00002326 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2327 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002328 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2329 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002330 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002331
2332 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002333 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002334 else
Chris Lattner08631c52008-11-23 21:45:46 +00002335 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002336 Result = new (Context) ReturnStmt(ReturnLoc);
2337 } else {
2338 const VarDecl *NRVOCandidate = 0;
2339 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2340 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002341
Eli Friedman38ac2432012-03-30 01:13:43 +00002342 if (!RelatedRetType.isNull()) {
2343 // If we have a related result type, perform an extra conversion here.
2344 // FIXME: The diagnostics here don't really describe what is happening.
2345 InitializedEntity Entity =
2346 InitializedEntity::InitializeTemporary(RelatedRetType);
2347
2348 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2349 RetValExp);
2350 if (Res.isInvalid()) {
2351 // FIXME: Cleanup temporaries here, anyway?
2352 return StmtError();
2353 }
2354 RetValExp = Res.takeAs<Expr>();
2355 }
2356
Douglas Gregor5077c382010-05-15 06:01:05 +00002357 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2358 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2359 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002360
John McCall856d3792011-06-16 23:24:51 +00002361 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002362 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002363 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002365 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002366 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002367 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002368 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002369 if (Res.isInvalid()) {
2370 // FIXME: Cleanup temporaries here, anyway?
2371 return StmtError();
2372 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002373
Douglas Gregor5077c382010-05-15 06:01:05 +00002374 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002375 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002376 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002377 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002378
John McCallb4eb64d2010-10-08 02:01:28 +00002379 if (RetValExp) {
2380 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00002381 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00002382 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002383 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002384 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002385
2386 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002387 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002388 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002389 !CurContext->isDependentContext())
2390 FunctionScopes.back()->Returns.push_back(Result);
John McCallf85e1932011-06-15 23:02:42 +00002391
Douglas Gregor5077c382010-05-15 06:01:05 +00002392 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002393}
2394
Chris Lattner810f6d52009-03-13 17:38:01 +00002395/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2396/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2397/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2398/// provide a strong guidance to not use it.
2399///
2400/// This method checks to see if the argument is an acceptable l-value and
2401/// returns false if it is a case we can handle.
2402static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00002403 // Type dependent expressions will be checked during instantiation.
2404 if (E->isTypeDependent())
2405 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002406
John McCall7eb0a9e2010-11-24 05:12:34 +00002407 if (E->isLValue())
Chris Lattner810f6d52009-03-13 17:38:01 +00002408 return false; // Cool, this is an lvalue.
2409
2410 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2411 // are supposed to allow.
2412 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall7eb0a9e2010-11-24 05:12:34 +00002413 if (E != E2 && E2->isLValue()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002414 if (!S.getLangOpts().HeinousExtensions)
Chris Lattner810f6d52009-03-13 17:38:01 +00002415 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2416 << E->getSourceRange();
2417 else
2418 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2419 << E->getSourceRange();
2420 // Accept, even if we emitted an error diagnostic.
2421 return false;
2422 }
2423
2424 // None of the above, just randomly invalid non-lvalue.
2425 return true;
2426}
2427
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002428/// isOperandMentioned - Return true if the specified operand # is mentioned
2429/// anywhere in the decomposed asm string.
2430static bool isOperandMentioned(unsigned OpNo,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002431 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002432 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2433 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2434 if (!Piece.isOperand()) continue;
2435
2436 // If this is a reference to the input and if the input was the smaller
2437 // one, then we have to reject this asm.
2438 if (Piece.getOperandNo() == OpNo)
2439 return true;
2440 }
2441
2442 return false;
2443}
Chris Lattner810f6d52009-03-13 17:38:01 +00002444
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002445StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2446 bool IsVolatile, unsigned NumOutputs,
2447 unsigned NumInputs, IdentifierInfo **Names,
2448 MultiExprArg constraints, MultiExprArg exprs,
2449 Expr *asmString, MultiExprArg clobbers,
2450 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002451 unsigned NumClobbers = clobbers.size();
2452 StringLiteral **Constraints =
2453 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00002454 Expr **Exprs = exprs.get();
2455 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00002456 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2457
Chris Lattner5f9e2722011-07-23 10:55:15 +00002458 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Chris Lattner1708b962008-08-18 19:55:17 +00002460 // The parser verifies that there is a string literal here.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002461 if (!AsmString->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002462 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2463 << AsmString->getSourceRange());
2464
Chris Lattner1708b962008-08-18 19:55:17 +00002465 for (unsigned i = 0; i != NumOutputs; i++) {
2466 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002467 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002468 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2469 << Literal->getSourceRange());
2470
Chris Lattner5f9e2722011-07-23 10:55:15 +00002471 StringRef OutputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002472 if (Names[i])
2473 OutputName = Names[i]->getName();
2474
2475 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002476 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002477 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002478 diag::err_asm_invalid_output_constraint)
2479 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00002480
Anders Carlssond04c6e22007-11-27 04:11:28 +00002481 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00002482 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00002483 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00002484 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002485 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00002486 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002487 }
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Chris Lattner44def072009-04-26 07:16:29 +00002489 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002490 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002491
Chris Lattner5f9e2722011-07-23 10:55:15 +00002492 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner806503f2009-05-03 05:55:43 +00002493
Anders Carlsson04728b72007-11-23 19:43:50 +00002494 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00002495 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002496 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002497 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2498 << Literal->getSourceRange());
2499
Chris Lattner5f9e2722011-07-23 10:55:15 +00002500 StringRef InputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002501 if (Names[i])
2502 InputName = Names[i]->getName();
2503
2504 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002505 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00002506 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002507 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002508 diag::err_asm_invalid_input_constraint)
2509 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00002510 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002511
Eli Friedman72056a22009-05-03 07:49:42 +00002512 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00002513
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002514 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00002515 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00002516 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00002517 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002518 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00002519 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002520 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002521 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002522
Chris Lattner44def072009-04-26 07:16:29 +00002523 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002524 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00002525 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002526 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00002527 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002528 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002529 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002530 }
Mike Stump1eb44332009-09-09 15:08:12 +00002531
John Wiegley429bb272011-04-08 18:41:53 +00002532 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2533 if (Result.isInvalid())
2534 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002535
John Wiegley429bb272011-04-08 18:41:53 +00002536 Exprs[i] = Result.take();
Chris Lattner806503f2009-05-03 05:55:43 +00002537 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002538 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002539
Anders Carlsson6fa90862007-11-25 00:25:21 +00002540 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00002541 for (unsigned i = 0; i != NumClobbers; i++) {
2542 StringLiteral *Literal = Clobbers[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002543 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002544 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2545 << Literal->getSourceRange());
2546
Chris Lattner5f9e2722011-07-23 10:55:15 +00002547 StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00002548
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002549 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002550 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00002551 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00002552 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002553
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002554 AsmStmt *NS =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002555 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2556 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson966146e2010-01-30 23:19:41 +00002557 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002558 // Validate the asm string, ensuring it makes sense given the operands we
2559 // have.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002560 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002561 unsigned DiagOffs;
2562 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00002563 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2564 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002565 return StmtError();
2566 }
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Chris Lattner806503f2009-05-03 05:55:43 +00002568 // Validate tied input operands for type mismatches.
2569 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2570 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Chris Lattner806503f2009-05-03 05:55:43 +00002572 // If this is a tied constraint, verify that the output and input have
2573 // either exactly the same type, or that they are int/ptr operands with the
2574 // same size (int/long, int*/long, are ok etc).
2575 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Chris Lattner806503f2009-05-03 05:55:43 +00002577 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner935f0f02011-02-21 22:09:29 +00002578 unsigned InputOpNo = i+NumOutputs;
Chris Lattnerf69fcae2009-05-03 07:04:21 +00002579 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner935f0f02011-02-21 22:09:29 +00002580 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedmanf45b3572011-09-14 19:20:00 +00002581
2582 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2583 continue;
2584
Chris Lattner7adaa182009-05-03 05:59:17 +00002585 QualType InTy = InputExpr->getType();
2586 QualType OutTy = OutputExpr->getType();
2587 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00002588 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Chris Lattneraab64d02010-04-23 17:27:29 +00002590 // Decide if the input and output are in the same domain (integer/ptr or
2591 // floating point.
2592 enum AsmDomain {
2593 AD_Int, AD_FP, AD_Other
2594 } InputDomain, OutputDomain;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595
Chris Lattneraab64d02010-04-23 17:27:29 +00002596 if (InTy->isIntegerType() || InTy->isPointerType())
2597 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002598 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002599 InputDomain = AD_FP;
2600 else
2601 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Chris Lattneraab64d02010-04-23 17:27:29 +00002603 if (OutTy->isIntegerType() || OutTy->isPointerType())
2604 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002605 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002606 OutputDomain = AD_FP;
2607 else
2608 OutputDomain = AD_Other;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002609
Chris Lattneraab64d02010-04-23 17:27:29 +00002610 // They are ok if they are the same size and in the same domain. This
2611 // allows tying things like:
2612 // void* to int*
2613 // void* to int if they are the same size.
2614 // double to long double if they are the same size.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002615 //
Chris Lattneraab64d02010-04-23 17:27:29 +00002616 uint64_t OutSize = Context.getTypeSize(OutTy);
2617 uint64_t InSize = Context.getTypeSize(InTy);
2618 if (OutSize == InSize && InputDomain == OutputDomain &&
2619 InputDomain != AD_Other)
2620 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002621
Chris Lattneraab64d02010-04-23 17:27:29 +00002622 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002623 // then we can promote the smaller one to a larger input and the asm string
2624 // won't notice.
Chris Lattneraab64d02010-04-23 17:27:29 +00002625 bool SmallerValueMentioned = false;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002626
2627 // If this is a reference to the input and if the input was the smaller
2628 // one, then we have to reject this asm.
Chris Lattner935f0f02011-02-21 22:09:29 +00002629 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002630 // This is a use in the asm string of the smaller operand. Since we
2631 // codegen this by promoting to a wider value, the asm will get printed
2632 // "wrong".
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002633 SmallerValueMentioned |= InSize < OutSize;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002634 }
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002635 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002636 // If this is a reference to the output, and if the output is the larger
2637 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002638 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner806503f2009-05-03 05:55:43 +00002639 }
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Chris Lattneraab64d02010-04-23 17:27:29 +00002641 // If the smaller value wasn't mentioned in the asm string, and if the
2642 // output was a register, just extend the shorter one to the size of the
2643 // larger one.
2644 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2645 OutputConstraintInfos[TiedTo].allowsRegister())
2646 continue;
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002647
Chris Lattner935f0f02011-02-21 22:09:29 +00002648 // Either both of the operands were mentioned or the smaller one was
2649 // mentioned. One more special case that we'll allow: if the tied input is
2650 // integer, unmentioned, and is a constant, then we'll allow truncating it
2651 // down to the size of the destination.
2652 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2653 !isOperandMentioned(InputOpNo, Pieces) &&
2654 InputExpr->isEvaluatable(Context)) {
John McCall4da89c82011-05-10 23:39:47 +00002655 CastKind castKind =
2656 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2657 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner935f0f02011-02-21 22:09:29 +00002658 Exprs[InputOpNo] = InputExpr;
2659 NS->setInputExpr(i, InputExpr);
2660 continue;
2661 }
2662
Chris Lattnerc1f3b282009-05-03 06:50:40 +00002663 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00002664 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00002665 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00002666 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00002667 return StmtError();
2668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002670 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00002671}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002672
Chad Rosier8cd64b42012-06-11 20:47:18 +00002673StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
2674 std::string &AsmString,
2675 SourceLocation EndLoc) {
2676 MSAsmStmt *NS =
2677 new (Context) MSAsmStmt(Context, AsmLoc, AsmString, EndLoc);
2678
2679 return Owned(NS);
2680}
2681
John McCall60d7b3a2010-08-24 06:29:42 +00002682StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002683Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002684 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002685 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002686 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002687 if (Var && Var->isInvalidDecl())
2688 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002689
John McCall9ae2f072010-08-23 23:25:46 +00002690 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002691}
2692
John McCall60d7b3a2010-08-24 06:29:42 +00002693StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002694Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2695 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002696}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002697
John McCall60d7b3a2010-08-24 06:29:42 +00002698StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002700 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002701 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002702 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2703
John McCall781472f2010-08-25 08:40:02 +00002704 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002705 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002706 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2707 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002708 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002709 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002710}
2711
John McCalld1376ee2012-05-08 21:41:25 +00002712StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002713 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002714 ExprResult Result = DefaultLvalueConversion(Throw);
2715 if (Result.isInvalid())
2716 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002717
John McCalld1376ee2012-05-08 21:41:25 +00002718 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregord1377b22010-04-22 21:44:01 +00002719 QualType ThrowType = Throw->getType();
2720 // Make sure the expression type is an ObjC pointer or "void *".
2721 if (!ThrowType->isDependentType() &&
2722 !ThrowType->isObjCObjectPointerType()) {
2723 const PointerType *PT = ThrowType->getAs<PointerType>();
2724 if (!PT || !PT->getPointeeType()->isVoidType())
2725 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2726 << Throw->getType() << Throw->getSourceRange());
2727 }
2728 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002729
John McCall9ae2f072010-08-23 23:25:46 +00002730 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002731}
2732
John McCall60d7b3a2010-08-24 06:29:42 +00002733StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002734Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002735 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002736 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002737 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2738
John McCall9ae2f072010-08-23 23:25:46 +00002739 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002740 // @throw without an expression designates a rethrow (which much occur
2741 // in the context of an @catch clause).
2742 Scope *AtCatchParent = CurScope;
2743 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2744 AtCatchParent = AtCatchParent->getParent();
2745 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002746 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002747 }
Fariborz Jahanianf2dd68f2011-07-20 23:39:56 +00002748
John McCall9ae2f072010-08-23 23:25:46 +00002749 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002750}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002751
John McCall07524032011-07-27 21:50:02 +00002752ExprResult
2753Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2754 ExprResult result = DefaultLvalueConversion(operand);
2755 if (result.isInvalid())
2756 return ExprError();
2757 operand = result.take();
2758
2759 // Make sure the expression type is an ObjC pointer or "void *".
2760 QualType type = operand->getType();
2761 if (!type->isDependentType() &&
2762 !type->isObjCObjectPointerType()) {
2763 const PointerType *pointerType = type->getAs<PointerType>();
2764 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2765 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2766 << type << operand->getSourceRange();
2767 }
2768
2769 // The operand to @synchronized is a full-expression.
2770 return MaybeCreateExprWithCleanups(operand);
2771}
2772
John McCall60d7b3a2010-08-24 06:29:42 +00002773StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002774Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2775 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002776 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002777 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002778 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002779}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002780
2781/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2782/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002783StmtResult
John McCalld226f652010-08-21 09:40:31 +00002784Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002785 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002786 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002787 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002788 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002789 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002790}
Sebastian Redl8351da02008-12-22 21:35:02 +00002791
John McCallf85e1932011-06-15 23:02:42 +00002792StmtResult
2793Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2794 getCurFunction()->setHasBranchProtectedScope();
2795 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2796}
2797
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002798namespace {
2799
Sebastian Redlc447aba2009-07-29 17:15:45 +00002800class TypeWithHandler {
2801 QualType t;
2802 CXXCatchStmt *stmt;
2803public:
2804 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2805 : t(type), stmt(statement) {}
2806
John McCall0953e762009-09-24 19:53:00 +00002807 // An arbitrary order is fine as long as it places identical
2808 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002809 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002810 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002811 return true;
John McCall0953e762009-09-24 19:53:00 +00002812 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002813 return false;
2814 else
2815 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2816 }
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Sebastian Redlc447aba2009-07-29 17:15:45 +00002818 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002819 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002820 }
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Sebastian Redlc447aba2009-07-29 17:15:45 +00002822 CXXCatchStmt *getCatchStmt() const { return stmt; }
2823 SourceLocation getTypeSpecStartLoc() const {
2824 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2825 }
2826};
2827
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002828}
2829
Sebastian Redl8351da02008-12-22 21:35:02 +00002830/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2831/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002832StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002833Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002834 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002835 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002836 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002837 !getSourceManager().isInSystemHeader(TryLoc))
2838 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002839
Sebastian Redl8351da02008-12-22 21:35:02 +00002840 unsigned NumHandlers = RawHandlers.size();
2841 assert(NumHandlers > 0 &&
2842 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00002843 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00002844
Chris Lattner5f9e2722011-07-23 10:55:15 +00002845 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002846
2847 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002848 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002849 if (!Handler->getExceptionDecl()) {
2850 if (i < NumHandlers - 1)
2851 return StmtError(Diag(Handler->getLocStart(),
2852 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Sebastian Redlc447aba2009-07-29 17:15:45 +00002854 continue;
2855 }
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Sebastian Redlc447aba2009-07-29 17:15:45 +00002857 const QualType CaughtType = Handler->getCaughtType();
2858 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2859 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002860 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002861
2862 // Detect handlers for the same type as an earlier one.
2863 if (NumHandlers > 1) {
2864 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Sebastian Redlc447aba2009-07-29 17:15:45 +00002866 TypeWithHandler prev = TypesWithHandlers[0];
2867 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2868 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Sebastian Redlc447aba2009-07-29 17:15:45 +00002870 if (curr == prev) {
2871 Diag(curr.getTypeSpecStartLoc(),
2872 diag::warn_exception_caught_by_earlier_handler)
2873 << curr.getCatchStmt()->getCaughtType().getAsString();
2874 Diag(prev.getTypeSpecStartLoc(),
2875 diag::note_previous_exception_handler)
2876 << prev.getCatchStmt()->getCaughtType().getAsString();
2877 }
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Sebastian Redlc447aba2009-07-29 17:15:45 +00002879 prev = curr;
2880 }
2881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882
John McCall781472f2010-08-25 08:40:02 +00002883 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002884
Sebastian Redl8351da02008-12-22 21:35:02 +00002885 // FIXME: We should detect handlers that cannot catch anything because an
2886 // earlier handler catches a superclass. Need to find a method that is not
2887 // quadratic for this.
2888 // Neither of these are explicitly forbidden, but every compiler detects them
2889 // and warns.
2890
John McCall9ae2f072010-08-23 23:25:46 +00002891 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00002892 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00002893}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002894
2895StmtResult
2896Sema::ActOnSEHTryBlock(bool IsCXXTry,
2897 SourceLocation TryLoc,
2898 Stmt *TryBlock,
2899 Stmt *Handler) {
2900 assert(TryBlock && Handler);
2901
2902 getCurFunction()->setHasBranchProtectedScope();
2903
2904 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2905}
2906
2907StmtResult
2908Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2909 Expr *FilterExpr,
2910 Stmt *Block) {
2911 assert(FilterExpr && Block);
2912
2913 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002914 return StmtError(Diag(FilterExpr->getExprLoc(),
2915 diag::err_filter_expression_integral)
2916 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002917 }
2918
2919 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2920}
2921
2922StmtResult
2923Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2924 Stmt *Block) {
2925 assert(Block);
2926 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2927}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002928
2929StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2930 bool IsIfExists,
2931 NestedNameSpecifierLoc QualifierLoc,
2932 DeclarationNameInfo NameInfo,
2933 Stmt *Nested)
2934{
2935 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2936 QualifierLoc, NameInfo,
2937 cast<CompoundStmt>(Nested));
2938}
2939
2940
2941StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2942 bool IsIfExists,
2943 CXXScopeSpec &SS,
2944 UnqualifiedId &Name,
2945 Stmt *Nested) {
2946 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2947 SS.getWithLocInContext(Context),
2948 GetNameFromUnqualifiedId(Name),
2949 Nested);
2950}