blob: 20b0d2f166a37b4b6470431395d003a7c67e221d [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Richard Smith02e85f32011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
John McCall03318c12011-11-11 03:57:31 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000024#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000028#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000029#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000035using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000036using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000037
John McCalldadc5752010-08-24 06:29:42 +000038StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000039 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000040 if (!E) // FIXME: FullExprArg has no error state?
41 return StmtError();
42
Chris Lattner903eb512008-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 Redl52f03ba2008-12-21 12:04:03 +000046
Chris Lattner903eb512008-07-25 23:18:17 +000047 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000048 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000049}
50
51
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000052StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000053 bool HasLeadingEmptyMacro) {
54 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000055}
56
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000057StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000059 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattnercbafe8d2009-04-12 20:13:14 +000061 // If we have an invalid decl, just return an error.
62 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner34a22092009-03-04 04:23:07 +000064 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000065}
Chris Lattneraf8d5812006-11-10 05:07:45 +000066
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000067void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000069
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000070 // If we have an invalid decl, just return.
71 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000072 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
73
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000074 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000075 var->setUsed();
76
John McCalld4631322011-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 McCall31168b02011-06-15 23:02:42 +000080
John McCalld4631322011-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 Blaikiebbafb8a2012-03-11 07:00:24 +000084 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-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 McCall31168b02011-06-15 23:02:42 +000094 }
95 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000096}
97
Chandler Carruthe2669392011-08-17 09:34:37 +000098/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +000099///
100/// Adding a cast to void (or other expression wrappers) will prevent the
101/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000102static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000103 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000104 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-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 Carruthe2669392011-08-17 09:34:37 +0000108 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000109
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000110 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000111 IsNotEqual = Op->getOpcode() == BO_NE;
112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-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 Carruthe2669392011-08-17 09:34:37 +0000116 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000117
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000118 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000121 } else {
122 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000123 return false;
Chandler Carruthae51ecc2011-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 Carruthe2669392011-08-17 09:34:37 +0000129 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
Chandler Carruthe2669392011-08-17 09:34:37 +0000131 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 << (unsigned)IsNotEqual << E->getSourceRange();
133
Chandler Carruthe89ca5f2011-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 Carruthe2669392011-08-17 09:34:37 +0000144
145 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000146}
147
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000148void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150 return DiagnoseUnusedExprResult(Label->getSubStmt());
151
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000152 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000153 if (!E)
154 return;
155
Eli Friedmanc11535c2012-05-24 00:47:05 +0000156 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000157 SourceLocation Loc;
158 SourceRange R1, R2;
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +0000159 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmanc11535c2012-05-24 00:47:05 +0000160 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000161 return;
Mike Stump11289f42009-09-09 15:08:12 +0000162
Chris Lattner2ba5ca92009-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 McCall5d413782010-12-06 08:20:24 +0000167 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000168 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000169 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
170 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000171
Chandler Carruthe2669392011-08-17 09:34:37 +0000172 if (DiagnoseUnusedComparison(*this, E))
173 return;
174
Eli Friedmanc11535c2012-05-24 00:47:05 +0000175 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000176 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000177 if (E->getType()->isVoidType())
178 return;
179
Chris Lattner1a6babf2009-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 Lopes518e3702009-12-20 23:11:08 +0000182 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000183 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000184 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000195 }
John McCallb7bd14f2010-12-02 01:19:52 +0000196 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000197 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000198 Diag(Loc, diag::err_arc_unused_init_message) << R1;
199 return;
200 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000201 const ObjCMethodDecl *MD = ME->getMethodDecl();
202 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000203 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000204 return;
205 }
Ted Kremeneke65b0862012-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 Gregorb33eed02010-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 Jahanian5cab26d2010-03-30 18:22:15 +0000217 }
John McCall2351cb92010-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 Friedmanc11535c2012-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 Kremenek3427fac2011-02-23 01:52:04 +0000238 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000239}
240
Dmitri Gribenko800ddf32012-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 McCalldadc5752010-08-24 06:29:42 +0000253StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000254Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000255 MultiStmtArg elts, bool isStmtExpr) {
256 unsigned NumElts = elts.size();
257 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000260 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-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 Stump11289f42009-09-09 15:08:12 +0000270
Chris Lattnerd864daf2007-08-27 04:29:41 +0000271 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000272 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000273 Diag(D->getLocation(), diag::ext_mixed_decls_code);
274 }
275 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000276 // Warn about unused expressions in statements.
277 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000278 // Ignore statements that are last in a statement expression.
279 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000280 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000281
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000282 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000283 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000284
Dmitri Gribenko800ddf32012-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 Kremenek5a201952009-02-07 01:47:29 +0000294 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000295}
296
John McCalldadc5752010-08-24 06:29:42 +0000297StmtResult
John McCallb268a282010-08-23 23:25:46 +0000298Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
299 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000300 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000301 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000302
John McCallaab3e412010-08-25 08:40:02 +0000303 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000304 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000305 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000306 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000307
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-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 Smithf4c51d92012-02-04 09:53:13 +0000311 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
312 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
313 if (!LHSVal)
314 return StmtError();
315 }
Richard Smithf8379a02012-01-18 23:55:52 +0000316
317 // GCC extension: The expression shall be an integer constant.
318
Richard Smithf4c51d92012-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 Smithf8379a02012-01-18 23:55:52 +0000322 }
323 }
324
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000325 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
326 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000327 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000328 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000329}
330
Chris Lattner34a22092009-03-04 04:23:07 +0000331/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000332void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000333 DiagnoseUnusedExprResult(SubStmt);
334
Chris Lattner34a22092009-03-04 04:23:07 +0000335 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000336 CS->setSubStmt(SubStmt);
337}
338
John McCalldadc5752010-08-24 06:29:42 +0000339StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000340Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000341 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000342 DiagnoseUnusedExprResult(SubStmt);
343
John McCallaab3e412010-08-25 08:40:02 +0000344 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000345 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000346 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000347 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000348
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000349 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000350 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000351 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000352}
353
John McCalldadc5752010-08-24 06:29:42 +0000354StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000355Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
356 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-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 Redl6a8002e2009-01-11 00:38:46 +0000361 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000362 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000363
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000364 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000365 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
366 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000367 if (!TheDecl->isGnuLocal())
368 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000369 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000370}
371
Richard Smithc202b282012-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 McCalldadc5752010-08-24 06:29:42 +0000382StmtResult
John McCall48871652010-08-21 09:40:31 +0000383Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000384 Stmt *thenStmt, SourceLocation ElseLoc,
385 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000386 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000387
Douglas Gregor633caca2009-11-23 23:44:04 +0000388 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000389 if (CondVar) {
390 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000391 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000392 if (CondResult.isInvalid())
393 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000394 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000395 Expr *ConditionExpr = CondResult.takeAs<Expr>();
396 if (!ConditionExpr)
397 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000399 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000400
John McCallb268a282010-08-23 23:25:46 +0000401 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000402 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
403 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000404 }
405
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000406 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000407
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000409 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000410}
Steve Naroff86272ea2007-05-29 02:14:17 +0000411
Chris Lattnerfc1c44a2007-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 Stump11289f42009-09-09 15:08:12 +0000417 SourceLocation Loc,
Chris Lattnerfc1c44a2007-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 Foad6d4db0c2010-12-07 08:25:34 +0000422 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000423 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-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 Lattnerfc1c44a2007-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 Foad6d4db0c2010-12-07 08:25:34 +0000432 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000433 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000434 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000435 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000436 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000437 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000439 // Regardless of whether a diagnostic was emitted, really do the
440 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000441 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000442 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-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 Takumif9cbcc42011-01-27 07:10:08 +0000446 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000447 // behavior.
448 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000449 llvm::APSInt OldVal(Val);
450 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000451 }
452}
453
Chris Lattner67998452007-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 Lattner1463cca2007-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 Lattner67998452007-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 Lattner4b2ff022007-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 Gregorbd6839732010-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 Lattnera96d4272009-10-16 16:45:22 +0000501/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
502/// potentially integral-promoted expression @p expr.
John McCall5939b162011-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 Lattnera96d4272009-10-16 16:45:22 +0000509 }
510 return expr->getType();
511}
512
John McCalldadc5752010-08-24 06:29:42 +0000513StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000514Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000515 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000516 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000517
Douglas Gregore60e41a2010-05-06 17:25:47 +0000518 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000519 if (CondVar) {
520 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000521 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
522 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000523 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000524
John McCallb268a282010-08-23 23:25:46 +0000525 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
John McCallb268a282010-08-23 23:25:46 +0000528 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000529 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Douglas Gregore2b37442012-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 McCallb268a282010-08-23 23:25:46 +0000579 CondResult
Douglas Gregore2b37442012-05-04 22:38:52 +0000580 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +0000581 /*AllowScopedEnumerations*/ true);
John McCallb268a282010-08-23 23:25:46 +0000582 if (CondResult.isInvalid()) return StmtError();
583 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
John McCall5939b162011-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 McCall48871652010-08-21 09:40:31 +0000590 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000591 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000592 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000593 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000594 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000595 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000596 }
John McCalla95172b2010-08-01 00:26:45 +0000597
John McCallaab3e412010-08-25 08:40:02 +0000598 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
John McCallb268a282010-08-23 23:25:46 +0000600 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000601 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000602 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000603}
604
Gabor Greif16e02862010-10-01 22:05:14 +0000605static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
606 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000607 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000608 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000609 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000610 Val.setIsSigned(IsSigned);
611}
612
John McCalldadc5752010-08-24 06:29:42 +0000613StmtResult
John McCallb268a282010-08-23 23:25:46 +0000614Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
615 Stmt *BodyStmt) {
616 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000617 assert(SS == getCurFunction()->SwitchStack.back() &&
618 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000619
Steve Naroff42a350a2007-09-01 21:08:38 +0000620 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000621 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000622
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000623 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000624 if (!CondExpr) return StmtError();
625
626 QualType CondType = CondExpr->getType();
627
John McCalld3dfbd62010-05-18 03:19:21 +0000628 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000629 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000630 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000631
Chris Lattnera96d4272009-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'Callaghan93135aa2009-10-17 19:32:54 +0000639 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000640 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000642 // appropriate type now, just return an error.
643 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000644 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000645
Chris Lattner4ebae652010-04-16 23:34:13 +0000646 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-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 Carlsson51873c22007-07-22 07:07:56 +0000653 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000654
Chris Lattnerfc1c44a2007-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 Stump11289f42009-09-09 15:08:12 +0000657 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000658 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000659 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000660 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000661 bool CondIsSigned
662 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000663
Chris Lattnerfc1c44a2007-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 Lattner0e62c1c2011-07-23 10:55:15 +0000667 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000668 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000670 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000671 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
672 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000674 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattner10cb5e52007-08-23 06:23:56 +0000676 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000678 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000679 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000680
Anders Carlsson51873c22007-07-22 07:07:56 +0000681 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000682 if (TheDefaultStmt) {
683 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000684 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000685
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000686 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-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 Lattner10cb5e52007-08-23 06:23:56 +0000690 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000691 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000692 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000694 } else {
695 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattnera65e1f32008-01-16 19:17:22 +0000697 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000698
699 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
700 HasDependentValue = true;
701 break;
702 }
Mike Stump11289f42009-09-09 15:08:12 +0000703
Richard Smithf8379a02012-01-18 23:55:52 +0000704 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000705
David Blaikiebbafb8a2012-03-11 07:00:24 +0000706 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-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 Lattnerfc1c44a2007-08-23 05:46:52 +0000733 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000734 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000735 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000736
Chris Lattnera65e1f32008-01-16 19:17:22 +0000737 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000738
Chris Lattner10cb5e52007-08-23 06:23:56 +0000739 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000740 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000741 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000742 CS->getRHS()->isValueDependent()) {
743 HasDependentValue = true;
744 break;
745 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000746 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000747 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000748 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000749 }
750 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000751
752 if (!HasDependentValue) {
John McCalld3dfbd62010-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 McCalld3dfbd62010-05-18 03:19:21 +0000757 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000758 HasConstantCond
Richard Smith5fab0c92011-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 McCalld3dfbd62010-05-18 03:19:21 +0000764 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000765 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000766
Douglas Gregor2a2d00f2009-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 McCalld3dfbd62010-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 Gregor2a2d00f2009-05-15 23:57:33 +0000777 // If we have a duplicate, report it.
Douglas Gregor9841df62012-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 Gregor0a9f4e02012-05-16 16:11:17 +0000788 llvm::SmallString<16> CaseValStr;
789 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000790
791 if (PrevString == CurrString)
792 Diag(CaseVals[i].second->getLHS()->getLocStart(),
793 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000794 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000795 else
796 Diag(CaseVals[i].second->getLHS()->getLocStart(),
797 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000798 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
799 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000800 CaseValStr;
801
John McCalld3dfbd62010-05-18 03:19:21 +0000802 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000803 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-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 Gregor2a2d00f2009-05-15 23:57:33 +0000806 CaseListIsErroneous = true;
807 }
808 }
809 }
Mike Stump11289f42009-09-09 15:08:12 +0000810
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregor2a2d00f2009-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 McCalld3dfbd62010-05-18 03:19:21 +0000821 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000822 CaseStmt *CR = CaseRanges[i].second;
823 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000824 llvm::APSInt HiVal;
825
David Blaikiebbafb8a2012-03-11 07:00:24 +0000826 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-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 Stump11289f42009-09-09 15:08:12 +0000845
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000846 // Convert the value to the same width/sign as the condition.
847 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000848 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000849 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000850
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000851 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000852
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000853 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000854 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000855 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
856 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000857 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000858 CaseRanges.erase(CaseRanges.begin()+i);
859 --i, --e;
860 continue;
861 }
John McCalld3dfbd62010-05-18 03:19:21 +0000862
863 if (ShouldCheckConstantCond &&
864 LoVal <= ConstantCondValue &&
865 ConstantCondValue <= HiVal)
866 ShouldCheckConstantCond = false;
867
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000868 HiVals.push_back(HiVal);
869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000878
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000883
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000893
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000900
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor2a2d00f2009-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 Stump11289f42009-09-09 15:08:12 +0000912 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000913 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-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 Gregor2a2d00f2009-05-15 23:57:33 +0000916 CaseListIsErroneous = true;
917 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000918 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000919 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000920
John McCalld3dfbd62010-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 Kremenekc42f3452010-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 McCalld3dfbd62010-05-18 03:19:21 +0000934 //
Chris Lattner51679082010-09-16 17:09:42 +0000935 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000936
Douglas Gregorbd6839732010-02-08 22:24:16 +0000937 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000938 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000939 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000940 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000941 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000942 EnumValsTy EnumVals;
943
John McCalld3dfbd62010-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 Greif16e02862010-10-01 22:05:14 +0000947 EDI != ED->enumerator_end(); ++EDI) {
948 llvm::APSInt Val = EDI->getInitVal();
949 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie40ed2972012-06-06 20:45:41 +0000950 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000951 }
952 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000953 EnumValsTy::iterator EIend =
954 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000955
956 // See which case values aren't in enum.
David Blaikiee476f972012-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 Jahaniana6983a92012-03-21 20:56:29 +0000964 << CondTypeBeforePromotion;
David Blaikiee476f972012-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 Takumif9cbcc42011-01-27 07:10:08 +0000972
David Blaikiee476f972012-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 Jahaniana6983a92012-03-21 20:56:29 +0000975 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +0000976 }
David Blaikiee476f972012-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 Jahaniana6983a92012-03-21 20:56:29 +0000985 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000986 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987
Ted Kremenekc42f3452010-09-09 00:05:53 +0000988 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000989 CaseValsTy::const_iterator CI = CaseVals.begin();
990 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000991 bool hasCasesNotInSwitch = false;
992
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000993 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000994
David Blaikiee476f972012-01-22 02:31:55 +0000995 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000996 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000997 llvm::APSInt CIVal;
998 while (CI != CaseVals.end() && CI->first < EI->first)
999 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000
Douglas Gregorbd6839732010-02-08 22:24:16 +00001001 if (CI != CaseVals.end() && CI->first == EI->first)
1002 continue;
1003
Ted Kremenekc42f3452010-09-09 00:05:53 +00001004 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001005 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001006 llvm::APSInt Hi =
1007 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001008 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001009 if (EI->first <= Hi)
1010 break;
1011 }
1012
Ted Kremenekc42f3452010-09-09 00:05:53 +00001013 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001014 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001015 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001016 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001018
David Blaikie60ac6382012-01-23 04:46:12 +00001019 if (TheDefaultStmt && UnhandledNames.empty())
1020 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001021
Chris Lattner51679082010-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 Blaikie60ac6382012-01-23 04:46:12 +00001026 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1027 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001028 << UnhandledNames[0];
1029 break;
1030 case 2:
David Blaikie60ac6382012-01-23 04:46:12 +00001031 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1032 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001033 << UnhandledNames[0] << UnhandledNames[1];
1034 break;
1035 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001036 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1037 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001038 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1039 break;
1040 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001041 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1042 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001043 << (unsigned)UnhandledNames.size()
1044 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1045 break;
1046 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001047
1048 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001049 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001050 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001051 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001052
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001053 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1054 diag::warn_empty_switch_body);
1055
Mike Stump87c57ac2009-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 Lattner10cb5e52007-08-23 06:23:56 +00001058 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001059 return StmtError();
1060
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001061 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001062}
1063
John McCalldadc5752010-08-24 06:29:42 +00001064StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001066 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001067 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
Douglas Gregor680f8612009-11-24 21:15:44 +00001069 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001070 if (CondVar) {
1071 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001072 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001073 if (CondResult.isInvalid())
1074 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001075 }
John McCallb268a282010-08-23 23:25:46 +00001076 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001077 if (!ConditionExpr)
1078 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
John McCallb268a282010-08-23 23:25:46 +00001080 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001081
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001082 if (isa<NullStmt>(Body))
1083 getCurCompoundScope().setHasEmptyLoopBodies();
1084
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001085 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +00001086 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001087}
1088
John McCalldadc5752010-08-24 06:29:42 +00001089StmtResult
John McCallb268a282010-08-23 23:25:46 +00001090Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001091 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001092 Expr *Cond, SourceLocation CondRParen) {
1093 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001094
John Wiegley01296292011-04-08 18:41:53 +00001095 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1096 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001097 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001098 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001099
John McCallacf0ee52010-10-08 02:01:28 +00001100 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +00001101 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +00001102 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001103 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001104 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
John McCallb268a282010-08-23 23:25:46 +00001106 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001107
John McCallb268a282010-08-23 23:25:46 +00001108 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001109}
1110
Richard Trieu451a5db2012-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 Trieu451a5db2012-04-30 18:01:30 +00001119public:
1120 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1121
1122 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001123 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu451a5db2012-04-30 18:01:30 +00001124 Inherited(S.Context),
1125 Decls(Decls),
1126 Ranges(Ranges),
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001127 Simple(true) {}
Richard Trieu451a5db2012-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;
1196 //bool EvalDecl;
1197
1198public:
1199 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1200
1201 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1202 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1203 if (!Statement) return;
1204
1205 Visit(Statement);
1206 }
1207
1208 void VisitReturnStmt(ReturnStmt *S) {
1209 FoundDecl = true;
1210 }
1211
1212 void VisitBreakStmt(BreakStmt *S) {
1213 FoundDecl = true;
1214 }
1215
1216 void VisitGotoStmt(GotoStmt *S) {
1217 FoundDecl = true;
1218 }
1219
1220 void VisitCastExpr(CastExpr *E) {
1221 if (E->getCastKind() == CK_LValueToRValue)
1222 CheckLValueToRValueCast(E->getSubExpr());
1223 else
1224 Visit(E->getSubExpr());
1225 }
1226
1227 void CheckLValueToRValueCast(Expr *E) {
1228 E = E->IgnoreParenImpCasts();
1229
1230 if (isa<DeclRefExpr>(E)) {
1231 return;
1232 }
1233
1234 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1235 Visit(CO->getCond());
1236 CheckLValueToRValueCast(CO->getTrueExpr());
1237 CheckLValueToRValueCast(CO->getFalseExpr());
1238 return;
1239 }
1240
1241 if (BinaryConditionalOperator *BCO =
1242 dyn_cast<BinaryConditionalOperator>(E)) {
1243 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1244 CheckLValueToRValueCast(BCO->getFalseExpr());
1245 return;
1246 }
1247
1248 Visit(E);
1249 }
1250
1251 void VisitDeclRefExpr(DeclRefExpr *E) {
1252 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1253 if (Decls.count(VD))
1254 FoundDecl = true;
1255 }
1256
1257 bool FoundDeclInUse() { return FoundDecl; }
1258
1259 }; // end class DeclMatcher
1260
1261 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1262 Expr *Third, Stmt *Body) {
1263 // Condition is empty
1264 if (!Second) return;
1265
1266 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1267 Second->getLocStart())
1268 == DiagnosticsEngine::Ignored)
1269 return;
1270
1271 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1272 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1273 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001274 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001275 DE.Visit(Second);
1276
1277 // Don't analyze complex conditionals.
1278 if (!DE.isSimple()) return;
1279
1280 // No decls found.
1281 if (Decls.size() == 0) return;
1282
Richard Trieu0030f1d2012-05-04 03:01:54 +00001283 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001284 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1285 E = Decls.end();
1286 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001287 if ((*I)->getType().isVolatileQualified() ||
1288 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001289
1290 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1291 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1292 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1293 return;
1294
1295 // Load decl names into diagnostic.
1296 if (Decls.size() > 4)
1297 PDiag << 0;
1298 else {
1299 PDiag << Decls.size();
1300 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1301 E = Decls.end();
1302 I != E; ++I)
1303 PDiag << (*I)->getDeclName();
1304 }
1305
1306 // Load SourceRanges into diagnostic if there is room.
1307 // Otherwise, load the SourceRange of the conditional expression.
1308 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1309 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1310 E = Ranges.end();
1311 I != E; ++I)
1312 PDiag << *I;
1313 else
1314 PDiag << Second->getSourceRange();
1315
1316 S.Diag(Ranges.begin()->getBegin(), PDiag);
1317 }
1318
1319} // end namespace
1320
John McCalldadc5752010-08-24 06:29:42 +00001321StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001322Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001323 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001324 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001325 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001326 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001327 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001328 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1329 // declare identifiers for objects having storage class 'auto' or
1330 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001331 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1332 DI!=DE; ++DI) {
1333 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001334 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001335 VD = 0;
1336 if (VD == 0)
1337 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1338 // FIXME: mark decl erroneous!
1339 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001340 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001341 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001342
Richard Trieu451a5db2012-04-30 18:01:30 +00001343 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1344
John McCalldadc5752010-08-24 06:29:42 +00001345 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001346 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001347 if (secondVar) {
1348 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001349 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001350 if (SecondResult.isInvalid())
1351 return StmtError();
1352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001354 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355
Anders Carlsson1682af52009-08-01 01:39:59 +00001356 DiagnoseUnusedExprResult(First);
1357 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001358 DiagnoseUnusedExprResult(Body);
1359
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001360 if (isa<NullStmt>(Body))
1361 getCurCompoundScope().setHasEmptyLoopBodies();
1362
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363 return Owned(new (Context) ForStmt(Context, First,
1364 SecondResult.take(), ConditionVar,
1365 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001366 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001367}
1368
John McCall34376a62010-12-04 03:47:34 +00001369/// In an Objective C collection iteration statement:
1370/// for (x in y)
1371/// x can be an arbitrary l-value expression. Bind it up as a
1372/// full-expression.
1373StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001374 // Reduce placeholder expressions here. Note that this rejects the
1375 // use of pseudo-object l-values in this position.
1376 ExprResult result = CheckPlaceholderExpr(E);
1377 if (result.isInvalid()) return StmtError();
1378 E = result.take();
1379
John McCall34376a62010-12-04 03:47:34 +00001380 CheckImplicitConversions(E);
John McCallbc153352012-03-30 05:43:39 +00001381
1382 result = MaybeCreateExprWithCleanups(E);
1383 if (result.isInvalid()) return StmtError();
1384
1385 return Owned(static_cast<Stmt*>(result.take()));
John McCall34376a62010-12-04 03:47:34 +00001386}
1387
John McCall53848232011-07-27 01:07:15 +00001388ExprResult
1389Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1390 assert(collection);
1391
1392 // Bail out early if we've got a type-dependent expression.
1393 if (collection->isTypeDependent()) return Owned(collection);
1394
1395 // Perform normal l-value conversion.
1396 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1397 if (result.isInvalid())
1398 return ExprError();
1399 collection = result.take();
1400
1401 // The operand needs to have object-pointer type.
1402 // TODO: should we do a contextual conversion?
1403 const ObjCObjectPointerType *pointerType =
1404 collection->getType()->getAs<ObjCObjectPointerType>();
1405 if (!pointerType)
1406 return Diag(forLoc, diag::err_collection_expr_type)
1407 << collection->getType() << collection->getSourceRange();
1408
1409 // Check that the operand provides
1410 // - countByEnumeratingWithState:objects:count:
1411 const ObjCObjectType *objectType = pointerType->getObjectType();
1412 ObjCInterfaceDecl *iface = objectType->getInterface();
1413
1414 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001415 // Under ARC, it is an error not to have a forward-declared class.
1416 if (iface &&
1417 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001418 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001419 ? diag::err_arc_collection_forward
1420 : 0,
1421 collection)) {
John McCall53848232011-07-27 01:07:15 +00001422 // Otherwise, if we have any useful type information, check that
1423 // the type declares the appropriate method.
1424 } else if (iface || !objectType->qual_empty()) {
1425 IdentifierInfo *selectorIdents[] = {
1426 &Context.Idents.get("countByEnumeratingWithState"),
1427 &Context.Idents.get("objects"),
1428 &Context.Idents.get("count")
1429 };
1430 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1431
1432 ObjCMethodDecl *method = 0;
1433
1434 // If there's an interface, look in both the public and private APIs.
1435 if (iface) {
1436 method = iface->lookupInstanceMethod(selector);
1437 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1438 }
1439
1440 // Also check protocol qualifiers.
1441 if (!method)
1442 method = LookupMethodInQualifiedType(selector, pointerType,
1443 /*instance*/ true);
1444
1445 // If we didn't find it anywhere, give up.
1446 if (!method) {
1447 Diag(forLoc, diag::warn_collection_expr_type)
1448 << collection->getType() << selector << collection->getSourceRange();
1449 }
1450
1451 // TODO: check for an incompatible signature?
1452 }
1453
1454 // Wrap up any cleanups in the expression.
1455 return Owned(MaybeCreateExprWithCleanups(collection));
1456}
1457
John McCalldadc5752010-08-24 06:29:42 +00001458StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001459Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1460 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001461 Stmt *First, Expr *Second,
1462 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +00001463 if (First) {
1464 QualType FirstType;
1465 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001466 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001467 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1468 diag::err_toomany_element_decls));
1469
John McCall31168b02011-06-15 23:02:42 +00001470 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1471 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001472 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1473 // declare identifiers for objects having storage class 'auto' or
1474 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001475 if (!D->hasLocalStorage())
1476 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001477 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001478 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001479 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001480 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001481 return StmtError(Diag(First->getLocStart(),
1482 diag::err_selector_element_not_lvalue)
1483 << First->getSourceRange());
1484
Mike Stump11289f42009-09-09 15:08:12 +00001485 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001486 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001487 if (!FirstType->isDependentType() &&
1488 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001489 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +00001490 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001491 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001492 }
John McCall53848232011-07-27 01:07:15 +00001493
Ted Kremenek5a201952009-02-07 01:47:29 +00001494 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1495 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001496}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001497
Richard Smith02e85f32011-04-14 22:09:26 +00001498namespace {
1499
1500enum BeginEndFunction {
1501 BEF_begin,
1502 BEF_end
1503};
1504
1505/// Build a variable declaration for a for-range statement.
1506static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1507 QualType Type, const char *Name) {
1508 DeclContext *DC = SemaRef.CurContext;
1509 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1510 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1511 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1512 TInfo, SC_Auto, SC_None);
Richard Smith0c502d22011-04-18 15:49:25 +00001513 Decl->setImplicit();
Richard Smith02e85f32011-04-14 22:09:26 +00001514 return Decl;
1515}
1516
1517/// Finish building a variable declaration for a for-range statement.
1518/// \return true if an error occurs.
1519static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1520 SourceLocation Loc, int diag) {
1521 // Deduce the type for the iterator variable now rather than leaving it to
1522 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1523 TypeSourceInfo *InitTSI = 0;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001524 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redl09edce02012-01-23 22:09:39 +00001525 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1526 Sema::DAR_Failed)
Richard Smith02e85f32011-04-14 22:09:26 +00001527 SemaRef.Diag(Loc, diag) << Init->getType();
1528 if (!InitTSI) {
1529 Decl->setInvalidDecl();
1530 return true;
1531 }
1532 Decl->setTypeSourceInfo(InitTSI);
1533 Decl->setType(InitTSI->getType());
1534
John McCall31168b02011-06-15 23:02:42 +00001535 // In ARC, infer lifetime.
1536 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1537 // we're doing the equivalent of fast iteration.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001538 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001539 SemaRef.inferObjCARCLifetime(Decl))
1540 Decl->setInvalidDecl();
1541
Richard Smith02e85f32011-04-14 22:09:26 +00001542 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1543 /*TypeMayContainAuto=*/false);
1544 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001545 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001546 return false;
1547}
1548
1549/// Produce a note indicating which begin/end function was implicitly called
1550/// by a C++0x for-range statement. This is often not obvious from the code,
1551/// nor from the diagnostics produced when analysing the implicit expressions
1552/// required in a for-range statement.
1553void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1554 BeginEndFunction BEF) {
1555 CallExpr *CE = dyn_cast<CallExpr>(E);
1556 if (!CE)
1557 return;
1558 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1559 if (!D)
1560 return;
1561 SourceLocation Loc = D->getLocation();
1562
1563 std::string Description;
1564 bool IsTemplate = false;
1565 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1566 Description = SemaRef.getTemplateArgumentBindingsText(
1567 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1568 IsTemplate = true;
1569 }
1570
1571 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1572 << BEF << IsTemplate << Description << E->getType();
1573}
1574
1575/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1576/// given LookupResult is non-empty, it is assumed to describe a member which
1577/// will be invoked. Otherwise, the function will be found via argument
1578/// dependent lookup.
1579static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1580 SourceLocation Loc,
1581 VarDecl *Decl,
1582 BeginEndFunction BEF,
1583 const DeclarationNameInfo &NameInfo,
1584 LookupResult &MemberLookup,
1585 Expr *Range) {
1586 ExprResult CallExpr;
1587 if (!MemberLookup.empty()) {
1588 ExprResult MemberRef =
1589 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1590 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001591 /*TemplateKWLoc=*/SourceLocation(),
1592 /*FirstQualifierInScope=*/0,
1593 MemberLookup,
Richard Smith02e85f32011-04-14 22:09:26 +00001594 /*TemplateArgs=*/0);
1595 if (MemberRef.isInvalid())
1596 return ExprError();
1597 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1598 Loc, 0);
1599 if (CallExpr.isInvalid())
1600 return ExprError();
1601 } else {
1602 UnresolvedSet<0> FoundNames;
1603 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1604 // std is an associated namespace.
1605 UnresolvedLookupExpr *Fn =
1606 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1607 NestedNameSpecifierLoc(), NameInfo,
1608 /*NeedsADL=*/true, /*Overloaded=*/false,
1609 FoundNames.begin(), FoundNames.end(),
1610 /*LookInStdNamespace=*/true);
1611 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00001612 0, /*AllowTypoCorrection=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001613 if (CallExpr.isInvalid()) {
1614 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1615 << Range->getType();
1616 return ExprError();
1617 }
1618 }
1619 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1620 diag::err_for_range_iter_deduction_failure)) {
1621 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1622 return ExprError();
1623 }
1624 return CallExpr;
1625}
1626
1627}
1628
1629/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1630///
1631/// C++0x [stmt.ranged]:
1632/// A range-based for statement is equivalent to
1633///
1634/// {
1635/// auto && __range = range-init;
1636/// for ( auto __begin = begin-expr,
1637/// __end = end-expr;
1638/// __begin != __end;
1639/// ++__begin ) {
1640/// for-range-declaration = *__begin;
1641/// statement
1642/// }
1643/// }
1644///
1645/// The body of the loop is not available yet, since it cannot be analysed until
1646/// we have determined the type of the for-range-declaration.
1647StmtResult
1648Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1649 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1650 SourceLocation RParenLoc) {
1651 if (!First || !Range)
1652 return StmtError();
1653
1654 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1655 assert(DS && "first part of for range not a decl stmt");
1656
1657 if (!DS->isSingleDecl()) {
1658 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1659 return StmtError();
1660 }
1661 if (DS->getSingleDecl()->isInvalidDecl())
1662 return StmtError();
1663
1664 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1665 return StmtError();
1666
1667 // Build auto && __range = range-init
1668 SourceLocation RangeLoc = Range->getLocStart();
1669 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1670 Context.getAutoRRefDeductType(),
1671 "__range");
1672 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1673 diag::err_for_range_deduction_failure))
1674 return StmtError();
1675
1676 // Claim the type doesn't contain auto: we've already done the checking.
1677 DeclGroupPtrTy RangeGroup =
1678 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1679 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1680 if (RangeDecl.isInvalid())
1681 return StmtError();
1682
1683 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1684 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1685 RParenLoc);
1686}
1687
1688/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1689StmtResult
1690Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1691 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1692 Expr *Inc, Stmt *LoopVarDecl,
1693 SourceLocation RParenLoc) {
1694 Scope *S = getCurScope();
1695
1696 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1697 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1698 QualType RangeVarType = RangeVar->getType();
1699
1700 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1701 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1702
1703 StmtResult BeginEndDecl = BeginEnd;
1704 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1705
1706 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1707 SourceLocation RangeLoc = RangeVar->getLocation();
1708
Ted Kremenekbed648e2011-10-10 22:36:28 +00001709 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1710
1711 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1712 VK_LValue, ColonLoc);
1713 if (BeginRangeRef.isInvalid())
1714 return StmtError();
1715
1716 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1717 VK_LValue, ColonLoc);
1718 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00001719 return StmtError();
1720
1721 QualType AutoType = Context.getAutoDeductType();
1722 Expr *Range = RangeVar->getInit();
1723 if (!Range)
1724 return StmtError();
1725 QualType RangeType = Range->getType();
1726
1727 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001728 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00001729 return StmtError();
1730
1731 // Build auto __begin = begin-expr, __end = end-expr.
1732 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1733 "__begin");
1734 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1735 "__end");
1736
1737 // Build begin-expr and end-expr and attach to __begin and __end variables.
1738 ExprResult BeginExpr, EndExpr;
1739 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1740 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1741 // __range + __bound, respectively, where __bound is the array bound. If
1742 // _RangeT is an array of unknown size or an array of incomplete type,
1743 // the program is ill-formed;
1744
1745 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001746 BeginExpr = BeginRangeRef;
1747 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001748 diag::err_for_range_iter_deduction_failure)) {
1749 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1750 return StmtError();
1751 }
1752
1753 // Find the array bound.
1754 ExprResult BoundExpr;
1755 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1756 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001757 Context.getPointerDiffType(),
1758 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001759 else if (const VariableArrayType *VAT =
1760 dyn_cast<VariableArrayType>(UnqAT))
1761 BoundExpr = VAT->getSizeExpr();
1762 else {
1763 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1764 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00001765 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00001766 }
1767
1768 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001769 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00001770 BoundExpr.get());
1771 if (EndExpr.isInvalid())
1772 return StmtError();
1773 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1774 diag::err_for_range_iter_deduction_failure)) {
1775 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1776 return StmtError();
1777 }
1778 } else {
1779 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1780 ColonLoc);
1781 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1782 ColonLoc);
1783
1784 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1785 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1786
1787 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1788 // - if _RangeT is a class type, the unqualified-ids begin and end are
1789 // looked up in the scope of class _RangeT as if by class member access
1790 // lookup (3.4.5), and if either (or both) finds at least one
1791 // declaration, begin-expr and end-expr are __range.begin() and
1792 // __range.end(), respectively;
1793 LookupQualifiedName(BeginMemberLookup, D);
1794 LookupQualifiedName(EndMemberLookup, D);
1795
1796 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1797 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1798 << RangeType << BeginMemberLookup.empty();
1799 return StmtError();
1800 }
1801 } else {
1802 // - otherwise, begin-expr and end-expr are begin(__range) and
1803 // end(__range), respectively, where begin and end are looked up with
1804 // argument-dependent lookup (3.4.2). For the purposes of this name
1805 // lookup, namespace std is an associated namespace.
1806 }
1807
1808 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1809 BEF_begin, BeginNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001810 BeginMemberLookup,
1811 BeginRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001812 if (BeginExpr.isInvalid())
1813 return StmtError();
1814
1815 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1816 BEF_end, EndNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001817 EndMemberLookup, EndRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001818 if (EndExpr.isInvalid())
1819 return StmtError();
1820 }
1821
1822 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1823 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1824 if (!Context.hasSameType(BeginType, EndType)) {
1825 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1826 << BeginType << EndType;
1827 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1828 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1829 }
1830
1831 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1832 // Claim the type doesn't contain auto: we've already done the checking.
1833 DeclGroupPtrTy BeginEndGroup =
1834 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1835 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1836
Ted Kremenekbed648e2011-10-10 22:36:28 +00001837 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1838 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00001839 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001840 if (BeginRef.isInvalid())
1841 return StmtError();
1842
Richard Smith02e85f32011-04-14 22:09:26 +00001843 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1844 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001845 if (EndRef.isInvalid())
1846 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00001847
1848 // Build and check __begin != __end expression.
1849 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1850 BeginRef.get(), EndRef.get());
1851 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1852 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1853 if (NotEqExpr.isInvalid()) {
1854 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1855 if (!Context.hasSameType(BeginType, EndType))
1856 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1857 return StmtError();
1858 }
1859
1860 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001861 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1862 VK_LValue, ColonLoc);
1863 if (BeginRef.isInvalid())
1864 return StmtError();
1865
Richard Smith02e85f32011-04-14 22:09:26 +00001866 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1867 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1868 if (IncrExpr.isInvalid()) {
1869 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1870 return StmtError();
1871 }
1872
1873 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001874 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1875 VK_LValue, ColonLoc);
1876 if (BeginRef.isInvalid())
1877 return StmtError();
1878
Richard Smith02e85f32011-04-14 22:09:26 +00001879 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1880 if (DerefExpr.isInvalid()) {
1881 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1882 return StmtError();
1883 }
1884
1885 // Attach *__begin as initializer for VD.
1886 if (!LoopVar->isInvalidDecl()) {
1887 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1888 /*TypeMayContainAuto=*/true);
1889 if (LoopVar->isInvalidDecl())
1890 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1891 }
Richard Smithf9603352011-06-21 23:07:19 +00001892 } else {
1893 // The range is implicitly used as a placeholder when it is dependent.
1894 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00001895 }
1896
1897 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1898 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1899 NotEqExpr.take(), IncrExpr.take(),
1900 LoopVarDS, /*Body=*/0, ForLoc,
1901 ColonLoc, RParenLoc));
1902}
1903
1904/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1905/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1906/// body cannot be performed until after the type of the range variable is
1907/// determined.
1908StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1909 if (!S || !B)
1910 return StmtError();
1911
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001912 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1913 ForStmt->setBody(B);
1914
1915 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1916 diag::warn_empty_range_based_for_body);
1917
Richard Smith02e85f32011-04-14 22:09:26 +00001918 return S;
1919}
1920
Chris Lattnercab02a62011-02-17 20:34:02 +00001921StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1922 SourceLocation LabelLoc,
1923 LabelDecl *TheDecl) {
1924 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001925 TheDecl->setUsed();
1926 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001927}
Chris Lattner1c310502007-05-31 06:00:00 +00001928
John McCalldadc5752010-08-24 06:29:42 +00001929StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001930Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001931 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001932 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001933 if (!E->isTypeDependent()) {
1934 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001935 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001936 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001937 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001938 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1939 if (ExprRes.isInvalid())
1940 return StmtError();
1941 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001942 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001943 return StmtError();
Eli Friedman9ccdb1d2012-01-31 22:47:07 +00001944 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001945 }
John McCalla95172b2010-08-01 00:26:45 +00001946
John McCallaab3e412010-08-25 08:40:02 +00001947 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001948
Douglas Gregor30776d42009-05-16 00:20:29 +00001949 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001950}
1951
John McCalldadc5752010-08-24 06:29:42 +00001952StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001953Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001954 Scope *S = CurScope->getContinueParent();
1955 if (!S) {
1956 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001957 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001958 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001959
Ted Kremenek5a201952009-02-07 01:47:29 +00001960 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001961}
1962
John McCalldadc5752010-08-24 06:29:42 +00001963StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001964Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001965 Scope *S = CurScope->getBreakParent();
1966 if (!S) {
1967 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001968 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001969 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001970
Ted Kremenek5a201952009-02-07 01:47:29 +00001971 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001972}
1973
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001974/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001975/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001976///
Douglas Gregor5d369002011-01-21 18:05:27 +00001977/// \param ReturnType If we're determining the copy elision candidate for
1978/// a return statement, this is the return type of the function. If we're
1979/// determining the copy elision candidate for a throw expression, this will
1980/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001981///
Douglas Gregor5d369002011-01-21 18:05:27 +00001982/// \param E The expression being returned from the function or block, or
1983/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001984///
Douglas Gregor86394412011-05-20 15:00:53 +00001985/// \param AllowFunctionParameter Whether we allow function parameters to
1986/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1987/// we re-use this logic to determine whether we should try to move as part of
1988/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001989///
1990/// \returns The NRVO candidate variable, if the return statement may use the
1991/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001992const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1993 Expr *E,
1994 bool AllowFunctionParameter) {
1995 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001996 // - in a return statement in a function with ...
1997 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001998 if (!ReturnType.isNull()) {
1999 if (!ReturnType->isRecordType())
2000 return 0;
2001 // ... the same cv-unqualified type as the function return type ...
2002 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2003 return 0;
2004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
2006 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00002007 // (other than a function or catch-clause parameter)) ...
2008 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002009 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002010 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002011 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2012 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002013 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014
John McCall03318c12011-11-11 03:57:31 +00002015 // ...object (other than a function or catch-clause parameter)...
2016 if (VD->getKind() != Decl::Var &&
2017 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2018 return 0;
2019 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020
John McCall03318c12011-11-11 03:57:31 +00002021 // ...automatic...
2022 if (!VD->hasLocalStorage()) return 0;
2023
2024 // ...non-volatile...
2025 if (VD->getType().isVolatileQualified()) return 0;
2026 if (VD->getType()->isReferenceType()) return 0;
2027
2028 // __block variables can't be allocated in a way that permits NRVO.
2029 if (VD->hasAttr<BlocksAttr>()) return 0;
2030
2031 // Variables with higher required alignment than their type's ABI
2032 // alignment cannot use NRVO.
2033 if (VD->hasAttr<AlignedAttr>() &&
2034 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2035 return 0;
2036
2037 return VD;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002038}
2039
Douglas Gregor626fbed2011-01-21 21:08:57 +00002040/// \brief Perform the initialization of a potentially-movable value, which
2041/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002042///
2043/// This routine implements C++0x [class.copy]p33, which attempts to treat
2044/// returned lvalues as rvalues in certain cases (to prefer move construction),
2045/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002047Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2048 const VarDecl *NRVOCandidate,
2049 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002050 Expr *Value,
2051 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002052 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002053 // When the criteria for elision of a copy operation are met or would
2054 // be met save for the fact that the source object is a function
2055 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002056 // overload resolution to select the constructor for the copy is first
2057 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002058 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002059 if (AllowNRVO &&
2060 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002061 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002062 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063
Douglas Gregorf282a762011-01-21 19:38:21 +00002064 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002066 = InitializationKind::CreateCopy(Value->getLocStart(),
2067 Value->getLocStart());
2068 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
2070 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002071 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002072 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002073 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002074 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002075 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2076 StepEnd = Seq.step_end();
2077 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002078 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002079 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080
2081 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002082 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083
Douglas Gregorf282a762011-01-21 19:38:21 +00002084 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002085 = Constructor->getParamDecl(0)->getType()
2086 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087
Douglas Gregorf282a762011-01-21 19:38:21 +00002088 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002090 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2091 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002092 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093
Douglas Gregorf282a762011-01-21 19:38:21 +00002094 // Promote "AsRvalue" to the heap, since we now need this
2095 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002096 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002097 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Douglas Gregorf282a762011-01-21 19:38:21 +00002099 // Complete type-checking the initialization of the return type
2100 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002101 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00002102 }
2103 }
2104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105
Douglas Gregorf282a762011-01-21 19:38:21 +00002106 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002108 // (again) now with the return value expression as written.
2109 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002110 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111
Douglas Gregorf282a762011-01-21 19:38:21 +00002112 return Res;
2113}
2114
Eli Friedman34b49062012-01-26 03:00:14 +00002115/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2116/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002117///
John McCalldadc5752010-08-24 06:29:42 +00002118StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002119Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2120 // If this is the first return we've seen, infer the return type.
2121 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2122 // rules which allows multiple return statements.
2123 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2124 if (CurCap->HasImplicitReturnType) {
2125 QualType ReturnT;
Douglas Gregor940a5502012-02-09 18:40:39 +00002126 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002127 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2128 if (Result.isInvalid())
2129 return StmtError();
2130 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002131
Eli Friedman34b49062012-01-26 03:00:14 +00002132 if (!RetValExp->isTypeDependent())
2133 ReturnT = RetValExp->getType();
2134 else
2135 ReturnT = Context.DependentTy;
Douglas Gregor940a5502012-02-09 18:40:39 +00002136 } else {
2137 if (RetValExp) {
2138 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2139 // initializer list, because it is not an expression (even
2140 // though we represent it as one). We still deduce 'void'.
2141 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2142 << RetValExp->getSourceRange();
2143 }
2144
Eli Friedman34b49062012-01-26 03:00:14 +00002145 ReturnT = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002146 }
Eli Friedman34b49062012-01-26 03:00:14 +00002147 // We require the return types to strictly match here.
2148 if (!CurCap->ReturnType.isNull() &&
2149 !CurCap->ReturnType->isDependentType() &&
2150 !ReturnT->isDependentType() &&
2151 !Context.hasSameType(ReturnT, CurCap->ReturnType)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002152 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Douglas Gregorb9e38f12012-02-15 15:57:22 +00002153 << ReturnT << CurCap->ReturnType
Douglas Gregor85dae8922012-02-15 15:59:09 +00002154 << (getCurLambda() != 0);
Eli Friedman34b49062012-01-26 03:00:14 +00002155 return StmtError();
2156 }
2157 CurCap->ReturnType = ReturnT;
Steve Naroffc540d662008-09-03 18:15:37 +00002158 }
Eli Friedman34b49062012-01-26 03:00:14 +00002159 QualType FnRetType = CurCap->ReturnType;
2160 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002161
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002162 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002163 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2164 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2165 return StmtError();
2166 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002167 } else {
2168 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2169 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2170 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2171 return StmtError();
2172 }
2173 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002174
Steve Naroffc540d662008-09-03 18:15:37 +00002175 // Otherwise, verify that this result type matches the previous one. We are
2176 // pickier with blocks than for normal functions because we don't have GCC
2177 // compatibility to worry about here.
John McCall75f92b52011-08-17 21:34:14 +00002178 const VarDecl *NRVOCandidate = 0;
John McCall5500ef22011-08-17 22:09:46 +00002179 if (FnRetType->isDependentType()) {
2180 // Delay processing for now. TODO: there are lots of dependent
2181 // types we can conclusively prove aren't void.
2182 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002183 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002184 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002185 (RetValExp->isTypeDependent() ||
2186 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002187 if (!getLangOpts().CPlusPlus &&
2188 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002189 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002190 else {
2191 Diag(ReturnLoc, diag::err_return_block_has_expr);
2192 RetValExp = 0;
2193 }
Steve Naroffc540d662008-09-03 18:15:37 +00002194 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002195 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002196 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2197 } else if (!RetValExp->isTypeDependent()) {
2198 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002199
John McCall5500ef22011-08-17 22:09:46 +00002200 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2201 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2202 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002203
John McCall5500ef22011-08-17 22:09:46 +00002204 // In C++ the return statement is handled via a copy initialization.
2205 // the C version of which boils down to CheckSingleAssignmentConstraints.
2206 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2207 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2208 FnRetType,
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00002209 NRVOCandidate != 0);
John McCall5500ef22011-08-17 22:09:46 +00002210 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2211 FnRetType, RetValExp);
2212 if (Res.isInvalid()) {
2213 // FIXME: Cleanup temporaries here, anyway?
2214 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002215 }
John McCall5500ef22011-08-17 22:09:46 +00002216 RetValExp = Res.take();
2217 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +00002218 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002219
John McCall75f92b52011-08-17 21:34:14 +00002220 if (RetValExp) {
2221 CheckImplicitConversions(RetValExp, ReturnLoc);
2222 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2223 }
John McCall5500ef22011-08-17 22:09:46 +00002224 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2225 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002226
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002227 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002228 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002229 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002230 !CurContext->isDependentContext())
2231 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002233 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00002234}
Chris Lattneraf8d5812006-11-10 05:07:45 +00002235
John McCalldadc5752010-08-24 06:29:42 +00002236StmtResult
John McCallb268a282010-08-23 23:25:46 +00002237Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002238 // Check for unexpanded parameter packs.
2239 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2240 return StmtError();
2241
Eli Friedman34b49062012-01-26 03:00:14 +00002242 if (isa<CapturingScopeInfo>(getCurFunction()))
2243 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00002244
Chris Lattner79413952008-12-04 23:50:19 +00002245 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002246 QualType RelatedRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002247 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00002248 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00002249 if (FD->hasAttr<NoReturnAttr>() ||
2250 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00002251 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002252 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002253 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman410fc7a2012-03-30 01:13:43 +00002254 FnRetType = MD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00002255 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2256 // In the implementation of a method with a related return type, the
2257 // type used to type-check the validity of return statements within the
2258 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002259 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2260 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002261 }
2262 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002263 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002264
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002265 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002266 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002267 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002268 if (isa<InitListExpr>(RetValExp)) {
2269 // We simply never allow init lists as the return value of void
2270 // functions. This is compatible because this was never allowed before,
2271 // so there's no legacy code to deal with.
2272 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2273 int FunctionKind = 0;
2274 if (isa<ObjCMethodDecl>(CurDecl))
2275 FunctionKind = 1;
2276 else if (isa<CXXConstructorDecl>(CurDecl))
2277 FunctionKind = 2;
2278 else if (isa<CXXDestructorDecl>(CurDecl))
2279 FunctionKind = 3;
2280
2281 Diag(ReturnLoc, diag::err_return_init_list)
2282 << CurDecl->getDeclName() << FunctionKind
2283 << RetValExp->getSourceRange();
2284
2285 // Drop the expression.
2286 RetValExp = 0;
2287 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002288 // C99 6.8.6.4p1 (ext_ since GCC warns)
2289 unsigned D = diag::ext_return_has_expr;
2290 if (RetValExp->getType()->isVoidType())
2291 D = diag::ext_return_has_void_expr;
2292 else {
2293 ExprResult Result = Owned(RetValExp);
2294 Result = IgnoredValueConversions(Result.take());
2295 if (Result.isInvalid())
2296 return StmtError();
2297 RetValExp = Result.take();
2298 RetValExp = ImpCastExprToType(RetValExp,
2299 Context.VoidTy, CK_ToVoid).take();
2300 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002301
Nick Lewycky1be750a2011-06-01 07:44:31 +00002302 // return (some void expression); is legal in C++.
2303 if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002304 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002305 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002306
2307 int FunctionKind = 0;
2308 if (isa<ObjCMethodDecl>(CurDecl))
2309 FunctionKind = 1;
2310 else if (isa<CXXConstructorDecl>(CurDecl))
2311 FunctionKind = 2;
2312 else if (isa<CXXDestructorDecl>(CurDecl))
2313 FunctionKind = 3;
2314
Nick Lewycky1be750a2011-06-01 07:44:31 +00002315 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002316 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002317 << RetValExp->getSourceRange();
2318 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002319 }
Mike Stump11289f42009-09-09 15:08:12 +00002320
Sebastian Redleef474c2012-02-22 10:50:08 +00002321 if (RetValExp) {
2322 CheckImplicitConversions(RetValExp, ReturnLoc);
2323 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2324 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002326
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002327 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2328 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002329 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2330 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002331 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002332
2333 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002334 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002335 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002336 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002337 Result = new (Context) ReturnStmt(ReturnLoc);
2338 } else {
2339 const VarDecl *NRVOCandidate = 0;
2340 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2341 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002342
Eli Friedman410fc7a2012-03-30 01:13:43 +00002343 if (!RelatedRetType.isNull()) {
2344 // If we have a related result type, perform an extra conversion here.
2345 // FIXME: The diagnostics here don't really describe what is happening.
2346 InitializedEntity Entity =
2347 InitializedEntity::InitializeTemporary(RelatedRetType);
2348
2349 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2350 RetValExp);
2351 if (Res.isInvalid()) {
2352 // FIXME: Cleanup temporaries here, anyway?
2353 return StmtError();
2354 }
2355 RetValExp = Res.takeAs<Expr>();
2356 }
2357
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002358 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2359 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2360 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002361
John McCallfa272342011-06-16 23:24:51 +00002362 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002363 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00002364 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002366 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00002367 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002369 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002370 if (Res.isInvalid()) {
2371 // FIXME: Cleanup temporaries here, anyway?
2372 return StmtError();
2373 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002374
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002375 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002376 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002377 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002379
John McCallacf0ee52010-10-08 02:01:28 +00002380 if (RetValExp) {
2381 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00002382 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00002383 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002384 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00002385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386
2387 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002388 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002389 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002390 !CurContext->isDependentContext())
2391 FunctionScopes.back()->Returns.push_back(Result);
John McCall31168b02011-06-15 23:02:42 +00002392
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002393 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002394}
2395
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002396/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2397/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2398/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2399/// provide a strong guidance to not use it.
2400///
2401/// This method checks to see if the argument is an acceptable l-value and
2402/// returns false if it is a case we can handle.
2403static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00002404 // Type dependent expressions will be checked during instantiation.
2405 if (E->isTypeDependent())
2406 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002407
John McCall086a4642010-11-24 05:12:34 +00002408 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002409 return false; // Cool, this is an lvalue.
2410
2411 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2412 // are supposed to allow.
2413 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00002414 if (E != E2 && E2->isLValue()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002415 if (!S.getLangOpts().HeinousExtensions)
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002416 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2417 << E->getSourceRange();
2418 else
2419 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2420 << E->getSourceRange();
2421 // Accept, even if we emitted an error diagnostic.
2422 return false;
2423 }
2424
2425 // None of the above, just randomly invalid non-lvalue.
2426 return true;
2427}
2428
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002429/// isOperandMentioned - Return true if the specified operand # is mentioned
2430/// anywhere in the decomposed asm string.
2431static bool isOperandMentioned(unsigned OpNo,
Chris Lattner54b16772011-07-23 17:14:25 +00002432 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002433 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2434 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2435 if (!Piece.isOperand()) continue;
2436
2437 // If this is a reference to the input and if the input was the smaller
2438 // one, then we have to reject this asm.
2439 if (Piece.getOperandNo() == OpNo)
2440 return true;
2441 }
2442
2443 return false;
2444}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002445
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002446StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2447 bool IsVolatile, unsigned NumOutputs,
2448 unsigned NumInputs, IdentifierInfo **Names,
2449 MultiExprArg constraints, MultiExprArg exprs,
2450 Expr *asmString, MultiExprArg clobbers,
2451 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002452 unsigned NumClobbers = clobbers.size();
2453 StringLiteral **Constraints =
2454 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00002455 Expr **Exprs = exprs.get();
2456 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00002457 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2458
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002459 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00002460
Chris Lattner496acc12008-08-18 19:55:17 +00002461 // The parser verifies that there is a string literal here.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002462 if (!AsmString->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002463 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2464 << AsmString->getSourceRange());
2465
Chris Lattner496acc12008-08-18 19:55:17 +00002466 for (unsigned i = 0; i != NumOutputs; i++) {
2467 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002468 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002469 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2470 << Literal->getSourceRange());
2471
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002472 StringRef OutputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002473 if (Names[i])
2474 OutputName = Names[i]->getName();
2475
2476 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002477 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002478 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002479 diag::err_asm_invalid_output_constraint)
2480 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00002481
Anders Carlssonf511f642007-11-27 04:11:28 +00002482 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00002483 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002484 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00002485 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002486 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00002487 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002488 }
Mike Stump11289f42009-09-09 15:08:12 +00002489
Chris Lattnerd9725f72009-04-26 07:16:29 +00002490 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002491 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002492
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002493 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner34b51e82009-05-03 05:55:43 +00002494
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002495 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00002496 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002497 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002498 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2499 << Literal->getSourceRange());
2500
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002501 StringRef InputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002502 if (Names[i])
2503 InputName = Names[i]->getName();
2504
2505 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002506 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00002507 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002508 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002509 diag::err_asm_invalid_input_constraint)
2510 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00002511 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002512
Eli Friedman47e78572009-05-03 07:49:42 +00002513 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00002514
Anders Carlsson224fca82009-01-20 20:49:22 +00002515 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00002516 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002517 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00002518 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002519 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002520 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002521 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002522 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002523
Chris Lattnerd9725f72009-04-26 07:16:29 +00002524 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00002525 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00002526 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002527 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00002528 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002529 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00002530 }
Anders Carlsson224fca82009-01-20 20:49:22 +00002531 }
Mike Stump11289f42009-09-09 15:08:12 +00002532
John Wiegley01296292011-04-08 18:41:53 +00002533 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2534 if (Result.isInvalid())
2535 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002536
John Wiegley01296292011-04-08 18:41:53 +00002537 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00002538 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002539 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002540
Anders Carlsson290aa852007-11-25 00:25:21 +00002541 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00002542 for (unsigned i = 0; i != NumClobbers; i++) {
2543 StringLiteral *Literal = Clobbers[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002544 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002545 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2546 << Literal->getSourceRange());
2547
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002548 StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00002549
Douglas Gregore8bbc122011-09-02 00:18:52 +00002550 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002551 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00002552 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00002553 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002554
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002555 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2557 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00002558 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002559 // Validate the asm string, ensuring it makes sense given the operands we
2560 // have.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002561 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002562 unsigned DiagOffs;
2563 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00002564 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2565 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002566 return StmtError();
2567 }
Mike Stump11289f42009-09-09 15:08:12 +00002568
Chris Lattner34b51e82009-05-03 05:55:43 +00002569 // Validate tied input operands for type mismatches.
2570 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2571 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00002572
Chris Lattner34b51e82009-05-03 05:55:43 +00002573 // If this is a tied constraint, verify that the output and input have
2574 // either exactly the same type, or that they are int/ptr operands with the
2575 // same size (int/long, int*/long, are ok etc).
2576 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00002577
Chris Lattner34b51e82009-05-03 05:55:43 +00002578 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00002579 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00002580 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00002581 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedman8eac6c22011-09-14 19:20:00 +00002582
2583 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2584 continue;
2585
Chris Lattner2c295cf2009-05-03 05:59:17 +00002586 QualType InTy = InputExpr->getType();
2587 QualType OutTy = OutputExpr->getType();
2588 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00002589 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00002590
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002591 // Decide if the input and output are in the same domain (integer/ptr or
2592 // floating point.
2593 enum AsmDomain {
2594 AD_Int, AD_FP, AD_Other
2595 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002596
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002597 if (InTy->isIntegerType() || InTy->isPointerType())
2598 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002599 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002600 InputDomain = AD_FP;
2601 else
2602 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00002603
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002604 if (OutTy->isIntegerType() || OutTy->isPointerType())
2605 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002606 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002607 OutputDomain = AD_FP;
2608 else
2609 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002610
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002611 // They are ok if they are the same size and in the same domain. This
2612 // allows tying things like:
2613 // void* to int*
2614 // void* to int if they are the same size.
2615 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002617 uint64_t OutSize = Context.getTypeSize(OutTy);
2618 uint64_t InSize = Context.getTypeSize(InTy);
2619 if (OutSize == InSize && InputDomain == OutputDomain &&
2620 InputDomain != AD_Other)
2621 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002622
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002623 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00002624 // then we can promote the smaller one to a larger input and the asm string
2625 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002626 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002627
2628 // If this is a reference to the input and if the input was the smaller
2629 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00002630 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002631 // This is a use in the asm string of the smaller operand. Since we
2632 // codegen this by promoting to a wider value, the asm will get printed
2633 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00002634 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002635 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002636 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002637 // If this is a reference to the output, and if the output is the larger
2638 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002639 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002640 }
Mike Stump11289f42009-09-09 15:08:12 +00002641
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002642 // If the smaller value wasn't mentioned in the asm string, and if the
2643 // output was a register, just extend the shorter one to the size of the
2644 // larger one.
2645 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2646 OutputConstraintInfos[TiedTo].allowsRegister())
2647 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00002648
Chris Lattner93ede022011-02-21 22:09:29 +00002649 // Either both of the operands were mentioned or the smaller one was
2650 // mentioned. One more special case that we'll allow: if the tied input is
2651 // integer, unmentioned, and is a constant, then we'll allow truncating it
2652 // down to the size of the destination.
2653 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2654 !isOperandMentioned(InputOpNo, Pieces) &&
2655 InputExpr->isEvaluatable(Context)) {
John McCalldfbf9342011-05-10 23:39:47 +00002656 CastKind castKind =
2657 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2658 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002659 Exprs[InputOpNo] = InputExpr;
2660 NS->setInputExpr(i, InputExpr);
2661 continue;
2662 }
2663
Chris Lattner28b05c82009-05-03 06:50:40 +00002664 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002665 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002666 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002667 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002668 return StmtError();
2669 }
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002671 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002672}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002673
John McCalldadc5752010-08-24 06:29:42 +00002674StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002675Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002676 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002677 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002678 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002679 if (Var && Var->isInvalidDecl())
2680 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681
John McCallb268a282010-08-23 23:25:46 +00002682 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002683}
2684
John McCalldadc5752010-08-24 06:29:42 +00002685StmtResult
John McCallb268a282010-08-23 23:25:46 +00002686Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2687 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002688}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002689
John McCalldadc5752010-08-24 06:29:42 +00002690StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002691Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002692 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002693 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002694 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2695
John McCallaab3e412010-08-25 08:40:02 +00002696 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002697 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002698 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2699 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002700 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002701 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002702}
2703
John McCall0bd3e402012-05-08 21:41:25 +00002704StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002705 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00002706 ExprResult Result = DefaultLvalueConversion(Throw);
2707 if (Result.isInvalid())
2708 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002709
John McCall0bd3e402012-05-08 21:41:25 +00002710 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregor2900c162010-04-22 21:44:01 +00002711 QualType ThrowType = Throw->getType();
2712 // Make sure the expression type is an ObjC pointer or "void *".
2713 if (!ThrowType->isDependentType() &&
2714 !ThrowType->isObjCObjectPointerType()) {
2715 const PointerType *PT = ThrowType->getAs<PointerType>();
2716 if (!PT || !PT->getPointeeType()->isVoidType())
2717 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2718 << Throw->getType() << Throw->getSourceRange());
2719 }
2720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
John McCallb268a282010-08-23 23:25:46 +00002722 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002723}
2724
John McCalldadc5752010-08-24 06:29:42 +00002725StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002727 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002728 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002729 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2730
John McCallb268a282010-08-23 23:25:46 +00002731 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002732 // @throw without an expression designates a rethrow (which much occur
2733 // in the context of an @catch clause).
2734 Scope *AtCatchParent = CurScope;
2735 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2736 AtCatchParent = AtCatchParent->getParent();
2737 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002738 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739 }
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002740
John McCallb268a282010-08-23 23:25:46 +00002741 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002742}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002743
John McCalld9bb7432011-07-27 21:50:02 +00002744ExprResult
2745Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2746 ExprResult result = DefaultLvalueConversion(operand);
2747 if (result.isInvalid())
2748 return ExprError();
2749 operand = result.take();
2750
2751 // Make sure the expression type is an ObjC pointer or "void *".
2752 QualType type = operand->getType();
2753 if (!type->isDependentType() &&
2754 !type->isObjCObjectPointerType()) {
2755 const PointerType *pointerType = type->getAs<PointerType>();
2756 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2757 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2758 << type << operand->getSourceRange();
2759 }
2760
2761 // The operand to @synchronized is a full-expression.
2762 return MaybeCreateExprWithCleanups(operand);
2763}
2764
John McCalldadc5752010-08-24 06:29:42 +00002765StmtResult
John McCallb268a282010-08-23 23:25:46 +00002766Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2767 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00002768 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00002769 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00002770 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002771}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002772
2773/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2774/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002775StmtResult
John McCall48871652010-08-21 09:40:31 +00002776Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002777 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002778 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002779 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002780 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002781 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002782}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002783
John McCall31168b02011-06-15 23:02:42 +00002784StmtResult
2785Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2786 getCurFunction()->setHasBranchProtectedScope();
2787 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2788}
2789
Dan Gohman28ade552010-07-26 21:25:24 +00002790namespace {
2791
Sebastian Redl63c4da02009-07-29 17:15:45 +00002792class TypeWithHandler {
2793 QualType t;
2794 CXXCatchStmt *stmt;
2795public:
2796 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2797 : t(type), stmt(statement) {}
2798
John McCall8ccfcb52009-09-24 19:53:00 +00002799 // An arbitrary order is fine as long as it places identical
2800 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002801 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002802 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002803 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002804 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002805 return false;
2806 else
2807 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Sebastian Redl63c4da02009-07-29 17:15:45 +00002810 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002811 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002812 }
Mike Stump11289f42009-09-09 15:08:12 +00002813
Sebastian Redl63c4da02009-07-29 17:15:45 +00002814 CXXCatchStmt *getCatchStmt() const { return stmt; }
2815 SourceLocation getTypeSpecStartLoc() const {
2816 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2817 }
2818};
2819
Dan Gohman28ade552010-07-26 21:25:24 +00002820}
2821
Sebastian Redl9b244a82008-12-22 21:35:02 +00002822/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2823/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002824StmtResult
John McCallb268a282010-08-23 23:25:46 +00002825Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002826 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002827 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002828 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002829 !getSourceManager().isInSystemHeader(TryLoc))
2830 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002831
Sebastian Redl9b244a82008-12-22 21:35:02 +00002832 unsigned NumHandlers = RawHandlers.size();
2833 assert(NumHandlers > 0 &&
2834 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00002835 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002836
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002837 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002838
2839 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002840 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002841 if (!Handler->getExceptionDecl()) {
2842 if (i < NumHandlers - 1)
2843 return StmtError(Diag(Handler->getLocStart(),
2844 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002845
Sebastian Redl63c4da02009-07-29 17:15:45 +00002846 continue;
2847 }
Mike Stump11289f42009-09-09 15:08:12 +00002848
Sebastian Redl63c4da02009-07-29 17:15:45 +00002849 const QualType CaughtType = Handler->getCaughtType();
2850 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2851 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002852 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002853
2854 // Detect handlers for the same type as an earlier one.
2855 if (NumHandlers > 1) {
2856 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002857
Sebastian Redl63c4da02009-07-29 17:15:45 +00002858 TypeWithHandler prev = TypesWithHandlers[0];
2859 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2860 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002861
Sebastian Redl63c4da02009-07-29 17:15:45 +00002862 if (curr == prev) {
2863 Diag(curr.getTypeSpecStartLoc(),
2864 diag::warn_exception_caught_by_earlier_handler)
2865 << curr.getCatchStmt()->getCaughtType().getAsString();
2866 Diag(prev.getTypeSpecStartLoc(),
2867 diag::note_previous_exception_handler)
2868 << prev.getCatchStmt()->getCaughtType().getAsString();
2869 }
Mike Stump11289f42009-09-09 15:08:12 +00002870
Sebastian Redl63c4da02009-07-29 17:15:45 +00002871 prev = curr;
2872 }
2873 }
Mike Stump11289f42009-09-09 15:08:12 +00002874
John McCallaab3e412010-08-25 08:40:02 +00002875 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002876
Sebastian Redl9b244a82008-12-22 21:35:02 +00002877 // FIXME: We should detect handlers that cannot catch anything because an
2878 // earlier handler catches a superclass. Need to find a method that is not
2879 // quadratic for this.
2880 // Neither of these are explicitly forbidden, but every compiler detects them
2881 // and warns.
2882
John McCallb268a282010-08-23 23:25:46 +00002883 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002884 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002885}
John Wiegley1c0675e2011-04-28 01:08:34 +00002886
2887StmtResult
2888Sema::ActOnSEHTryBlock(bool IsCXXTry,
2889 SourceLocation TryLoc,
2890 Stmt *TryBlock,
2891 Stmt *Handler) {
2892 assert(TryBlock && Handler);
2893
2894 getCurFunction()->setHasBranchProtectedScope();
2895
2896 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2897}
2898
2899StmtResult
2900Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2901 Expr *FilterExpr,
2902 Stmt *Block) {
2903 assert(FilterExpr && Block);
2904
2905 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00002906 return StmtError(Diag(FilterExpr->getExprLoc(),
2907 diag::err_filter_expression_integral)
2908 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00002909 }
2910
2911 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2912}
2913
2914StmtResult
2915Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2916 Stmt *Block) {
2917 assert(Block);
2918 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2919}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002920
2921StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2922 bool IsIfExists,
2923 NestedNameSpecifierLoc QualifierLoc,
2924 DeclarationNameInfo NameInfo,
2925 Stmt *Nested)
2926{
2927 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2928 QualifierLoc, NameInfo,
2929 cast<CompoundStmt>(Nested));
2930}
2931
2932
2933StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2934 bool IsIfExists,
2935 CXXScopeSpec &SS,
2936 UnqualifiedId &Name,
2937 Stmt *Nested) {
2938 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2939 SS.getWithLocInContext(Context),
2940 GetNameFromUnqualifiedId(Name),
2941 Nested);
2942}