blob: 2d03ab99efcac2d34f7d057f2f73b0c4ef135c8f [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"
Sebastian Redl63c4da02009-07-29 17:15:45 +000033#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000034using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000035using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000036
John McCalldadc5752010-08-24 06:29:42 +000037StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000038 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000039 if (!E) // FIXME: FullExprArg has no error state?
40 return StmtError();
41
Chris Lattner903eb512008-07-25 23:18:17 +000042 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
43 // void expression for its side effects. Conversion to void allows any
44 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000045
Chris Lattner903eb512008-07-25 23:18:17 +000046 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000047 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000048}
49
50
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000051StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000052 bool HasLeadingEmptyMacro) {
53 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000054}
55
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000056StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
57 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000058 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000059
Chris Lattnercbafe8d2009-04-12 20:13:14 +000060 // If we have an invalid decl, just return an error.
61 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattner34a22092009-03-04 04:23:07 +000063 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000064}
Chris Lattneraf8d5812006-11-10 05:07:45 +000065
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000066void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
67 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000068
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000069 // If we have an invalid decl, just return.
70 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000071 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
72
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000073 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000074 var->setUsed();
75
John McCalld4631322011-06-17 06:42:21 +000076 // foreach variables are never actually initialized in the way that
77 // the parser came up with.
78 var->setInit(0);
John McCall31168b02011-06-15 23:02:42 +000079
John McCalld4631322011-06-17 06:42:21 +000080 // In ARC, we don't need to retain the iteration variable of a fast
81 // enumeration loop. Rather than actually trying to catch that
82 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +000083 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +000084 QualType type = var->getType();
85
86 // Only do this if we inferred the lifetime. Inferred lifetime
87 // will show up as a local qualifier because explicit lifetime
88 // should have shown up as an AttributedType instead.
89 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
90 // Add 'const' and mark the variable as pseudo-strong.
91 var->setType(type.withConst());
92 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +000093 }
94 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000095}
96
Chandler Carruthe2669392011-08-17 09:34:37 +000097/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +000098///
99/// Adding a cast to void (or other expression wrappers) will prevent the
100/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000101static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000102 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000103 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000104
105 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
106 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthe2669392011-08-17 09:34:37 +0000107 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000108
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000109 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000110 IsNotEqual = Op->getOpcode() == BO_NE;
111 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000112 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
113 if (Op->getOperator() != OO_EqualEqual &&
114 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthe2669392011-08-17 09:34:37 +0000115 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000116
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000117 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000118 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
119 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120 } else {
121 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000122 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000123 }
124
125 // Suppress warnings when the operator, suspicious as it may be, comes from
126 // a macro expansion.
127 if (Loc.isMacroID())
Chandler Carruthe2669392011-08-17 09:34:37 +0000128 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129
Chandler Carruthe2669392011-08-17 09:34:37 +0000130 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131 << (unsigned)IsNotEqual << E->getSourceRange();
132
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000133 // If the LHS is a plausible entity to assign to, provide a fixit hint to
134 // correct common typos.
135 if (CanAssign) {
136 if (IsNotEqual)
137 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
138 << FixItHint::CreateReplacement(Loc, "|=");
139 else
140 S.Diag(Loc, diag::note_equality_comparison_to_assign)
141 << FixItHint::CreateReplacement(Loc, "=");
142 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000143
144 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000145}
146
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000147void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000148 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
149 return DiagnoseUnusedExprResult(Label->getSubStmt());
150
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000151 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000152 if (!E)
153 return;
154
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000155 SourceLocation Loc;
156 SourceRange R1, R2;
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +0000157 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
158 !E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000159 return;
Mike Stump11289f42009-09-09 15:08:12 +0000160
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000161 // Okay, we have an unused result. Depending on what the base expression is,
162 // we might want to make a more specific diagnostic. Check for one of these
163 // cases now.
164 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000165 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000166 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000167 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
168 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000169
Chandler Carruthe2669392011-08-17 09:34:37 +0000170 if (DiagnoseUnusedComparison(*this, E))
171 return;
172
John McCall34376a62010-12-04 03:47:34 +0000173 E = E->IgnoreParenImpCasts();
Chris Lattner1a6babf2009-10-13 04:53:48 +0000174 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000175 if (E->getType()->isVoidType())
176 return;
177
Chris Lattner1a6babf2009-10-13 04:53:48 +0000178 // If the callee has attribute pure, const, or warn_unused_result, warn with
179 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000180 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000181 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000182 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000183 return;
184 }
185 if (FD->getAttr<PureAttr>()) {
186 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
187 return;
188 }
189 if (FD->getAttr<ConstAttr>()) {
190 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
191 return;
192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193 }
John McCallb7bd14f2010-12-02 01:19:52 +0000194 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000195 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000196 Diag(Loc, diag::err_arc_unused_init_message) << R1;
197 return;
198 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000199 const ObjCMethodDecl *MD = ME->getMethodDecl();
200 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000201 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000202 return;
203 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000204 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
205 const Expr *Source = POE->getSyntacticForm();
206 if (isa<ObjCSubscriptRefExpr>(Source))
207 DiagID = diag::warn_unused_container_subscript_expr;
208 else
209 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000210 } else if (const CXXFunctionalCastExpr *FC
211 = dyn_cast<CXXFunctionalCastExpr>(E)) {
212 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
213 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
214 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000215 }
John McCall2351cb92010-04-06 22:24:14 +0000216 // Diagnose "(void*) blah" as a typo for "(void) blah".
217 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
218 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
219 QualType T = TI->getType();
220
221 // We really do want to use the non-canonical type here.
222 if (T == Context.VoidPtrTy) {
223 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
224
225 Diag(Loc, diag::warn_unused_voidptr)
226 << FixItHint::CreateRemoval(TL.getStarLoc());
227 return;
228 }
229 }
230
Ted Kremenek3427fac2011-02-23 01:52:04 +0000231 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000232}
233
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000234void Sema::ActOnStartOfCompoundStmt() {
235 PushCompoundScope();
236}
237
238void Sema::ActOnFinishOfCompoundStmt() {
239 PopCompoundScope();
240}
241
242sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
243 return getCurFunction()->CompoundScopes.back();
244}
245
John McCalldadc5752010-08-24 06:29:42 +0000246StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000247Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000248 MultiStmtArg elts, bool isStmtExpr) {
249 unsigned NumElts = elts.size();
250 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000251 // If we're in C89 mode, check that we don't have any decls after stmts. If
252 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000253 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000254 // Note that __extension__ can be around a decl.
255 unsigned i = 0;
256 // Skip over all declarations.
257 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
258 /*empty*/;
259
260 // We found the end of the list or a statement. Scan for another declstmt.
261 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
262 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattnerd864daf2007-08-27 04:29:41 +0000264 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000265 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000266 Diag(D->getLocation(), diag::ext_mixed_decls_code);
267 }
268 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000269 // Warn about unused expressions in statements.
270 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000271 // Ignore statements that are last in a statement expression.
272 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000273 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000275 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000276 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000277
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000278 // Check for suspicious empty body (null statement) in `for' and `while'
279 // statements. Don't do anything for template instantiations, this just adds
280 // noise.
281 if (NumElts != 0 && !CurrentInstantiationScope &&
282 getCurCompoundScope().HasEmptyLoopBodies) {
283 for (unsigned i = 0; i != NumElts - 1; ++i)
284 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
285 }
286
Ted Kremenek5a201952009-02-07 01:47:29 +0000287 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000288}
289
John McCalldadc5752010-08-24 06:29:42 +0000290StmtResult
John McCallb268a282010-08-23 23:25:46 +0000291Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
292 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000293 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000294 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000295
John McCallaab3e412010-08-25 08:40:02 +0000296 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000297 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000298 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000299 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000300
David Blaikiebbafb8a2012-03-11 07:00:24 +0000301 if (!getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000302 // C99 6.8.4.2p3: The expression shall be an integer constant.
303 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000304 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
305 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
306 if (!LHSVal)
307 return StmtError();
308 }
Richard Smithf8379a02012-01-18 23:55:52 +0000309
310 // GCC extension: The expression shall be an integer constant.
311
Richard Smithf4c51d92012-02-04 09:53:13 +0000312 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
313 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
314 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000315 }
316 }
317
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000318 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
319 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000320 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000321 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000322}
323
Chris Lattner34a22092009-03-04 04:23:07 +0000324/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000325void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000326 DiagnoseUnusedExprResult(SubStmt);
327
Chris Lattner34a22092009-03-04 04:23:07 +0000328 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000329 CS->setSubStmt(SubStmt);
330}
331
John McCalldadc5752010-08-24 06:29:42 +0000332StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000333Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000334 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000335 DiagnoseUnusedExprResult(SubStmt);
336
John McCallaab3e412010-08-25 08:40:02 +0000337 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000338 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000339 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000340 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000341
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000342 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000343 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000344 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000345}
346
John McCalldadc5752010-08-24 06:29:42 +0000347StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000348Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
349 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000350 // If the label was multiply defined, reject it now.
351 if (TheDecl->getStmt()) {
352 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
353 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000354 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000355 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000356
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000357 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000358 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
359 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000360 if (!TheDecl->isGnuLocal())
361 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000362 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000363}
364
Richard Smithc202b282012-04-14 00:33:13 +0000365StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
366 const AttrVec &Attrs,
367 Stmt *SubStmt) {
368 // Fill in the declaration and return it. Variable length will require to
369 // change this to AttributedStmt::Create(Context, ....);
370 // and probably using ArrayRef
371 AttributedStmt *LS = new (Context) AttributedStmt(AttrLoc, Attrs, SubStmt);
372 return Owned(LS);
373}
374
John McCalldadc5752010-08-24 06:29:42 +0000375StmtResult
John McCall48871652010-08-21 09:40:31 +0000376Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000377 Stmt *thenStmt, SourceLocation ElseLoc,
378 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000379 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000380
Douglas Gregor633caca2009-11-23 23:44:04 +0000381 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000382 if (CondVar) {
383 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000384 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000385 if (CondResult.isInvalid())
386 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000387 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000388 Expr *ConditionExpr = CondResult.takeAs<Expr>();
389 if (!ConditionExpr)
390 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000392 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000393
John McCallb268a282010-08-23 23:25:46 +0000394 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000395 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
396 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000397 }
398
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000399 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000400
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000402 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000403}
Steve Naroff86272ea2007-05-29 02:14:17 +0000404
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000405/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
406/// the specified width and sign. If an overflow occurs, detect it and emit
407/// the specified diagnostic.
408void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
409 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000410 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000411 unsigned DiagID) {
412 // Perform a conversion to the promoted condition type if needed.
413 if (NewWidth > Val.getBitWidth()) {
414 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000415 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000416 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000417
418 // If the input was signed and negative and the output is
419 // unsigned, don't bother to warn: this is implementation-defined
420 // behavior.
421 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000422 } else if (NewWidth < Val.getBitWidth()) {
423 // If this is a truncation, check for overflow.
424 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000425 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000426 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000427 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000428 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000429 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000430 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000431
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000432 // Regardless of whether a diagnostic was emitted, really do the
433 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000434 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000435 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000436 } else if (NewSign != Val.isSigned()) {
437 // Convert the sign to match the sign of the condition. This can cause
438 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000440 // behavior.
441 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000442 llvm::APSInt OldVal(Val);
443 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000444 }
445}
446
Chris Lattner67998452007-08-23 18:29:20 +0000447namespace {
448 struct CaseCompareFunctor {
449 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
450 const llvm::APSInt &RHS) {
451 return LHS.first < RHS;
452 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000453 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
454 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
455 return LHS.first < RHS.first;
456 }
Chris Lattner67998452007-08-23 18:29:20 +0000457 bool operator()(const llvm::APSInt &LHS,
458 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
459 return LHS < RHS.first;
460 }
461 };
462}
463
Chris Lattner4b2ff022007-09-21 18:15:22 +0000464/// CmpCaseVals - Comparison predicate for sorting case values.
465///
466static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
467 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
468 if (lhs.first < rhs.first)
469 return true;
470
471 if (lhs.first == rhs.first &&
472 lhs.second->getCaseLoc().getRawEncoding()
473 < rhs.second->getCaseLoc().getRawEncoding())
474 return true;
475 return false;
476}
477
Douglas Gregorbd6839732010-02-08 22:24:16 +0000478/// CmpEnumVals - Comparison predicate for sorting enumeration values.
479///
480static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
481 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
482{
483 return lhs.first < rhs.first;
484}
485
486/// EqEnumVals - Comparison preficate for uniqing enumeration values.
487///
488static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
489 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
490{
491 return lhs.first == rhs.first;
492}
493
Chris Lattnera96d4272009-10-16 16:45:22 +0000494/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
495/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000496static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
497 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
498 expr = cleanups->getSubExpr();
499 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
500 if (impcast->getCastKind() != CK_IntegralCast) break;
501 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000502 }
503 return expr->getType();
504}
505
John McCalldadc5752010-08-24 06:29:42 +0000506StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000508 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000509 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000510
Douglas Gregore60e41a2010-05-06 17:25:47 +0000511 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000512 if (CondVar) {
513 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000514 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
515 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000516 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000517
John McCallb268a282010-08-23 23:25:46 +0000518 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000520
John McCallb268a282010-08-23 23:25:46 +0000521 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000522 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
John McCallb268a282010-08-23 23:25:46 +0000524 CondResult
Eli Friedman1da70392012-01-26 00:26:18 +0000525 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000526 PDiag(diag::err_typecheck_statement_requires_integer),
527 PDiag(diag::err_switch_incomplete_class_type)
John McCallb268a282010-08-23 23:25:46 +0000528 << Cond->getSourceRange(),
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000529 PDiag(diag::err_switch_explicit_conversion),
530 PDiag(diag::note_switch_conversion),
531 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000532 PDiag(diag::note_switch_conversion),
Richard Smith8dd34252012-02-04 07:07:42 +0000533 PDiag(0),
534 /*AllowScopedEnumerations*/ true);
John McCallb268a282010-08-23 23:25:46 +0000535 if (CondResult.isInvalid()) return StmtError();
536 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
John McCall5939b162011-08-06 07:30:58 +0000538 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
539 CondResult = UsualUnaryConversions(Cond);
540 if (CondResult.isInvalid()) return StmtError();
541 Cond = CondResult.take();
542
John McCall48871652010-08-21 09:40:31 +0000543 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000544 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000545 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000546 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000547 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000548 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000549 }
John McCalla95172b2010-08-01 00:26:45 +0000550
John McCallaab3e412010-08-25 08:40:02 +0000551 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
John McCallb268a282010-08-23 23:25:46 +0000553 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000554 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000555 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000556}
557
Gabor Greif16e02862010-10-01 22:05:14 +0000558static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
559 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000560 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000561 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000562 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000563 Val.setIsSigned(IsSigned);
564}
565
John McCalldadc5752010-08-24 06:29:42 +0000566StmtResult
John McCallb268a282010-08-23 23:25:46 +0000567Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
568 Stmt *BodyStmt) {
569 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000570 assert(SS == getCurFunction()->SwitchStack.back() &&
571 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000572
Steve Naroff42a350a2007-09-01 21:08:38 +0000573 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000574 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000575
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000576 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000577 if (!CondExpr) return StmtError();
578
579 QualType CondType = CondExpr->getType();
580
John McCalld3dfbd62010-05-18 03:19:21 +0000581 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000582 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000583 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000584
Chris Lattnera96d4272009-10-16 16:45:22 +0000585 // C++ 6.4.2.p2:
586 // Integral promotions are performed (on the switch condition).
587 //
588 // A case value unrepresentable by the original switch condition
589 // type (before the promotion) doesn't make sense, even when it can
590 // be represented by the promoted type. Therefore we need to find
591 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000592 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000593 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000595 // appropriate type now, just return an error.
596 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000597 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000598
Chris Lattner4ebae652010-04-16 23:34:13 +0000599 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000600 // switch(bool_expr) {...} is often a programmer error, e.g.
601 // switch(n && mask) { ... } // Doh - should be "n & mask".
602 // One can always use an if statement instead of switch(bool_expr).
603 Diag(SwitchLoc, diag::warn_bool_switch_condition)
604 << CondExpr->getSourceRange();
605 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000606 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000607
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000608 // Get the bitwidth of the switched-on value before promotions. We must
609 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000610 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000611 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000612 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000613 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000614 bool CondIsSigned
615 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000616
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000617 // Accumulate all of the case values in a vector so that we can sort them
618 // and detect duplicates. This vector contains the APInt for the case after
619 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000621 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000623 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000624 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
625 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000627 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner10cb5e52007-08-23 06:23:56 +0000629 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000630
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000631 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000632 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000633
Anders Carlsson51873c22007-07-22 07:07:56 +0000634 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000635 if (TheDefaultStmt) {
636 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000637 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000638
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000639 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000640 // we'll return a valid AST. This requires recursing down the AST and
641 // finding it, not something we are set up to do right now. For now,
642 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000643 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000644 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000645 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000647 } else {
648 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattnera65e1f32008-01-16 19:17:22 +0000650 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000651
652 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
653 HasDependentValue = true;
654 break;
655 }
Mike Stump11289f42009-09-09 15:08:12 +0000656
Richard Smithf8379a02012-01-18 23:55:52 +0000657 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000658
David Blaikiebbafb8a2012-03-11 07:00:24 +0000659 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000660 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
661 // constant expression of the promoted type of the switch condition.
662 ExprResult ConvLo =
663 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
664 if (ConvLo.isInvalid()) {
665 CaseListIsErroneous = true;
666 continue;
667 }
668 Lo = ConvLo.take();
669 } else {
670 // We already verified that the expression has a i-c-e value (C99
671 // 6.8.4.2p3) - get that value now.
672 LoVal = Lo->EvaluateKnownConstInt(Context);
673
674 // If the LHS is not the same type as the condition, insert an implicit
675 // cast.
676 Lo = DefaultLvalueConversion(Lo).take();
677 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
678 }
679
680 // Convert the value to the same width/sign as the condition had prior to
681 // integral promotions.
682 //
683 // FIXME: This causes us to reject valid code:
684 // switch ((char)c) { case 256: case 0: return 0; }
685 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000686 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000687 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000688 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000689
Chris Lattnera65e1f32008-01-16 19:17:22 +0000690 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner10cb5e52007-08-23 06:23:56 +0000692 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000693 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000694 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000695 CS->getRHS()->isValueDependent()) {
696 HasDependentValue = true;
697 break;
698 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000699 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000700 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000701 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000702 }
703 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000704
705 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000706 // If we don't have a default statement, check whether the
707 // condition is constant.
708 llvm::APSInt ConstantCondValue;
709 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000710 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000711 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000712 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
713 Expr::SE_AllowSideEffects);
714 assert(!HasConstantCond ||
715 (ConstantCondValue.getBitWidth() == CondWidth &&
716 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000717 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000718 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000719
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000720 // Sort all the scalar case values so we can easily detect duplicates.
721 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
722
723 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000724 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
725 if (ShouldCheckConstantCond &&
726 CaseVals[i].first == ConstantCondValue)
727 ShouldCheckConstantCond = false;
728
729 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000730 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000731 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000732 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
733 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000734 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000735 // FIXME: We really want to remove the bogus case stmt from the
736 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000737 CaseListIsErroneous = true;
738 }
739 }
740 }
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000742 // Detect duplicate case ranges, which usually don't exist at all in
743 // the first place.
744 if (!CaseRanges.empty()) {
745 // Sort all the case ranges by their low value so we can easily detect
746 // overlaps between ranges.
747 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000748
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000749 // Scan the ranges, computing the high values and removing empty ranges.
750 std::vector<llvm::APSInt> HiVals;
751 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000752 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000753 CaseStmt *CR = CaseRanges[i].second;
754 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000755 llvm::APSInt HiVal;
756
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000758 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
759 // constant expression of the promoted type of the switch condition.
760 ExprResult ConvHi =
761 CheckConvertedConstantExpression(Hi, CondType, HiVal,
762 CCEK_CaseValue);
763 if (ConvHi.isInvalid()) {
764 CaseListIsErroneous = true;
765 continue;
766 }
767 Hi = ConvHi.take();
768 } else {
769 HiVal = Hi->EvaluateKnownConstInt(Context);
770
771 // If the RHS is not the same type as the condition, insert an
772 // implicit cast.
773 Hi = DefaultLvalueConversion(Hi).take();
774 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000777 // Convert the value to the same width/sign as the condition.
778 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000779 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000780 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000781
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000782 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000784 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000785 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000786 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
787 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000788 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000789 CaseRanges.erase(CaseRanges.begin()+i);
790 --i, --e;
791 continue;
792 }
John McCalld3dfbd62010-05-18 03:19:21 +0000793
794 if (ShouldCheckConstantCond &&
795 LoVal <= ConstantCondValue &&
796 ConstantCondValue <= HiVal)
797 ShouldCheckConstantCond = false;
798
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000799 HiVals.push_back(HiVal);
800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000802 // Rescan the ranges, looking for overlap with singleton values and other
803 // ranges. Since the range list is sorted, we only need to compare case
804 // ranges with their neighbors.
805 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
806 llvm::APSInt &CRLo = CaseRanges[i].first;
807 llvm::APSInt &CRHi = HiVals[i];
808 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000809
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000810 // Check to see whether the case range overlaps with any
811 // singleton cases.
812 CaseStmt *OverlapStmt = 0;
813 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000814
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000815 // Find the smallest value >= the lower bound. If I is in the
816 // case range, then we have overlap.
817 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
818 CaseVals.end(), CRLo,
819 CaseCompareFunctor());
820 if (I != CaseVals.end() && I->first < CRHi) {
821 OverlapVal = I->first; // Found overlap with scalar.
822 OverlapStmt = I->second;
823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000825 // Find the smallest value bigger than the upper bound.
826 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
827 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
828 OverlapVal = (I-1)->first; // Found overlap with scalar.
829 OverlapStmt = (I-1)->second;
830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000832 // Check to see if this case stmt overlaps with the subsequent
833 // case range.
834 if (i && CRLo <= HiVals[i-1]) {
835 OverlapVal = HiVals[i-1]; // Found overlap with range.
836 OverlapStmt = CaseRanges[i-1].second;
837 }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000839 if (OverlapStmt) {
840 // If we have a duplicate, report it.
841 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
842 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000843 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000844 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000845 // FIXME: We really want to remove the bogus case stmt from the
846 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000847 CaseListIsErroneous = true;
848 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000849 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000850 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000851
John McCalld3dfbd62010-05-18 03:19:21 +0000852 // Complain if we have a constant condition and we didn't find a match.
853 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
854 // TODO: it would be nice if we printed enums as enums, chars as
855 // chars, etc.
856 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
857 << ConstantCondValue.toString(10)
858 << CondExpr->getSourceRange();
859 }
860
861 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000862 // values. We only issue a warning if there is not 'default:', but
863 // we still do the analysis to preserve this information in the AST
864 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000865 //
Chris Lattner51679082010-09-16 17:09:42 +0000866 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000867
Douglas Gregorbd6839732010-02-08 22:24:16 +0000868 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000869 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000870 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000871 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000872 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000873 EnumValsTy EnumVals;
874
John McCalld3dfbd62010-05-18 03:19:21 +0000875 // Gather all enum values, set their type and sort them,
876 // allowing easier comparison with CaseVals.
877 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000878 EDI != ED->enumerator_end(); ++EDI) {
879 llvm::APSInt Val = EDI->getInitVal();
880 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie2d7c57e2012-04-30 02:36:29 +0000881 EnumVals.push_back(std::make_pair(Val, &*EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000882 }
883 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000884 EnumValsTy::iterator EIend =
885 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000886
887 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +0000888 EnumValsTy::const_iterator EI = EnumVals.begin();
889 for (CaseValsTy::const_iterator CI = CaseVals.begin();
890 CI != CaseVals.end(); CI++) {
891 while (EI != EIend && EI->first < CI->first)
892 EI++;
893 if (EI == EIend || EI->first > CI->first)
894 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000895 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +0000896 }
897 // See which of case ranges aren't in enum
898 EI = EnumVals.begin();
899 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
900 RI != CaseRanges.end() && EI != EIend; RI++) {
901 while (EI != EIend && EI->first < RI->first)
902 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
David Blaikiee476f972012-01-22 02:31:55 +0000904 if (EI == EIend || EI->first != RI->first) {
905 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000906 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +0000907 }
David Blaikiee476f972012-01-22 02:31:55 +0000908
909 llvm::APSInt Hi =
910 RI->second->getRHS()->EvaluateKnownConstInt(Context);
911 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
912 while (EI != EIend && EI->first < Hi)
913 EI++;
914 if (EI == EIend || EI->first != Hi)
915 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000916 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Ted Kremenekc42f3452010-09-09 00:05:53 +0000919 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000920 CaseValsTy::const_iterator CI = CaseVals.begin();
921 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000922 bool hasCasesNotInSwitch = false;
923
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000924 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000925
David Blaikiee476f972012-01-22 02:31:55 +0000926 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000927 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000928 llvm::APSInt CIVal;
929 while (CI != CaseVals.end() && CI->first < EI->first)
930 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000931
Douglas Gregorbd6839732010-02-08 22:24:16 +0000932 if (CI != CaseVals.end() && CI->first == EI->first)
933 continue;
934
Ted Kremenekc42f3452010-09-09 00:05:53 +0000935 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +0000936 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +0000937 llvm::APSInt Hi =
938 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000939 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000940 if (EI->first <= Hi)
941 break;
942 }
943
Ted Kremenekc42f3452010-09-09 00:05:53 +0000944 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000945 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +0000946 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +0000947 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949
David Blaikie60ac6382012-01-23 04:46:12 +0000950 if (TheDefaultStmt && UnhandledNames.empty())
951 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +0000952
Chris Lattner51679082010-09-16 17:09:42 +0000953 // Produce a nice diagnostic if multiple values aren't handled.
954 switch (UnhandledNames.size()) {
955 case 0: break;
956 case 1:
David Blaikie60ac6382012-01-23 04:46:12 +0000957 Diag(CondExpr->getExprLoc(), TheDefaultStmt
958 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +0000959 << UnhandledNames[0];
960 break;
961 case 2:
David Blaikie60ac6382012-01-23 04:46:12 +0000962 Diag(CondExpr->getExprLoc(), TheDefaultStmt
963 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +0000964 << UnhandledNames[0] << UnhandledNames[1];
965 break;
966 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +0000967 Diag(CondExpr->getExprLoc(), TheDefaultStmt
968 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +0000969 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
970 break;
971 default:
David Blaikie60ac6382012-01-23 04:46:12 +0000972 Diag(CondExpr->getExprLoc(), TheDefaultStmt
973 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +0000974 << (unsigned)UnhandledNames.size()
975 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
976 break;
977 }
Ted Kremenekc42f3452010-09-09 00:05:53 +0000978
979 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +0000980 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000981 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000982 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000983
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000984 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
985 diag::warn_empty_switch_body);
986
Mike Stump87c57ac2009-05-16 07:39:55 +0000987 // FIXME: If the case list was broken is some way, we don't have a good system
988 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000989 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000990 return StmtError();
991
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000992 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000993}
994
John McCalldadc5752010-08-24 06:29:42 +0000995StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +0000997 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +0000998 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
Douglas Gregor680f8612009-11-24 21:15:44 +00001000 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001001 if (CondVar) {
1002 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001003 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001004 if (CondResult.isInvalid())
1005 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001006 }
John McCallb268a282010-08-23 23:25:46 +00001007 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001008 if (!ConditionExpr)
1009 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
John McCallb268a282010-08-23 23:25:46 +00001011 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001012
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001013 if (isa<NullStmt>(Body))
1014 getCurCompoundScope().setHasEmptyLoopBodies();
1015
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001016 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +00001017 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001018}
1019
John McCalldadc5752010-08-24 06:29:42 +00001020StmtResult
John McCallb268a282010-08-23 23:25:46 +00001021Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001022 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001023 Expr *Cond, SourceLocation CondRParen) {
1024 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001025
John Wiegley01296292011-04-08 18:41:53 +00001026 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1027 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001028 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001029 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001030
John McCallacf0ee52010-10-08 02:01:28 +00001031 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +00001032 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +00001033 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001034 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001035 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
John McCallb268a282010-08-23 23:25:46 +00001037 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001038
John McCallb268a282010-08-23 23:25:46 +00001039 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001040}
1041
Richard Trieu451a5db2012-04-30 18:01:30 +00001042namespace {
1043 // This visitor will traverse a conditional statement and store all
1044 // the evaluated decls into a vector. Simple is set to true if none
1045 // of the excluded constructs are used.
1046 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1047 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1048 llvm::SmallVector<SourceRange, 10> &Ranges;
1049 bool Simple;
1050 PartialDiagnostic &PDiag;
1051public:
1052 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1053
1054 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1055 llvm::SmallVector<SourceRange, 10> &Ranges,
1056 PartialDiagnostic &PDiag) :
1057 Inherited(S.Context),
1058 Decls(Decls),
1059 Ranges(Ranges),
1060 Simple(true),
1061 PDiag(PDiag) {}
1062
1063 bool isSimple() { return Simple; }
1064
1065 // Replaces the method in EvaluatedExprVisitor.
1066 void VisitMemberExpr(MemberExpr* E) {
1067 Simple = false;
1068 }
1069
1070 // Any Stmt not whitelisted will cause the condition to be marked complex.
1071 void VisitStmt(Stmt *S) {
1072 Simple = false;
1073 }
1074
1075 void VisitBinaryOperator(BinaryOperator *E) {
1076 Visit(E->getLHS());
1077 Visit(E->getRHS());
1078 }
1079
1080 void VisitCastExpr(CastExpr *E) {
1081 Visit(E->getSubExpr());
1082 }
1083
1084 void VisitUnaryOperator(UnaryOperator *E) {
1085 // Skip checking conditionals with derefernces.
1086 if (E->getOpcode() == UO_Deref)
1087 Simple = false;
1088 else
1089 Visit(E->getSubExpr());
1090 }
1091
1092 void VisitConditionalOperator(ConditionalOperator *E) {
1093 Visit(E->getCond());
1094 Visit(E->getTrueExpr());
1095 Visit(E->getFalseExpr());
1096 }
1097
1098 void VisitParenExpr(ParenExpr *E) {
1099 Visit(E->getSubExpr());
1100 }
1101
1102 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1103 Visit(E->getOpaqueValue()->getSourceExpr());
1104 Visit(E->getFalseExpr());
1105 }
1106
1107 void VisitIntegerLiteral(IntegerLiteral *E) { }
1108 void VisitFloatingLiteral(FloatingLiteral *E) { }
1109 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1110 void VisitCharacterLiteral(CharacterLiteral *E) { }
1111 void VisitGNUNullExpr(GNUNullExpr *E) { }
1112 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1113
1114 void VisitDeclRefExpr(DeclRefExpr *E) {
1115 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1116 if (!VD) return;
1117
1118 Ranges.push_back(E->getSourceRange());
1119
1120 Decls.insert(VD);
1121 }
1122
1123 }; // end class DeclExtractor
1124
1125 // DeclMatcher checks to see if the decls are used in a non-evauluated
1126 // context.
1127 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1128 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1129 bool FoundDecl;
1130 //bool EvalDecl;
1131
1132public:
1133 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1134
1135 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1136 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1137 if (!Statement) return;
1138
1139 Visit(Statement);
1140 }
1141
1142 void VisitReturnStmt(ReturnStmt *S) {
1143 FoundDecl = true;
1144 }
1145
1146 void VisitBreakStmt(BreakStmt *S) {
1147 FoundDecl = true;
1148 }
1149
1150 void VisitGotoStmt(GotoStmt *S) {
1151 FoundDecl = true;
1152 }
1153
1154 void VisitCastExpr(CastExpr *E) {
1155 if (E->getCastKind() == CK_LValueToRValue)
1156 CheckLValueToRValueCast(E->getSubExpr());
1157 else
1158 Visit(E->getSubExpr());
1159 }
1160
1161 void CheckLValueToRValueCast(Expr *E) {
1162 E = E->IgnoreParenImpCasts();
1163
1164 if (isa<DeclRefExpr>(E)) {
1165 return;
1166 }
1167
1168 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1169 Visit(CO->getCond());
1170 CheckLValueToRValueCast(CO->getTrueExpr());
1171 CheckLValueToRValueCast(CO->getFalseExpr());
1172 return;
1173 }
1174
1175 if (BinaryConditionalOperator *BCO =
1176 dyn_cast<BinaryConditionalOperator>(E)) {
1177 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1178 CheckLValueToRValueCast(BCO->getFalseExpr());
1179 return;
1180 }
1181
1182 Visit(E);
1183 }
1184
1185 void VisitDeclRefExpr(DeclRefExpr *E) {
1186 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1187 if (Decls.count(VD))
1188 FoundDecl = true;
1189 }
1190
1191 bool FoundDeclInUse() { return FoundDecl; }
1192
1193 }; // end class DeclMatcher
1194
1195 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1196 Expr *Third, Stmt *Body) {
1197 // Condition is empty
1198 if (!Second) return;
1199
1200 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1201 Second->getLocStart())
1202 == DiagnosticsEngine::Ignored)
1203 return;
1204
1205 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1206 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1207 llvm::SmallVector<SourceRange, 10> Ranges;
1208 DeclExtractor DE(S, Decls, Ranges, PDiag);
1209 DE.Visit(Second);
1210
1211 // Don't analyze complex conditionals.
1212 if (!DE.isSimple()) return;
1213
1214 // No decls found.
1215 if (Decls.size() == 0) return;
1216
Richard Trieu0030f1d2012-05-04 03:01:54 +00001217 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001218 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1219 E = Decls.end();
1220 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001221 if ((*I)->getType().isVolatileQualified() ||
1222 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001223
1224 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1225 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1226 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1227 return;
1228
1229 // Load decl names into diagnostic.
1230 if (Decls.size() > 4)
1231 PDiag << 0;
1232 else {
1233 PDiag << Decls.size();
1234 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1235 E = Decls.end();
1236 I != E; ++I)
1237 PDiag << (*I)->getDeclName();
1238 }
1239
1240 // Load SourceRanges into diagnostic if there is room.
1241 // Otherwise, load the SourceRange of the conditional expression.
1242 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1243 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1244 E = Ranges.end();
1245 I != E; ++I)
1246 PDiag << *I;
1247 else
1248 PDiag << Second->getSourceRange();
1249
1250 S.Diag(Ranges.begin()->getBegin(), PDiag);
1251 }
1252
1253} // end namespace
1254
John McCalldadc5752010-08-24 06:29:42 +00001255StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001256Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001257 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001258 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001259 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001260 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001261 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001262 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1263 // declare identifiers for objects having storage class 'auto' or
1264 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001265 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1266 DI!=DE; ++DI) {
1267 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001268 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001269 VD = 0;
1270 if (VD == 0)
1271 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1272 // FIXME: mark decl erroneous!
1273 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001274 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001275 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001276
Richard Trieu451a5db2012-04-30 18:01:30 +00001277 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1278
John McCalldadc5752010-08-24 06:29:42 +00001279 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001280 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001281 if (secondVar) {
1282 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001283 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001284 if (SecondResult.isInvalid())
1285 return StmtError();
1286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001288 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001289
Anders Carlsson1682af52009-08-01 01:39:59 +00001290 DiagnoseUnusedExprResult(First);
1291 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001292 DiagnoseUnusedExprResult(Body);
1293
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001294 if (isa<NullStmt>(Body))
1295 getCurCompoundScope().setHasEmptyLoopBodies();
1296
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297 return Owned(new (Context) ForStmt(Context, First,
1298 SecondResult.take(), ConditionVar,
1299 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001300 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001301}
1302
John McCall34376a62010-12-04 03:47:34 +00001303/// In an Objective C collection iteration statement:
1304/// for (x in y)
1305/// x can be an arbitrary l-value expression. Bind it up as a
1306/// full-expression.
1307StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001308 // Reduce placeholder expressions here. Note that this rejects the
1309 // use of pseudo-object l-values in this position.
1310 ExprResult result = CheckPlaceholderExpr(E);
1311 if (result.isInvalid()) return StmtError();
1312 E = result.take();
1313
John McCall34376a62010-12-04 03:47:34 +00001314 CheckImplicitConversions(E);
John McCallbc153352012-03-30 05:43:39 +00001315
1316 result = MaybeCreateExprWithCleanups(E);
1317 if (result.isInvalid()) return StmtError();
1318
1319 return Owned(static_cast<Stmt*>(result.take()));
John McCall34376a62010-12-04 03:47:34 +00001320}
1321
John McCall53848232011-07-27 01:07:15 +00001322ExprResult
1323Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1324 assert(collection);
1325
1326 // Bail out early if we've got a type-dependent expression.
1327 if (collection->isTypeDependent()) return Owned(collection);
1328
1329 // Perform normal l-value conversion.
1330 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1331 if (result.isInvalid())
1332 return ExprError();
1333 collection = result.take();
1334
1335 // The operand needs to have object-pointer type.
1336 // TODO: should we do a contextual conversion?
1337 const ObjCObjectPointerType *pointerType =
1338 collection->getType()->getAs<ObjCObjectPointerType>();
1339 if (!pointerType)
1340 return Diag(forLoc, diag::err_collection_expr_type)
1341 << collection->getType() << collection->getSourceRange();
1342
1343 // Check that the operand provides
1344 // - countByEnumeratingWithState:objects:count:
1345 const ObjCObjectType *objectType = pointerType->getObjectType();
1346 ObjCInterfaceDecl *iface = objectType->getInterface();
1347
1348 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001349 // Under ARC, it is an error not to have a forward-declared class.
1350 if (iface &&
1351 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001352 getLangOpts().ObjCAutoRefCount
Douglas Gregor4123a862011-11-14 22:10:01 +00001353 ? PDiag(diag::err_arc_collection_forward)
1354 << collection->getSourceRange()
1355 : PDiag(0))) {
John McCall53848232011-07-27 01:07:15 +00001356 // Otherwise, if we have any useful type information, check that
1357 // the type declares the appropriate method.
1358 } else if (iface || !objectType->qual_empty()) {
1359 IdentifierInfo *selectorIdents[] = {
1360 &Context.Idents.get("countByEnumeratingWithState"),
1361 &Context.Idents.get("objects"),
1362 &Context.Idents.get("count")
1363 };
1364 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1365
1366 ObjCMethodDecl *method = 0;
1367
1368 // If there's an interface, look in both the public and private APIs.
1369 if (iface) {
1370 method = iface->lookupInstanceMethod(selector);
1371 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1372 }
1373
1374 // Also check protocol qualifiers.
1375 if (!method)
1376 method = LookupMethodInQualifiedType(selector, pointerType,
1377 /*instance*/ true);
1378
1379 // If we didn't find it anywhere, give up.
1380 if (!method) {
1381 Diag(forLoc, diag::warn_collection_expr_type)
1382 << collection->getType() << selector << collection->getSourceRange();
1383 }
1384
1385 // TODO: check for an incompatible signature?
1386 }
1387
1388 // Wrap up any cleanups in the expression.
1389 return Owned(MaybeCreateExprWithCleanups(collection));
1390}
1391
John McCalldadc5752010-08-24 06:29:42 +00001392StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001393Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1394 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001395 Stmt *First, Expr *Second,
1396 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +00001397 if (First) {
1398 QualType FirstType;
1399 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001400 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001401 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1402 diag::err_toomany_element_decls));
1403
John McCall31168b02011-06-15 23:02:42 +00001404 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1405 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001406 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1407 // declare identifiers for objects having storage class 'auto' or
1408 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001409 if (!D->hasLocalStorage())
1410 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001411 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001412 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001413 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001414 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001415 return StmtError(Diag(First->getLocStart(),
1416 diag::err_selector_element_not_lvalue)
1417 << First->getSourceRange());
1418
Mike Stump11289f42009-09-09 15:08:12 +00001419 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001420 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001421 if (!FirstType->isDependentType() &&
1422 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001423 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +00001424 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001425 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001426 }
John McCall53848232011-07-27 01:07:15 +00001427
Ted Kremenek5a201952009-02-07 01:47:29 +00001428 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1429 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001430}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001431
Richard Smith02e85f32011-04-14 22:09:26 +00001432namespace {
1433
1434enum BeginEndFunction {
1435 BEF_begin,
1436 BEF_end
1437};
1438
1439/// Build a variable declaration for a for-range statement.
1440static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1441 QualType Type, const char *Name) {
1442 DeclContext *DC = SemaRef.CurContext;
1443 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1444 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1445 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1446 TInfo, SC_Auto, SC_None);
Richard Smith0c502d22011-04-18 15:49:25 +00001447 Decl->setImplicit();
Richard Smith02e85f32011-04-14 22:09:26 +00001448 return Decl;
1449}
1450
1451/// Finish building a variable declaration for a for-range statement.
1452/// \return true if an error occurs.
1453static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1454 SourceLocation Loc, int diag) {
1455 // Deduce the type for the iterator variable now rather than leaving it to
1456 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1457 TypeSourceInfo *InitTSI = 0;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001458 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redl09edce02012-01-23 22:09:39 +00001459 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1460 Sema::DAR_Failed)
Richard Smith02e85f32011-04-14 22:09:26 +00001461 SemaRef.Diag(Loc, diag) << Init->getType();
1462 if (!InitTSI) {
1463 Decl->setInvalidDecl();
1464 return true;
1465 }
1466 Decl->setTypeSourceInfo(InitTSI);
1467 Decl->setType(InitTSI->getType());
1468
John McCall31168b02011-06-15 23:02:42 +00001469 // In ARC, infer lifetime.
1470 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1471 // we're doing the equivalent of fast iteration.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001472 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001473 SemaRef.inferObjCARCLifetime(Decl))
1474 Decl->setInvalidDecl();
1475
Richard Smith02e85f32011-04-14 22:09:26 +00001476 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1477 /*TypeMayContainAuto=*/false);
1478 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001479 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001480 return false;
1481}
1482
1483/// Produce a note indicating which begin/end function was implicitly called
1484/// by a C++0x for-range statement. This is often not obvious from the code,
1485/// nor from the diagnostics produced when analysing the implicit expressions
1486/// required in a for-range statement.
1487void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1488 BeginEndFunction BEF) {
1489 CallExpr *CE = dyn_cast<CallExpr>(E);
1490 if (!CE)
1491 return;
1492 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1493 if (!D)
1494 return;
1495 SourceLocation Loc = D->getLocation();
1496
1497 std::string Description;
1498 bool IsTemplate = false;
1499 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1500 Description = SemaRef.getTemplateArgumentBindingsText(
1501 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1502 IsTemplate = true;
1503 }
1504
1505 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1506 << BEF << IsTemplate << Description << E->getType();
1507}
1508
1509/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1510/// given LookupResult is non-empty, it is assumed to describe a member which
1511/// will be invoked. Otherwise, the function will be found via argument
1512/// dependent lookup.
1513static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1514 SourceLocation Loc,
1515 VarDecl *Decl,
1516 BeginEndFunction BEF,
1517 const DeclarationNameInfo &NameInfo,
1518 LookupResult &MemberLookup,
1519 Expr *Range) {
1520 ExprResult CallExpr;
1521 if (!MemberLookup.empty()) {
1522 ExprResult MemberRef =
1523 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1524 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001525 /*TemplateKWLoc=*/SourceLocation(),
1526 /*FirstQualifierInScope=*/0,
1527 MemberLookup,
Richard Smith02e85f32011-04-14 22:09:26 +00001528 /*TemplateArgs=*/0);
1529 if (MemberRef.isInvalid())
1530 return ExprError();
1531 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1532 Loc, 0);
1533 if (CallExpr.isInvalid())
1534 return ExprError();
1535 } else {
1536 UnresolvedSet<0> FoundNames;
1537 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1538 // std is an associated namespace.
1539 UnresolvedLookupExpr *Fn =
1540 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1541 NestedNameSpecifierLoc(), NameInfo,
1542 /*NeedsADL=*/true, /*Overloaded=*/false,
1543 FoundNames.begin(), FoundNames.end(),
1544 /*LookInStdNamespace=*/true);
1545 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00001546 0, /*AllowTypoCorrection=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001547 if (CallExpr.isInvalid()) {
1548 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1549 << Range->getType();
1550 return ExprError();
1551 }
1552 }
1553 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1554 diag::err_for_range_iter_deduction_failure)) {
1555 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1556 return ExprError();
1557 }
1558 return CallExpr;
1559}
1560
1561}
1562
1563/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1564///
1565/// C++0x [stmt.ranged]:
1566/// A range-based for statement is equivalent to
1567///
1568/// {
1569/// auto && __range = range-init;
1570/// for ( auto __begin = begin-expr,
1571/// __end = end-expr;
1572/// __begin != __end;
1573/// ++__begin ) {
1574/// for-range-declaration = *__begin;
1575/// statement
1576/// }
1577/// }
1578///
1579/// The body of the loop is not available yet, since it cannot be analysed until
1580/// we have determined the type of the for-range-declaration.
1581StmtResult
1582Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1583 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1584 SourceLocation RParenLoc) {
1585 if (!First || !Range)
1586 return StmtError();
1587
1588 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1589 assert(DS && "first part of for range not a decl stmt");
1590
1591 if (!DS->isSingleDecl()) {
1592 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1593 return StmtError();
1594 }
1595 if (DS->getSingleDecl()->isInvalidDecl())
1596 return StmtError();
1597
1598 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1599 return StmtError();
1600
1601 // Build auto && __range = range-init
1602 SourceLocation RangeLoc = Range->getLocStart();
1603 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1604 Context.getAutoRRefDeductType(),
1605 "__range");
1606 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1607 diag::err_for_range_deduction_failure))
1608 return StmtError();
1609
1610 // Claim the type doesn't contain auto: we've already done the checking.
1611 DeclGroupPtrTy RangeGroup =
1612 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1613 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1614 if (RangeDecl.isInvalid())
1615 return StmtError();
1616
1617 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1618 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1619 RParenLoc);
1620}
1621
1622/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1623StmtResult
1624Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1625 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1626 Expr *Inc, Stmt *LoopVarDecl,
1627 SourceLocation RParenLoc) {
1628 Scope *S = getCurScope();
1629
1630 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1631 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1632 QualType RangeVarType = RangeVar->getType();
1633
1634 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1635 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1636
1637 StmtResult BeginEndDecl = BeginEnd;
1638 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1639
1640 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1641 SourceLocation RangeLoc = RangeVar->getLocation();
1642
Ted Kremenekbed648e2011-10-10 22:36:28 +00001643 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1644
1645 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1646 VK_LValue, ColonLoc);
1647 if (BeginRangeRef.isInvalid())
1648 return StmtError();
1649
1650 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1651 VK_LValue, ColonLoc);
1652 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00001653 return StmtError();
1654
1655 QualType AutoType = Context.getAutoDeductType();
1656 Expr *Range = RangeVar->getInit();
1657 if (!Range)
1658 return StmtError();
1659 QualType RangeType = Range->getType();
1660
1661 if (RequireCompleteType(RangeLoc, RangeType,
1662 PDiag(diag::err_for_range_incomplete_type)))
1663 return StmtError();
1664
1665 // Build auto __begin = begin-expr, __end = end-expr.
1666 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1667 "__begin");
1668 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1669 "__end");
1670
1671 // Build begin-expr and end-expr and attach to __begin and __end variables.
1672 ExprResult BeginExpr, EndExpr;
1673 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1674 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1675 // __range + __bound, respectively, where __bound is the array bound. If
1676 // _RangeT is an array of unknown size or an array of incomplete type,
1677 // the program is ill-formed;
1678
1679 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001680 BeginExpr = BeginRangeRef;
1681 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001682 diag::err_for_range_iter_deduction_failure)) {
1683 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1684 return StmtError();
1685 }
1686
1687 // Find the array bound.
1688 ExprResult BoundExpr;
1689 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1690 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001691 Context.getPointerDiffType(),
1692 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001693 else if (const VariableArrayType *VAT =
1694 dyn_cast<VariableArrayType>(UnqAT))
1695 BoundExpr = VAT->getSizeExpr();
1696 else {
1697 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1698 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00001699 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00001700 }
1701
1702 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001703 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00001704 BoundExpr.get());
1705 if (EndExpr.isInvalid())
1706 return StmtError();
1707 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1708 diag::err_for_range_iter_deduction_failure)) {
1709 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1710 return StmtError();
1711 }
1712 } else {
1713 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1714 ColonLoc);
1715 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1716 ColonLoc);
1717
1718 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1719 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1720
1721 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1722 // - if _RangeT is a class type, the unqualified-ids begin and end are
1723 // looked up in the scope of class _RangeT as if by class member access
1724 // lookup (3.4.5), and if either (or both) finds at least one
1725 // declaration, begin-expr and end-expr are __range.begin() and
1726 // __range.end(), respectively;
1727 LookupQualifiedName(BeginMemberLookup, D);
1728 LookupQualifiedName(EndMemberLookup, D);
1729
1730 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1731 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1732 << RangeType << BeginMemberLookup.empty();
1733 return StmtError();
1734 }
1735 } else {
1736 // - otherwise, begin-expr and end-expr are begin(__range) and
1737 // end(__range), respectively, where begin and end are looked up with
1738 // argument-dependent lookup (3.4.2). For the purposes of this name
1739 // lookup, namespace std is an associated namespace.
1740 }
1741
1742 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1743 BEF_begin, BeginNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001744 BeginMemberLookup,
1745 BeginRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001746 if (BeginExpr.isInvalid())
1747 return StmtError();
1748
1749 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1750 BEF_end, EndNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001751 EndMemberLookup, EndRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001752 if (EndExpr.isInvalid())
1753 return StmtError();
1754 }
1755
1756 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1757 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1758 if (!Context.hasSameType(BeginType, EndType)) {
1759 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1760 << BeginType << EndType;
1761 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1762 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1763 }
1764
1765 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1766 // Claim the type doesn't contain auto: we've already done the checking.
1767 DeclGroupPtrTy BeginEndGroup =
1768 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1769 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1770
Ted Kremenekbed648e2011-10-10 22:36:28 +00001771 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1772 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00001773 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001774 if (BeginRef.isInvalid())
1775 return StmtError();
1776
Richard Smith02e85f32011-04-14 22:09:26 +00001777 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1778 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001779 if (EndRef.isInvalid())
1780 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00001781
1782 // Build and check __begin != __end expression.
1783 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1784 BeginRef.get(), EndRef.get());
1785 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1786 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1787 if (NotEqExpr.isInvalid()) {
1788 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1789 if (!Context.hasSameType(BeginType, EndType))
1790 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1791 return StmtError();
1792 }
1793
1794 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001795 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1796 VK_LValue, ColonLoc);
1797 if (BeginRef.isInvalid())
1798 return StmtError();
1799
Richard Smith02e85f32011-04-14 22:09:26 +00001800 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1801 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1802 if (IncrExpr.isInvalid()) {
1803 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1804 return StmtError();
1805 }
1806
1807 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001808 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1809 VK_LValue, ColonLoc);
1810 if (BeginRef.isInvalid())
1811 return StmtError();
1812
Richard Smith02e85f32011-04-14 22:09:26 +00001813 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1814 if (DerefExpr.isInvalid()) {
1815 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1816 return StmtError();
1817 }
1818
1819 // Attach *__begin as initializer for VD.
1820 if (!LoopVar->isInvalidDecl()) {
1821 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1822 /*TypeMayContainAuto=*/true);
1823 if (LoopVar->isInvalidDecl())
1824 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1825 }
Richard Smithf9603352011-06-21 23:07:19 +00001826 } else {
1827 // The range is implicitly used as a placeholder when it is dependent.
1828 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00001829 }
1830
1831 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1832 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1833 NotEqExpr.take(), IncrExpr.take(),
1834 LoopVarDS, /*Body=*/0, ForLoc,
1835 ColonLoc, RParenLoc));
1836}
1837
1838/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1839/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1840/// body cannot be performed until after the type of the range variable is
1841/// determined.
1842StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1843 if (!S || !B)
1844 return StmtError();
1845
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001846 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1847 ForStmt->setBody(B);
1848
1849 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1850 diag::warn_empty_range_based_for_body);
1851
Richard Smith02e85f32011-04-14 22:09:26 +00001852 return S;
1853}
1854
Chris Lattnercab02a62011-02-17 20:34:02 +00001855StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1856 SourceLocation LabelLoc,
1857 LabelDecl *TheDecl) {
1858 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001859 TheDecl->setUsed();
1860 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001861}
Chris Lattner1c310502007-05-31 06:00:00 +00001862
John McCalldadc5752010-08-24 06:29:42 +00001863StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001864Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001865 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001866 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001867 if (!E->isTypeDependent()) {
1868 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001869 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001870 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001871 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001872 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1873 if (ExprRes.isInvalid())
1874 return StmtError();
1875 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001876 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001877 return StmtError();
Eli Friedman9ccdb1d2012-01-31 22:47:07 +00001878 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001879 }
John McCalla95172b2010-08-01 00:26:45 +00001880
John McCallaab3e412010-08-25 08:40:02 +00001881 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001882
Douglas Gregor30776d42009-05-16 00:20:29 +00001883 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001884}
1885
John McCalldadc5752010-08-24 06:29:42 +00001886StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001887Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001888 Scope *S = CurScope->getContinueParent();
1889 if (!S) {
1890 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001891 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001892 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001893
Ted Kremenek5a201952009-02-07 01:47:29 +00001894 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001895}
1896
John McCalldadc5752010-08-24 06:29:42 +00001897StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001898Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001899 Scope *S = CurScope->getBreakParent();
1900 if (!S) {
1901 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001902 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001903 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001904
Ted Kremenek5a201952009-02-07 01:47:29 +00001905 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001906}
1907
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001909/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001910///
Douglas Gregor5d369002011-01-21 18:05:27 +00001911/// \param ReturnType If we're determining the copy elision candidate for
1912/// a return statement, this is the return type of the function. If we're
1913/// determining the copy elision candidate for a throw expression, this will
1914/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001915///
Douglas Gregor5d369002011-01-21 18:05:27 +00001916/// \param E The expression being returned from the function or block, or
1917/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001918///
Douglas Gregor86394412011-05-20 15:00:53 +00001919/// \param AllowFunctionParameter Whether we allow function parameters to
1920/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1921/// we re-use this logic to determine whether we should try to move as part of
1922/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001923///
1924/// \returns The NRVO candidate variable, if the return statement may use the
1925/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001926const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1927 Expr *E,
1928 bool AllowFunctionParameter) {
1929 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001930 // - in a return statement in a function with ...
1931 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001932 if (!ReturnType.isNull()) {
1933 if (!ReturnType->isRecordType())
1934 return 0;
1935 // ... the same cv-unqualified type as the function return type ...
1936 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1937 return 0;
1938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
1940 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00001941 // (other than a function or catch-clause parameter)) ...
1942 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001943 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001944 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001945 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1946 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001947 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
John McCall03318c12011-11-11 03:57:31 +00001949 // ...object (other than a function or catch-clause parameter)...
1950 if (VD->getKind() != Decl::Var &&
1951 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
1952 return 0;
1953 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
John McCall03318c12011-11-11 03:57:31 +00001955 // ...automatic...
1956 if (!VD->hasLocalStorage()) return 0;
1957
1958 // ...non-volatile...
1959 if (VD->getType().isVolatileQualified()) return 0;
1960 if (VD->getType()->isReferenceType()) return 0;
1961
1962 // __block variables can't be allocated in a way that permits NRVO.
1963 if (VD->hasAttr<BlocksAttr>()) return 0;
1964
1965 // Variables with higher required alignment than their type's ABI
1966 // alignment cannot use NRVO.
1967 if (VD->hasAttr<AlignedAttr>() &&
1968 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
1969 return 0;
1970
1971 return VD;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001972}
1973
Douglas Gregor626fbed2011-01-21 21:08:57 +00001974/// \brief Perform the initialization of a potentially-movable value, which
1975/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00001976///
1977/// This routine implements C++0x [class.copy]p33, which attempts to treat
1978/// returned lvalues as rvalues in certain cases (to prefer move construction),
1979/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00001981Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1982 const VarDecl *NRVOCandidate,
1983 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001984 Expr *Value,
1985 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001986 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987 // When the criteria for elision of a copy operation are met or would
1988 // be met save for the fact that the source object is a function
1989 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00001990 // overload resolution to select the constructor for the copy is first
1991 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00001992 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001993 if (AllowNRVO &&
1994 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001996 Value->getType(), CK_LValueToRValue,
1997 Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998
Douglas Gregorf282a762011-01-21 19:38:21 +00001999 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002001 = InitializationKind::CreateCopy(Value->getLocStart(),
2002 Value->getLocStart());
2003 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
2005 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002006 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002007 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002008 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002009 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002010 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2011 StepEnd = Seq.step_end();
2012 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002013 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002014 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
2016 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002017 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018
Douglas Gregorf282a762011-01-21 19:38:21 +00002019 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002020 = Constructor->getParamDecl(0)->getType()
2021 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022
Douglas Gregorf282a762011-01-21 19:38:21 +00002023 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002025 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2026 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002027 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028
Douglas Gregorf282a762011-01-21 19:38:21 +00002029 // Promote "AsRvalue" to the heap, since we now need this
2030 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002031 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032 CK_LValueToRValue, Value, 0,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002033 VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
Douglas Gregorf282a762011-01-21 19:38:21 +00002035 // Complete type-checking the initialization of the return type
2036 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002037 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00002038 }
2039 }
2040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002041
Douglas Gregorf282a762011-01-21 19:38:21 +00002042 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002044 // (again) now with the return value expression as written.
2045 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002046 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Douglas Gregorf282a762011-01-21 19:38:21 +00002048 return Res;
2049}
2050
Eli Friedman34b49062012-01-26 03:00:14 +00002051/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2052/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002053///
John McCalldadc5752010-08-24 06:29:42 +00002054StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002055Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2056 // If this is the first return we've seen, infer the return type.
2057 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2058 // rules which allows multiple return statements.
2059 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2060 if (CurCap->HasImplicitReturnType) {
2061 QualType ReturnT;
Douglas Gregor940a5502012-02-09 18:40:39 +00002062 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002063 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2064 if (Result.isInvalid())
2065 return StmtError();
2066 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002067
Eli Friedman34b49062012-01-26 03:00:14 +00002068 if (!RetValExp->isTypeDependent())
2069 ReturnT = RetValExp->getType();
2070 else
2071 ReturnT = Context.DependentTy;
Douglas Gregor940a5502012-02-09 18:40:39 +00002072 } else {
2073 if (RetValExp) {
2074 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2075 // initializer list, because it is not an expression (even
2076 // though we represent it as one). We still deduce 'void'.
2077 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2078 << RetValExp->getSourceRange();
2079 }
2080
Eli Friedman34b49062012-01-26 03:00:14 +00002081 ReturnT = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002082 }
Eli Friedman34b49062012-01-26 03:00:14 +00002083 // We require the return types to strictly match here.
2084 if (!CurCap->ReturnType.isNull() &&
2085 !CurCap->ReturnType->isDependentType() &&
2086 !ReturnT->isDependentType() &&
2087 !Context.hasSameType(ReturnT, CurCap->ReturnType)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002088 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Douglas Gregorb9e38f12012-02-15 15:57:22 +00002089 << ReturnT << CurCap->ReturnType
Douglas Gregor85dae8922012-02-15 15:59:09 +00002090 << (getCurLambda() != 0);
Eli Friedman34b49062012-01-26 03:00:14 +00002091 return StmtError();
2092 }
2093 CurCap->ReturnType = ReturnT;
Steve Naroffc540d662008-09-03 18:15:37 +00002094 }
Eli Friedman34b49062012-01-26 03:00:14 +00002095 QualType FnRetType = CurCap->ReturnType;
2096 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002097
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002098 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002099 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2100 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2101 return StmtError();
2102 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002103 } else {
2104 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2105 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2106 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2107 return StmtError();
2108 }
2109 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002110
Steve Naroffc540d662008-09-03 18:15:37 +00002111 // Otherwise, verify that this result type matches the previous one. We are
2112 // pickier with blocks than for normal functions because we don't have GCC
2113 // compatibility to worry about here.
John McCall75f92b52011-08-17 21:34:14 +00002114 const VarDecl *NRVOCandidate = 0;
John McCall5500ef22011-08-17 22:09:46 +00002115 if (FnRetType->isDependentType()) {
2116 // Delay processing for now. TODO: there are lots of dependent
2117 // types we can conclusively prove aren't void.
2118 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002119 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002121 (RetValExp->isTypeDependent() ||
2122 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002123 if (!getLangOpts().CPlusPlus &&
2124 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002125 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002126 else {
2127 Diag(ReturnLoc, diag::err_return_block_has_expr);
2128 RetValExp = 0;
2129 }
Steve Naroffc540d662008-09-03 18:15:37 +00002130 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002131 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002132 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2133 } else if (!RetValExp->isTypeDependent()) {
2134 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002135
John McCall5500ef22011-08-17 22:09:46 +00002136 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2137 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2138 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002139
John McCall5500ef22011-08-17 22:09:46 +00002140 // In C++ the return statement is handled via a copy initialization.
2141 // the C version of which boils down to CheckSingleAssignmentConstraints.
2142 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2143 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2144 FnRetType,
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00002145 NRVOCandidate != 0);
John McCall5500ef22011-08-17 22:09:46 +00002146 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2147 FnRetType, RetValExp);
2148 if (Res.isInvalid()) {
2149 // FIXME: Cleanup temporaries here, anyway?
2150 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002151 }
John McCall5500ef22011-08-17 22:09:46 +00002152 RetValExp = Res.take();
2153 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +00002154 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002155
John McCall75f92b52011-08-17 21:34:14 +00002156 if (RetValExp) {
2157 CheckImplicitConversions(RetValExp, ReturnLoc);
2158 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2159 }
John McCall5500ef22011-08-17 22:09:46 +00002160 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2161 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002162
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002164 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002165 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002166 !CurContext->isDependentContext())
2167 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002169 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00002170}
Chris Lattneraf8d5812006-11-10 05:07:45 +00002171
John McCalldadc5752010-08-24 06:29:42 +00002172StmtResult
John McCallb268a282010-08-23 23:25:46 +00002173Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002174 // Check for unexpanded parameter packs.
2175 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2176 return StmtError();
2177
Eli Friedman34b49062012-01-26 03:00:14 +00002178 if (isa<CapturingScopeInfo>(getCurFunction()))
2179 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00002180
Chris Lattner79413952008-12-04 23:50:19 +00002181 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002182 QualType RelatedRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002183 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00002184 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00002185 if (FD->hasAttr<NoReturnAttr>() ||
2186 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00002187 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002188 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002189 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman410fc7a2012-03-30 01:13:43 +00002190 FnRetType = MD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00002191 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2192 // In the implementation of a method with a related return type, the
2193 // type used to type-check the validity of return statements within the
2194 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002195 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2196 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002197 }
2198 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002199 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002200
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002201 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002202 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002203 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002204 if (isa<InitListExpr>(RetValExp)) {
2205 // We simply never allow init lists as the return value of void
2206 // functions. This is compatible because this was never allowed before,
2207 // so there's no legacy code to deal with.
2208 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2209 int FunctionKind = 0;
2210 if (isa<ObjCMethodDecl>(CurDecl))
2211 FunctionKind = 1;
2212 else if (isa<CXXConstructorDecl>(CurDecl))
2213 FunctionKind = 2;
2214 else if (isa<CXXDestructorDecl>(CurDecl))
2215 FunctionKind = 3;
2216
2217 Diag(ReturnLoc, diag::err_return_init_list)
2218 << CurDecl->getDeclName() << FunctionKind
2219 << RetValExp->getSourceRange();
2220
2221 // Drop the expression.
2222 RetValExp = 0;
2223 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002224 // C99 6.8.6.4p1 (ext_ since GCC warns)
2225 unsigned D = diag::ext_return_has_expr;
2226 if (RetValExp->getType()->isVoidType())
2227 D = diag::ext_return_has_void_expr;
2228 else {
2229 ExprResult Result = Owned(RetValExp);
2230 Result = IgnoredValueConversions(Result.take());
2231 if (Result.isInvalid())
2232 return StmtError();
2233 RetValExp = Result.take();
2234 RetValExp = ImpCastExprToType(RetValExp,
2235 Context.VoidTy, CK_ToVoid).take();
2236 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002237
Nick Lewycky1be750a2011-06-01 07:44:31 +00002238 // return (some void expression); is legal in C++.
2239 if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002240 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002241 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002242
2243 int FunctionKind = 0;
2244 if (isa<ObjCMethodDecl>(CurDecl))
2245 FunctionKind = 1;
2246 else if (isa<CXXConstructorDecl>(CurDecl))
2247 FunctionKind = 2;
2248 else if (isa<CXXDestructorDecl>(CurDecl))
2249 FunctionKind = 3;
2250
Nick Lewycky1be750a2011-06-01 07:44:31 +00002251 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002252 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002253 << RetValExp->getSourceRange();
2254 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002255 }
Mike Stump11289f42009-09-09 15:08:12 +00002256
Sebastian Redleef474c2012-02-22 10:50:08 +00002257 if (RetValExp) {
2258 CheckImplicitConversions(RetValExp, ReturnLoc);
2259 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2260 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002263 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2264 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002265 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2266 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002267 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002268
2269 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002270 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002271 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002272 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002273 Result = new (Context) ReturnStmt(ReturnLoc);
2274 } else {
2275 const VarDecl *NRVOCandidate = 0;
2276 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2277 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002278
Eli Friedman410fc7a2012-03-30 01:13:43 +00002279 if (!RelatedRetType.isNull()) {
2280 // If we have a related result type, perform an extra conversion here.
2281 // FIXME: The diagnostics here don't really describe what is happening.
2282 InitializedEntity Entity =
2283 InitializedEntity::InitializeTemporary(RelatedRetType);
2284
2285 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2286 RetValExp);
2287 if (Res.isInvalid()) {
2288 // FIXME: Cleanup temporaries here, anyway?
2289 return StmtError();
2290 }
2291 RetValExp = Res.takeAs<Expr>();
2292 }
2293
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002294 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2295 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2296 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002297
John McCallfa272342011-06-16 23:24:51 +00002298 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002299 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00002300 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002302 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00002303 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002305 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002306 if (Res.isInvalid()) {
2307 // FIXME: Cleanup temporaries here, anyway?
2308 return StmtError();
2309 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002310
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002311 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002312 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002313 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002315
John McCallacf0ee52010-10-08 02:01:28 +00002316 if (RetValExp) {
2317 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00002318 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00002319 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002320 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00002321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002322
2323 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002324 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002325 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002326 !CurContext->isDependentContext())
2327 FunctionScopes.back()->Returns.push_back(Result);
John McCall31168b02011-06-15 23:02:42 +00002328
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002329 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002330}
2331
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002332/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2333/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2334/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2335/// provide a strong guidance to not use it.
2336///
2337/// This method checks to see if the argument is an acceptable l-value and
2338/// returns false if it is a case we can handle.
2339static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00002340 // Type dependent expressions will be checked during instantiation.
2341 if (E->isTypeDependent())
2342 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002343
John McCall086a4642010-11-24 05:12:34 +00002344 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002345 return false; // Cool, this is an lvalue.
2346
2347 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2348 // are supposed to allow.
2349 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00002350 if (E != E2 && E2->isLValue()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002351 if (!S.getLangOpts().HeinousExtensions)
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002352 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2353 << E->getSourceRange();
2354 else
2355 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2356 << E->getSourceRange();
2357 // Accept, even if we emitted an error diagnostic.
2358 return false;
2359 }
2360
2361 // None of the above, just randomly invalid non-lvalue.
2362 return true;
2363}
2364
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002365/// isOperandMentioned - Return true if the specified operand # is mentioned
2366/// anywhere in the decomposed asm string.
2367static bool isOperandMentioned(unsigned OpNo,
Chris Lattner54b16772011-07-23 17:14:25 +00002368 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002369 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2370 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2371 if (!Piece.isOperand()) continue;
2372
2373 // If this is a reference to the input and if the input was the smaller
2374 // one, then we have to reject this asm.
2375 if (Piece.getOperandNo() == OpNo)
2376 return true;
2377 }
2378
2379 return false;
2380}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002381
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002382StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2383 bool IsVolatile, unsigned NumOutputs,
2384 unsigned NumInputs, IdentifierInfo **Names,
2385 MultiExprArg constraints, MultiExprArg exprs,
2386 Expr *asmString, MultiExprArg clobbers,
2387 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002388 unsigned NumClobbers = clobbers.size();
2389 StringLiteral **Constraints =
2390 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00002391 Expr **Exprs = exprs.get();
2392 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00002393 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2394
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002395 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chris Lattner496acc12008-08-18 19:55:17 +00002397 // The parser verifies that there is a string literal here.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002398 if (!AsmString->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002399 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2400 << AsmString->getSourceRange());
2401
Chris Lattner496acc12008-08-18 19:55:17 +00002402 for (unsigned i = 0; i != NumOutputs; i++) {
2403 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002404 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002405 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2406 << Literal->getSourceRange());
2407
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002408 StringRef OutputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002409 if (Names[i])
2410 OutputName = Names[i]->getName();
2411
2412 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002413 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002414 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002415 diag::err_asm_invalid_output_constraint)
2416 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00002417
Anders Carlssonf511f642007-11-27 04:11:28 +00002418 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00002419 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002420 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00002421 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002422 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00002423 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Chris Lattnerd9725f72009-04-26 07:16:29 +00002426 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002427 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002428
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002429 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner34b51e82009-05-03 05:55:43 +00002430
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002431 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00002432 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002433 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002434 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2435 << Literal->getSourceRange());
2436
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002437 StringRef InputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002438 if (Names[i])
2439 InputName = Names[i]->getName();
2440
2441 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002442 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00002443 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002444 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002445 diag::err_asm_invalid_input_constraint)
2446 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00002447 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002448
Eli Friedman47e78572009-05-03 07:49:42 +00002449 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00002450
Anders Carlsson224fca82009-01-20 20:49:22 +00002451 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00002452 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002453 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00002454 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002455 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002456 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002457 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002458 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002459
Chris Lattnerd9725f72009-04-26 07:16:29 +00002460 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00002461 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00002462 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002463 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00002464 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002465 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00002466 }
Anders Carlsson224fca82009-01-20 20:49:22 +00002467 }
Mike Stump11289f42009-09-09 15:08:12 +00002468
John Wiegley01296292011-04-08 18:41:53 +00002469 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2470 if (Result.isInvalid())
2471 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002472
John Wiegley01296292011-04-08 18:41:53 +00002473 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00002474 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002475 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002476
Anders Carlsson290aa852007-11-25 00:25:21 +00002477 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00002478 for (unsigned i = 0; i != NumClobbers; i++) {
2479 StringLiteral *Literal = Clobbers[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002480 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002481 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2482 << Literal->getSourceRange());
2483
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002484 StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00002485
Douglas Gregore8bbc122011-09-02 00:18:52 +00002486 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002487 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00002488 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00002489 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002490
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002491 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002492 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2493 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00002494 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002495 // Validate the asm string, ensuring it makes sense given the operands we
2496 // have.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002497 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002498 unsigned DiagOffs;
2499 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00002500 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2501 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002502 return StmtError();
2503 }
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chris Lattner34b51e82009-05-03 05:55:43 +00002505 // Validate tied input operands for type mismatches.
2506 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2507 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattner34b51e82009-05-03 05:55:43 +00002509 // If this is a tied constraint, verify that the output and input have
2510 // either exactly the same type, or that they are int/ptr operands with the
2511 // same size (int/long, int*/long, are ok etc).
2512 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00002513
Chris Lattner34b51e82009-05-03 05:55:43 +00002514 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00002515 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00002516 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00002517 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedman8eac6c22011-09-14 19:20:00 +00002518
2519 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2520 continue;
2521
Chris Lattner2c295cf2009-05-03 05:59:17 +00002522 QualType InTy = InputExpr->getType();
2523 QualType OutTy = OutputExpr->getType();
2524 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00002525 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00002526
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002527 // Decide if the input and output are in the same domain (integer/ptr or
2528 // floating point.
2529 enum AsmDomain {
2530 AD_Int, AD_FP, AD_Other
2531 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002533 if (InTy->isIntegerType() || InTy->isPointerType())
2534 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002535 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002536 InputDomain = AD_FP;
2537 else
2538 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00002539
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002540 if (OutTy->isIntegerType() || OutTy->isPointerType())
2541 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002542 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002543 OutputDomain = AD_FP;
2544 else
2545 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002546
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002547 // They are ok if they are the same size and in the same domain. This
2548 // allows tying things like:
2549 // void* to int*
2550 // void* to int if they are the same size.
2551 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002553 uint64_t OutSize = Context.getTypeSize(OutTy);
2554 uint64_t InSize = Context.getTypeSize(InTy);
2555 if (OutSize == InSize && InputDomain == OutputDomain &&
2556 InputDomain != AD_Other)
2557 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002558
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002559 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00002560 // then we can promote the smaller one to a larger input and the asm string
2561 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002562 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002563
2564 // If this is a reference to the input and if the input was the smaller
2565 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00002566 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002567 // This is a use in the asm string of the smaller operand. Since we
2568 // codegen this by promoting to a wider value, the asm will get printed
2569 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00002570 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002571 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002572 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002573 // If this is a reference to the output, and if the output is the larger
2574 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002575 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002576 }
Mike Stump11289f42009-09-09 15:08:12 +00002577
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002578 // If the smaller value wasn't mentioned in the asm string, and if the
2579 // output was a register, just extend the shorter one to the size of the
2580 // larger one.
2581 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2582 OutputConstraintInfos[TiedTo].allowsRegister())
2583 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00002584
Chris Lattner93ede022011-02-21 22:09:29 +00002585 // Either both of the operands were mentioned or the smaller one was
2586 // mentioned. One more special case that we'll allow: if the tied input is
2587 // integer, unmentioned, and is a constant, then we'll allow truncating it
2588 // down to the size of the destination.
2589 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2590 !isOperandMentioned(InputOpNo, Pieces) &&
2591 InputExpr->isEvaluatable(Context)) {
John McCalldfbf9342011-05-10 23:39:47 +00002592 CastKind castKind =
2593 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2594 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002595 Exprs[InputOpNo] = InputExpr;
2596 NS->setInputExpr(i, InputExpr);
2597 continue;
2598 }
2599
Chris Lattner28b05c82009-05-03 06:50:40 +00002600 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002601 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002602 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002603 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002604 return StmtError();
2605 }
Mike Stump11289f42009-09-09 15:08:12 +00002606
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002607 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002608}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002609
John McCalldadc5752010-08-24 06:29:42 +00002610StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002611Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002612 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002613 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002614 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002615 if (Var && Var->isInvalidDecl())
2616 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617
John McCallb268a282010-08-23 23:25:46 +00002618 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002619}
2620
John McCalldadc5752010-08-24 06:29:42 +00002621StmtResult
John McCallb268a282010-08-23 23:25:46 +00002622Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2623 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002624}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002625
John McCalldadc5752010-08-24 06:29:42 +00002626StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002627Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002628 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002629 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002630 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2631
John McCallaab3e412010-08-25 08:40:02 +00002632 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002633 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002634 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2635 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002636 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002637 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002638}
2639
John McCalldadc5752010-08-24 06:29:42 +00002640StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCallb268a282010-08-23 23:25:46 +00002641 Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002642 if (Throw) {
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002643 Throw = MaybeCreateExprWithCleanups(Throw);
John Wiegley01296292011-04-08 18:41:53 +00002644 ExprResult Result = DefaultLvalueConversion(Throw);
2645 if (Result.isInvalid())
2646 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002647
John Wiegley01296292011-04-08 18:41:53 +00002648 Throw = Result.take();
Douglas Gregor2900c162010-04-22 21:44:01 +00002649 QualType ThrowType = Throw->getType();
2650 // Make sure the expression type is an ObjC pointer or "void *".
2651 if (!ThrowType->isDependentType() &&
2652 !ThrowType->isObjCObjectPointerType()) {
2653 const PointerType *PT = ThrowType->getAs<PointerType>();
2654 if (!PT || !PT->getPointeeType()->isVoidType())
2655 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2656 << Throw->getType() << Throw->getSourceRange());
2657 }
2658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002659
John McCallb268a282010-08-23 23:25:46 +00002660 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002661}
2662
John McCalldadc5752010-08-24 06:29:42 +00002663StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002665 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002666 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002667 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2668
John McCallb268a282010-08-23 23:25:46 +00002669 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002670 // @throw without an expression designates a rethrow (which much occur
2671 // in the context of an @catch clause).
2672 Scope *AtCatchParent = CurScope;
2673 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2674 AtCatchParent = AtCatchParent->getParent();
2675 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002676 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 }
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002678
John McCallb268a282010-08-23 23:25:46 +00002679 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002680}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002681
John McCalld9bb7432011-07-27 21:50:02 +00002682ExprResult
2683Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2684 ExprResult result = DefaultLvalueConversion(operand);
2685 if (result.isInvalid())
2686 return ExprError();
2687 operand = result.take();
2688
2689 // Make sure the expression type is an ObjC pointer or "void *".
2690 QualType type = operand->getType();
2691 if (!type->isDependentType() &&
2692 !type->isObjCObjectPointerType()) {
2693 const PointerType *pointerType = type->getAs<PointerType>();
2694 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2695 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2696 << type << operand->getSourceRange();
2697 }
2698
2699 // The operand to @synchronized is a full-expression.
2700 return MaybeCreateExprWithCleanups(operand);
2701}
2702
John McCalldadc5752010-08-24 06:29:42 +00002703StmtResult
John McCallb268a282010-08-23 23:25:46 +00002704Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2705 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00002706 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00002707 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00002708 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002709}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002710
2711/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2712/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002713StmtResult
John McCall48871652010-08-21 09:40:31 +00002714Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002715 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002716 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002717 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002718 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002719 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002720}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002721
John McCall31168b02011-06-15 23:02:42 +00002722StmtResult
2723Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2724 getCurFunction()->setHasBranchProtectedScope();
2725 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2726}
2727
Dan Gohman28ade552010-07-26 21:25:24 +00002728namespace {
2729
Sebastian Redl63c4da02009-07-29 17:15:45 +00002730class TypeWithHandler {
2731 QualType t;
2732 CXXCatchStmt *stmt;
2733public:
2734 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2735 : t(type), stmt(statement) {}
2736
John McCall8ccfcb52009-09-24 19:53:00 +00002737 // An arbitrary order is fine as long as it places identical
2738 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002739 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002740 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002741 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002742 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002743 return false;
2744 else
2745 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2746 }
Mike Stump11289f42009-09-09 15:08:12 +00002747
Sebastian Redl63c4da02009-07-29 17:15:45 +00002748 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002749 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002750 }
Mike Stump11289f42009-09-09 15:08:12 +00002751
Sebastian Redl63c4da02009-07-29 17:15:45 +00002752 CXXCatchStmt *getCatchStmt() const { return stmt; }
2753 SourceLocation getTypeSpecStartLoc() const {
2754 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2755 }
2756};
2757
Dan Gohman28ade552010-07-26 21:25:24 +00002758}
2759
Sebastian Redl9b244a82008-12-22 21:35:02 +00002760/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2761/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002762StmtResult
John McCallb268a282010-08-23 23:25:46 +00002763Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002764 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002765 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002766 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002767 !getSourceManager().isInSystemHeader(TryLoc))
2768 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002769
Sebastian Redl9b244a82008-12-22 21:35:02 +00002770 unsigned NumHandlers = RawHandlers.size();
2771 assert(NumHandlers > 0 &&
2772 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00002773 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002774
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002775 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002776
2777 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002778 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002779 if (!Handler->getExceptionDecl()) {
2780 if (i < NumHandlers - 1)
2781 return StmtError(Diag(Handler->getLocStart(),
2782 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002783
Sebastian Redl63c4da02009-07-29 17:15:45 +00002784 continue;
2785 }
Mike Stump11289f42009-09-09 15:08:12 +00002786
Sebastian Redl63c4da02009-07-29 17:15:45 +00002787 const QualType CaughtType = Handler->getCaughtType();
2788 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2789 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002790 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002791
2792 // Detect handlers for the same type as an earlier one.
2793 if (NumHandlers > 1) {
2794 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002795
Sebastian Redl63c4da02009-07-29 17:15:45 +00002796 TypeWithHandler prev = TypesWithHandlers[0];
2797 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2798 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002799
Sebastian Redl63c4da02009-07-29 17:15:45 +00002800 if (curr == prev) {
2801 Diag(curr.getTypeSpecStartLoc(),
2802 diag::warn_exception_caught_by_earlier_handler)
2803 << curr.getCatchStmt()->getCaughtType().getAsString();
2804 Diag(prev.getTypeSpecStartLoc(),
2805 diag::note_previous_exception_handler)
2806 << prev.getCatchStmt()->getCaughtType().getAsString();
2807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808
Sebastian Redl63c4da02009-07-29 17:15:45 +00002809 prev = curr;
2810 }
2811 }
Mike Stump11289f42009-09-09 15:08:12 +00002812
John McCallaab3e412010-08-25 08:40:02 +00002813 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002814
Sebastian Redl9b244a82008-12-22 21:35:02 +00002815 // FIXME: We should detect handlers that cannot catch anything because an
2816 // earlier handler catches a superclass. Need to find a method that is not
2817 // quadratic for this.
2818 // Neither of these are explicitly forbidden, but every compiler detects them
2819 // and warns.
2820
John McCallb268a282010-08-23 23:25:46 +00002821 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002822 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002823}
John Wiegley1c0675e2011-04-28 01:08:34 +00002824
2825StmtResult
2826Sema::ActOnSEHTryBlock(bool IsCXXTry,
2827 SourceLocation TryLoc,
2828 Stmt *TryBlock,
2829 Stmt *Handler) {
2830 assert(TryBlock && Handler);
2831
2832 getCurFunction()->setHasBranchProtectedScope();
2833
2834 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2835}
2836
2837StmtResult
2838Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2839 Expr *FilterExpr,
2840 Stmt *Block) {
2841 assert(FilterExpr && Block);
2842
2843 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00002844 return StmtError(Diag(FilterExpr->getExprLoc(),
2845 diag::err_filter_expression_integral)
2846 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00002847 }
2848
2849 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2850}
2851
2852StmtResult
2853Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2854 Stmt *Block) {
2855 assert(Block);
2856 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2857}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002858
2859StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2860 bool IsIfExists,
2861 NestedNameSpecifierLoc QualifierLoc,
2862 DeclarationNameInfo NameInfo,
2863 Stmt *Nested)
2864{
2865 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2866 QualifierLoc, NameInfo,
2867 cast<CompoundStmt>(Nested));
2868}
2869
2870
2871StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2872 bool IsIfExists,
2873 CXXScopeSpec &SS,
2874 UnqualifiedId &Name,
2875 Stmt *Nested) {
2876 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2877 SS.getWithLocInContext(Context),
2878 GetNameFromUnqualifiedId(Name),
2879 Nested);
2880}