blob: 8303616db4c3f84df739d230dce7e97eab5b1aaa [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"
Anders Carlsson59689ed2008-11-22 21:04:56 +000019#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000027#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000028#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000029#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000032using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000033using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000034
John McCalldadc5752010-08-24 06:29:42 +000035StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000036 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000037 if (!E) // FIXME: FullExprArg has no error state?
38 return StmtError();
39
Chris Lattner903eb512008-07-25 23:18:17 +000040 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41 // void expression for its side effects. Conversion to void allows any
42 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000043
Chris Lattner903eb512008-07-25 23:18:17 +000044 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000045 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000046}
47
48
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000049StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
50 SourceLocation LeadingEmptyMacroLoc) {
51 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacroLoc));
Chris Lattner0f203a72007-05-28 01:45:28 +000052}
53
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000054StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
55 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000056 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000057
Chris Lattnercbafe8d2009-04-12 20:13:14 +000058 // If we have an invalid decl, just return an error.
59 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattner34a22092009-03-04 04:23:07 +000061 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000062}
Chris Lattneraf8d5812006-11-10 05:07:45 +000063
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000064void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000066
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000067 // If we have an invalid decl, just return.
68 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000069 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
70
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000071 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000072 var->setUsed();
73
John McCalld4631322011-06-17 06:42:21 +000074 // foreach variables are never actually initialized in the way that
75 // the parser came up with.
76 var->setInit(0);
John McCall31168b02011-06-15 23:02:42 +000077
John McCalld4631322011-06-17 06:42:21 +000078 // In ARC, we don't need to retain the iteration variable of a fast
79 // enumeration loop. Rather than actually trying to catch that
80 // during declaration processing, we remove the consequences here.
81 if (getLangOptions().ObjCAutoRefCount) {
82 QualType type = var->getType();
83
84 // Only do this if we inferred the lifetime. Inferred lifetime
85 // will show up as a local qualifier because explicit lifetime
86 // should have shown up as an AttributedType instead.
87 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
88 // Add 'const' and mark the variable as pseudo-strong.
89 var->setType(type.withConst());
90 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +000091 }
92 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000093}
94
Chandler Carruthe2669392011-08-17 09:34:37 +000095/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +000096///
97/// Adding a cast to void (or other expression wrappers) will prevent the
98/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +000099static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000100 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000101 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000102
103 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
104 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthe2669392011-08-17 09:34:37 +0000105 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000106
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000107 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000108 IsNotEqual = Op->getOpcode() == BO_NE;
109 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000110 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
111 if (Op->getOperator() != OO_EqualEqual &&
112 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthe2669392011-08-17 09:34:37 +0000113 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000114
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000115 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000116 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
117 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000118 } else {
119 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000120 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000121 }
122
123 // Suppress warnings when the operator, suspicious as it may be, comes from
124 // a macro expansion.
125 if (Loc.isMacroID())
Chandler Carruthe2669392011-08-17 09:34:37 +0000126 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000127
Chandler Carruthe2669392011-08-17 09:34:37 +0000128 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 << (unsigned)IsNotEqual << E->getSourceRange();
130
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000131 // If the LHS is a plausible entity to assign to, provide a fixit hint to
132 // correct common typos.
133 if (CanAssign) {
134 if (IsNotEqual)
135 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
136 << FixItHint::CreateReplacement(Loc, "|=");
137 else
138 S.Diag(Loc, diag::note_equality_comparison_to_assign)
139 << FixItHint::CreateReplacement(Loc, "=");
140 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000141
142 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000143}
144
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000145void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000146 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
147 return DiagnoseUnusedExprResult(Label->getSubStmt());
148
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000149 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000150 if (!E)
151 return;
152
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000153 SourceLocation Loc;
154 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +0000155 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000156 return;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000158 // Okay, we have an unused result. Depending on what the base expression is,
159 // we might want to make a more specific diagnostic. Check for one of these
160 // cases now.
161 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000162 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000163 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000164 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
165 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000166
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 if (DiagnoseUnusedComparison(*this, E))
168 return;
169
John McCall34376a62010-12-04 03:47:34 +0000170 E = E->IgnoreParenImpCasts();
Chris Lattner1a6babf2009-10-13 04:53:48 +0000171 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000172 if (E->getType()->isVoidType())
173 return;
174
Chris Lattner1a6babf2009-10-13 04:53:48 +0000175 // If the callee has attribute pure, const, or warn_unused_result, warn with
176 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000177 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000178 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000179 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000180 return;
181 }
182 if (FD->getAttr<PureAttr>()) {
183 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
184 return;
185 }
186 if (FD->getAttr<ConstAttr>()) {
187 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
188 return;
189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000190 }
John McCallb7bd14f2010-12-02 01:19:52 +0000191 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
John McCall31168b02011-06-15 23:02:42 +0000192 if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) {
193 Diag(Loc, diag::err_arc_unused_init_message) << R1;
194 return;
195 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000196 const ObjCMethodDecl *MD = ME->getMethodDecl();
197 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000198 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000199 return;
200 }
John McCallb7bd14f2010-12-02 01:19:52 +0000201 } else if (isa<ObjCPropertyRefExpr>(E)) {
202 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000203 } else if (const CXXFunctionalCastExpr *FC
204 = dyn_cast<CXXFunctionalCastExpr>(E)) {
205 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
206 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
207 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000208 }
John McCall2351cb92010-04-06 22:24:14 +0000209 // Diagnose "(void*) blah" as a typo for "(void) blah".
210 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
211 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
212 QualType T = TI->getType();
213
214 // We really do want to use the non-canonical type here.
215 if (T == Context.VoidPtrTy) {
216 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
217
218 Diag(Loc, diag::warn_unused_voidptr)
219 << FixItHint::CreateRemoval(TL.getStarLoc());
220 return;
221 }
222 }
223
Ted Kremenek3427fac2011-02-23 01:52:04 +0000224 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000228Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000229 MultiStmtArg elts, bool isStmtExpr) {
230 unsigned NumElts = elts.size();
231 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000232 // If we're in C89 mode, check that we don't have any decls after stmts. If
233 // so, emit an extension diagnostic.
234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
235 // Note that __extension__ can be around a decl.
236 unsigned i = 0;
237 // Skip over all declarations.
238 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
239 /*empty*/;
240
241 // We found the end of the list or a statement. Scan for another declstmt.
242 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
243 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattnerd864daf2007-08-27 04:29:41 +0000245 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000246 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000247 Diag(D->getLocation(), diag::ext_mixed_decls_code);
248 }
249 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000250 // Warn about unused expressions in statements.
251 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000252 // Ignore statements that are last in a statement expression.
253 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000254 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000256 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000257 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000258
Ted Kremenek5a201952009-02-07 01:47:29 +0000259 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000260}
261
John McCalldadc5752010-08-24 06:29:42 +0000262StmtResult
John McCallb268a282010-08-23 23:25:46 +0000263Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
264 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000265 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000266 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000267
Steve Naroff8eeeb132007-05-08 21:09:37 +0000268 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000269 // However, GCC allows any evaluatable integer expression.
Mike Stump11289f42009-09-09 15:08:12 +0000270 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000271 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000272 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000273
Chris Lattner46eeb222007-07-18 02:28:47 +0000274 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000275
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000276 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
277 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000278 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000279 }
280
John McCallaab3e412010-08-25 08:40:02 +0000281 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000282 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000283 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000284 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000285
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000286 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
287 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000288 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000289 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000290}
291
Chris Lattner34a22092009-03-04 04:23:07 +0000292/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000293void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chris Lattner34a22092009-03-04 04:23:07 +0000294 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000295 CS->setSubStmt(SubStmt);
296}
297
John McCalldadc5752010-08-24 06:29:42 +0000298StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000299Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000301 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000302 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000303 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000304 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000305
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000306 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000307 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000308 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000309}
310
John McCalldadc5752010-08-24 06:29:42 +0000311StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000312Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
313 SourceLocation ColonLoc, Stmt *SubStmt) {
314
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000315 // If the label was multiply defined, reject it now.
316 if (TheDecl->getStmt()) {
317 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
318 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000319 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000320 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000321
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000322 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000323 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
324 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000325 if (!TheDecl->isGnuLocal())
326 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000327 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000328}
329
John McCalldadc5752010-08-24 06:29:42 +0000330StmtResult
John McCall48871652010-08-21 09:40:31 +0000331Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000332 Stmt *thenStmt, SourceLocation ElseLoc,
333 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000334 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregor633caca2009-11-23 23:44:04 +0000336 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000337 if (CondVar) {
338 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000339 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000340 if (CondResult.isInvalid())
341 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000342 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000343 Expr *ConditionExpr = CondResult.takeAs<Expr>();
344 if (!ConditionExpr)
345 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000346
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000347 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000348
Anders Carlssondb83d772007-10-10 20:50:11 +0000349 // Warn if the if block has a null body without an else value.
350 // this helps prevent bugs due to typos, such as
351 // if (condition);
352 // do_stuff();
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000353 //
John McCallb268a282010-08-23 23:25:46 +0000354 if (!elseStmt) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000355 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Argyrios Kyrtzidis90ee2a42010-11-19 20:54:25 +0000356 // But do not warn if the body is a macro that expands to nothing, e.g:
357 //
358 // #define CALL(x)
359 // if (condition)
360 // CALL(0);
361 //
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000362 if (!stmt->hasLeadingEmptyMacro())
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000363 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000364 }
365
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000366 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000367
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000369 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000370}
Steve Naroff86272ea2007-05-29 02:14:17 +0000371
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000372/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
373/// the specified width and sign. If an overflow occurs, detect it and emit
374/// the specified diagnostic.
375void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
376 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000377 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000378 unsigned DiagID) {
379 // Perform a conversion to the promoted condition type if needed.
380 if (NewWidth > Val.getBitWidth()) {
381 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000382 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000383 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000384
385 // If the input was signed and negative and the output is
386 // unsigned, don't bother to warn: this is implementation-defined
387 // behavior.
388 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000389 } else if (NewWidth < Val.getBitWidth()) {
390 // If this is a truncation, check for overflow.
391 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000392 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000393 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000394 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000395 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000396 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000397 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000399 // Regardless of whether a diagnostic was emitted, really do the
400 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000401 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000402 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000403 } else if (NewSign != Val.isSigned()) {
404 // Convert the sign to match the sign of the condition. This can cause
405 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000407 // behavior.
408 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000409 llvm::APSInt OldVal(Val);
410 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000411 }
412}
413
Chris Lattner67998452007-08-23 18:29:20 +0000414namespace {
415 struct CaseCompareFunctor {
416 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
417 const llvm::APSInt &RHS) {
418 return LHS.first < RHS;
419 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000420 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
421 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
422 return LHS.first < RHS.first;
423 }
Chris Lattner67998452007-08-23 18:29:20 +0000424 bool operator()(const llvm::APSInt &LHS,
425 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
426 return LHS < RHS.first;
427 }
428 };
429}
430
Chris Lattner4b2ff022007-09-21 18:15:22 +0000431/// CmpCaseVals - Comparison predicate for sorting case values.
432///
433static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
434 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
435 if (lhs.first < rhs.first)
436 return true;
437
438 if (lhs.first == rhs.first &&
439 lhs.second->getCaseLoc().getRawEncoding()
440 < rhs.second->getCaseLoc().getRawEncoding())
441 return true;
442 return false;
443}
444
Douglas Gregorbd6839732010-02-08 22:24:16 +0000445/// CmpEnumVals - Comparison predicate for sorting enumeration values.
446///
447static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
448 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
449{
450 return lhs.first < rhs.first;
451}
452
453/// EqEnumVals - Comparison preficate for uniqing enumeration values.
454///
455static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
456 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
457{
458 return lhs.first == rhs.first;
459}
460
Chris Lattnera96d4272009-10-16 16:45:22 +0000461/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
462/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000463static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
464 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
465 expr = cleanups->getSubExpr();
466 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
467 if (impcast->getCastKind() != CK_IntegralCast) break;
468 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000469 }
470 return expr->getType();
471}
472
John McCalldadc5752010-08-24 06:29:42 +0000473StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000474Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000475 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000476 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000477
Douglas Gregore60e41a2010-05-06 17:25:47 +0000478 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000479 if (CondVar) {
480 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000481 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
482 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000483 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000484
John McCallb268a282010-08-23 23:25:46 +0000485 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000487
John McCallb268a282010-08-23 23:25:46 +0000488 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000489 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490
John McCallb268a282010-08-23 23:25:46 +0000491 CondResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000493 PDiag(diag::err_typecheck_statement_requires_integer),
494 PDiag(diag::err_switch_incomplete_class_type)
John McCallb268a282010-08-23 23:25:46 +0000495 << Cond->getSourceRange(),
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000496 PDiag(diag::err_switch_explicit_conversion),
497 PDiag(diag::note_switch_conversion),
498 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000499 PDiag(diag::note_switch_conversion),
500 PDiag(0));
John McCallb268a282010-08-23 23:25:46 +0000501 if (CondResult.isInvalid()) return StmtError();
502 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
John McCall5939b162011-08-06 07:30:58 +0000504 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
505 CondResult = UsualUnaryConversions(Cond);
506 if (CondResult.isInvalid()) return StmtError();
507 Cond = CondResult.take();
508
John McCall48871652010-08-21 09:40:31 +0000509 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000510 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000511 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000512 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000513 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000514 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000515 }
John McCalla95172b2010-08-01 00:26:45 +0000516
John McCallaab3e412010-08-25 08:40:02 +0000517 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
John McCallb268a282010-08-23 23:25:46 +0000519 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000520 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000521 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000522}
523
Gabor Greif16e02862010-10-01 22:05:14 +0000524static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
525 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000526 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000527 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000528 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000529 Val.setIsSigned(IsSigned);
530}
531
John McCalldadc5752010-08-24 06:29:42 +0000532StmtResult
John McCallb268a282010-08-23 23:25:46 +0000533Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
534 Stmt *BodyStmt) {
535 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000536 assert(SS == getCurFunction()->SwitchStack.back() &&
537 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000538
Steve Naroff42a350a2007-09-01 21:08:38 +0000539 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000540 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000541
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000542 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000543 if (!CondExpr) return StmtError();
544
545 QualType CondType = CondExpr->getType();
546
John McCalld3dfbd62010-05-18 03:19:21 +0000547 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000548 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000549 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000550
Chris Lattnera96d4272009-10-16 16:45:22 +0000551 // C++ 6.4.2.p2:
552 // Integral promotions are performed (on the switch condition).
553 //
554 // A case value unrepresentable by the original switch condition
555 // type (before the promotion) doesn't make sense, even when it can
556 // be represented by the promoted type. Therefore we need to find
557 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000558 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000559 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000560 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000561 // appropriate type now, just return an error.
562 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000563 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000564
Chris Lattner4ebae652010-04-16 23:34:13 +0000565 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000566 // switch(bool_expr) {...} is often a programmer error, e.g.
567 // switch(n && mask) { ... } // Doh - should be "n & mask".
568 // One can always use an if statement instead of switch(bool_expr).
569 Diag(SwitchLoc, diag::warn_bool_switch_condition)
570 << CondExpr->getSourceRange();
571 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000572 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000573
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000574 // Get the bitwidth of the switched-on value before promotions. We must
575 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000576 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000577 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000578 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000579 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000580 bool CondIsSigned
581 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000582
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000583 // Accumulate all of the case values in a vector so that we can sort them
584 // and detect duplicates. This vector contains the APInt for the case after
585 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000586 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000587 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000588
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000589 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000590 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
591 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000592
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000593 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattner10cb5e52007-08-23 06:23:56 +0000595 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000596
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000597 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000598 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000599
Anders Carlsson51873c22007-07-22 07:07:56 +0000600 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000601 if (TheDefaultStmt) {
602 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000603 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000604
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000605 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000606 // we'll return a valid AST. This requires recursing down the AST and
607 // finding it, not something we are set up to do right now. For now,
608 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000609 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000610 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000611 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000612
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000613 } else {
614 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000615
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000616 // We already verified that the expression has a i-c-e value (C99
617 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000618 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000619
620 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
621 HasDependentValue = true;
622 break;
623 }
Mike Stump11289f42009-09-09 15:08:12 +0000624
Anders Carlsson59689ed2008-11-22 21:04:56 +0000625 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000627 // Convert the value to the same width/sign as the condition.
628 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000629 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000630 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000631
Chris Lattnera65e1f32008-01-16 19:17:22 +0000632 // If the LHS is not the same type as the condition, insert an implicit
633 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000634 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
Chris Lattnera65e1f32008-01-16 19:17:22 +0000635 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000636
Chris Lattner10cb5e52007-08-23 06:23:56 +0000637 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000638 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000639 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000640 CS->getRHS()->isValueDependent()) {
641 HasDependentValue = true;
642 break;
643 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000644 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000645 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000646 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000647 }
648 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000649
650 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000651 // If we don't have a default statement, check whether the
652 // condition is constant.
653 llvm::APSInt ConstantCondValue;
654 bool HasConstantCond = false;
655 bool ShouldCheckConstantCond = false;
656 if (!HasDependentValue && !TheDefaultStmt) {
657 Expr::EvalResult Result;
658 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
659 if (HasConstantCond) {
660 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
661 ConstantCondValue = Result.Val.getInt();
662 ShouldCheckConstantCond = true;
663
664 assert(ConstantCondValue.getBitWidth() == CondWidth &&
665 ConstantCondValue.isSigned() == CondIsSigned);
666 }
667 }
668
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000669 // Sort all the scalar case values so we can easily detect duplicates.
670 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
671
672 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000673 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
674 if (ShouldCheckConstantCond &&
675 CaseVals[i].first == ConstantCondValue)
676 ShouldCheckConstantCond = false;
677
678 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000679 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000680 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000681 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
682 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000683 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000684 // FIXME: We really want to remove the bogus case stmt from the
685 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000686 CaseListIsErroneous = true;
687 }
688 }
689 }
Mike Stump11289f42009-09-09 15:08:12 +0000690
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000691 // Detect duplicate case ranges, which usually don't exist at all in
692 // the first place.
693 if (!CaseRanges.empty()) {
694 // Sort all the case ranges by their low value so we can easily detect
695 // overlaps between ranges.
696 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000697
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000698 // Scan the ranges, computing the high values and removing empty ranges.
699 std::vector<llvm::APSInt> HiVals;
700 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000701 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000702 CaseStmt *CR = CaseRanges[i].second;
703 Expr *Hi = CR->getRHS();
704 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000705
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000706 // Convert the value to the same width/sign as the condition.
707 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000708 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000709 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000710
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000711 // If the LHS is not the same type as the condition, insert an implicit
712 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000713 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000714 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000715
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000716 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000717 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000718 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
719 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000720 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000721 CaseRanges.erase(CaseRanges.begin()+i);
722 --i, --e;
723 continue;
724 }
John McCalld3dfbd62010-05-18 03:19:21 +0000725
726 if (ShouldCheckConstantCond &&
727 LoVal <= ConstantCondValue &&
728 ConstantCondValue <= HiVal)
729 ShouldCheckConstantCond = false;
730
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000731 HiVals.push_back(HiVal);
732 }
Mike Stump11289f42009-09-09 15:08:12 +0000733
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000734 // Rescan the ranges, looking for overlap with singleton values and other
735 // ranges. Since the range list is sorted, we only need to compare case
736 // ranges with their neighbors.
737 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
738 llvm::APSInt &CRLo = CaseRanges[i].first;
739 llvm::APSInt &CRHi = HiVals[i];
740 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000742 // Check to see whether the case range overlaps with any
743 // singleton cases.
744 CaseStmt *OverlapStmt = 0;
745 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000746
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000747 // Find the smallest value >= the lower bound. If I is in the
748 // case range, then we have overlap.
749 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
750 CaseVals.end(), CRLo,
751 CaseCompareFunctor());
752 if (I != CaseVals.end() && I->first < CRHi) {
753 OverlapVal = I->first; // Found overlap with scalar.
754 OverlapStmt = I->second;
755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000757 // Find the smallest value bigger than the upper bound.
758 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
759 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
760 OverlapVal = (I-1)->first; // Found overlap with scalar.
761 OverlapStmt = (I-1)->second;
762 }
Mike Stump11289f42009-09-09 15:08:12 +0000763
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000764 // Check to see if this case stmt overlaps with the subsequent
765 // case range.
766 if (i && CRLo <= HiVals[i-1]) {
767 OverlapVal = HiVals[i-1]; // Found overlap with range.
768 OverlapStmt = CaseRanges[i-1].second;
769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000771 if (OverlapStmt) {
772 // If we have a duplicate, report it.
773 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
774 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000775 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000776 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000777 // FIXME: We really want to remove the bogus case stmt from the
778 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000779 CaseListIsErroneous = true;
780 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000781 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000782 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000783
John McCalld3dfbd62010-05-18 03:19:21 +0000784 // Complain if we have a constant condition and we didn't find a match.
785 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
786 // TODO: it would be nice if we printed enums as enums, chars as
787 // chars, etc.
788 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
789 << ConstantCondValue.toString(10)
790 << CondExpr->getSourceRange();
791 }
792
793 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000794 // values. We only issue a warning if there is not 'default:', but
795 // we still do the analysis to preserve this information in the AST
796 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000797 //
Chris Lattner51679082010-09-16 17:09:42 +0000798 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000799
Douglas Gregorbd6839732010-02-08 22:24:16 +0000800 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000801 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000802 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000803 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000804 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000805 EnumValsTy EnumVals;
806
John McCalld3dfbd62010-05-18 03:19:21 +0000807 // Gather all enum values, set their type and sort them,
808 // allowing easier comparison with CaseVals.
809 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000810 EDI != ED->enumerator_end(); ++EDI) {
811 llvm::APSInt Val = EDI->getInitVal();
812 AdjustAPSInt(Val, CondWidth, CondIsSigned);
813 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000814 }
815 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000816 EnumValsTy::iterator EIend =
817 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000818
819 // See which case values aren't in enum.
820 // TODO: we might want to check whether case values are out of the
821 // enum even if we don't want to check whether all cases are handled.
822 if (!TheDefaultStmt) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000823 EnumValsTy::const_iterator EI = EnumVals.begin();
824 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000825 CI != CaseVals.end(); CI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000826 while (EI != EIend && EI->first < CI->first)
827 EI++;
828 if (EI == EIend || EI->first > CI->first)
John McCalld3dfbd62010-05-18 03:19:21 +0000829 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
830 << ED->getDeclName();
Ted Kremenek02627a22010-09-09 06:53:59 +0000831 }
832 // See which of case ranges aren't in enum
833 EI = EnumVals.begin();
834 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000835 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000836 while (EI != EIend && EI->first < RI->first)
837 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838
Ted Kremenek02627a22010-09-09 06:53:59 +0000839 if (EI == EIend || EI->first != RI->first) {
840 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
841 << ED->getDeclName();
842 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000843
Ted Kremenek02627a22010-09-09 06:53:59 +0000844 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000845 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Ted Kremenek02627a22010-09-09 06:53:59 +0000846 while (EI != EIend && EI->first < Hi)
847 EI++;
848 if (EI == EIend || EI->first != Hi)
849 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
850 << ED->getDeclName();
851 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Ted Kremenekc42f3452010-09-09 00:05:53 +0000854 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000855 CaseValsTy::const_iterator CI = CaseVals.begin();
856 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000857 bool hasCasesNotInSwitch = false;
858
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000859 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Ted Kremenekc42f3452010-09-09 00:05:53 +0000861 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000862 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000863 llvm::APSInt CIVal;
864 while (CI != CaseVals.end() && CI->first < EI->first)
865 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000866
Douglas Gregorbd6839732010-02-08 22:24:16 +0000867 if (CI != CaseVals.end() && CI->first == EI->first)
868 continue;
869
Ted Kremenekc42f3452010-09-09 00:05:53 +0000870 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +0000871 for (; RI != CaseRanges.end(); RI++) {
872 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000873 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000874 if (EI->first <= Hi)
875 break;
876 }
877
Ted Kremenekc42f3452010-09-09 00:05:53 +0000878 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000879 hasCasesNotInSwitch = true;
880 if (!TheDefaultStmt)
Chris Lattner51679082010-09-16 17:09:42 +0000881 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +0000882 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Chris Lattner51679082010-09-16 17:09:42 +0000885 // Produce a nice diagnostic if multiple values aren't handled.
886 switch (UnhandledNames.size()) {
887 case 0: break;
888 case 1:
889 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
890 << UnhandledNames[0];
891 break;
892 case 2:
893 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
894 << UnhandledNames[0] << UnhandledNames[1];
895 break;
896 case 3:
897 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
898 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
899 break;
900 default:
901 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
902 << (unsigned)UnhandledNames.size()
903 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
904 break;
905 }
Ted Kremenekc42f3452010-09-09 00:05:53 +0000906
907 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +0000908 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000909 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000910 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000911
Mike Stump87c57ac2009-05-16 07:39:55 +0000912 // FIXME: If the case list was broken is some way, we don't have a good system
913 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000914 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000915 return StmtError();
916
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000917 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000918}
919
John McCalldadc5752010-08-24 06:29:42 +0000920StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +0000922 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +0000923 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924
Douglas Gregor680f8612009-11-24 21:15:44 +0000925 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000926 if (CondVar) {
927 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000928 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000929 if (CondResult.isInvalid())
930 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +0000931 }
John McCallb268a282010-08-23 23:25:46 +0000932 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000933 if (!ConditionExpr)
934 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935
John McCallb268a282010-08-23 23:25:46 +0000936 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000938 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +0000939 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000940}
941
John McCalldadc5752010-08-24 06:29:42 +0000942StmtResult
John McCallb268a282010-08-23 23:25:46 +0000943Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000944 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +0000945 Expr *Cond, SourceLocation CondRParen) {
946 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000947
John Wiegley01296292011-04-08 18:41:53 +0000948 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
949 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +0000950 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +0000951 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +0000952
John McCallacf0ee52010-10-08 02:01:28 +0000953 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +0000954 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000955 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000956 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000957 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000958
John McCallb268a282010-08-23 23:25:46 +0000959 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000960
John McCallb268a282010-08-23 23:25:46 +0000961 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000962}
963
John McCalldadc5752010-08-24 06:29:42 +0000964StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000965Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +0000966 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000967 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +0000968 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000969 if (!getLangOptions().CPlusPlus) {
970 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000971 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
972 // declare identifiers for objects having storage class 'auto' or
973 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000974 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
975 DI!=DE; ++DI) {
976 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +0000977 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000978 VD = 0;
979 if (VD == 0)
980 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
981 // FIXME: mark decl erroneous!
982 }
Chris Lattner39f920f2007-08-28 05:03:08 +0000983 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000984 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000985
John McCalldadc5752010-08-24 06:29:42 +0000986 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000987 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000988 if (secondVar) {
989 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000990 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000991 if (SecondResult.isInvalid())
992 return StmtError();
993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000994
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000995 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Anders Carlsson1682af52009-08-01 01:39:59 +0000997 DiagnoseUnusedExprResult(First);
998 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000999 DiagnoseUnusedExprResult(Body);
1000
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001 return Owned(new (Context) ForStmt(Context, First,
1002 SecondResult.take(), ConditionVar,
1003 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001004 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001005}
1006
John McCall34376a62010-12-04 03:47:34 +00001007/// In an Objective C collection iteration statement:
1008/// for (x in y)
1009/// x can be an arbitrary l-value expression. Bind it up as a
1010/// full-expression.
1011StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1012 CheckImplicitConversions(E);
John McCall5d413782010-12-06 08:20:24 +00001013 ExprResult Result = MaybeCreateExprWithCleanups(E);
John McCall34376a62010-12-04 03:47:34 +00001014 if (Result.isInvalid()) return StmtError();
1015 return Owned(static_cast<Stmt*>(Result.get()));
1016}
1017
John McCall53848232011-07-27 01:07:15 +00001018ExprResult
1019Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1020 assert(collection);
1021
1022 // Bail out early if we've got a type-dependent expression.
1023 if (collection->isTypeDependent()) return Owned(collection);
1024
1025 // Perform normal l-value conversion.
1026 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1027 if (result.isInvalid())
1028 return ExprError();
1029 collection = result.take();
1030
1031 // The operand needs to have object-pointer type.
1032 // TODO: should we do a contextual conversion?
1033 const ObjCObjectPointerType *pointerType =
1034 collection->getType()->getAs<ObjCObjectPointerType>();
1035 if (!pointerType)
1036 return Diag(forLoc, diag::err_collection_expr_type)
1037 << collection->getType() << collection->getSourceRange();
1038
1039 // Check that the operand provides
1040 // - countByEnumeratingWithState:objects:count:
1041 const ObjCObjectType *objectType = pointerType->getObjectType();
1042 ObjCInterfaceDecl *iface = objectType->getInterface();
1043
1044 // If we have a forward-declared type, we can't do this check.
1045 if (iface && iface->isForwardDecl()) {
1046 // This is ill-formed under ARC.
1047 if (getLangOptions().ObjCAutoRefCount) {
1048 Diag(forLoc, diag::err_arc_collection_forward)
1049 << pointerType->getPointeeType() << collection->getSourceRange();
1050 }
1051
1052 // Otherwise, if we have any useful type information, check that
1053 // the type declares the appropriate method.
1054 } else if (iface || !objectType->qual_empty()) {
1055 IdentifierInfo *selectorIdents[] = {
1056 &Context.Idents.get("countByEnumeratingWithState"),
1057 &Context.Idents.get("objects"),
1058 &Context.Idents.get("count")
1059 };
1060 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1061
1062 ObjCMethodDecl *method = 0;
1063
1064 // If there's an interface, look in both the public and private APIs.
1065 if (iface) {
1066 method = iface->lookupInstanceMethod(selector);
1067 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1068 }
1069
1070 // Also check protocol qualifiers.
1071 if (!method)
1072 method = LookupMethodInQualifiedType(selector, pointerType,
1073 /*instance*/ true);
1074
1075 // If we didn't find it anywhere, give up.
1076 if (!method) {
1077 Diag(forLoc, diag::warn_collection_expr_type)
1078 << collection->getType() << selector << collection->getSourceRange();
1079 }
1080
1081 // TODO: check for an incompatible signature?
1082 }
1083
1084 // Wrap up any cleanups in the expression.
1085 return Owned(MaybeCreateExprWithCleanups(collection));
1086}
1087
John McCalldadc5752010-08-24 06:29:42 +00001088StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001089Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1090 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001091 Stmt *First, Expr *Second,
1092 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +00001093 if (First) {
1094 QualType FirstType;
1095 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001096 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001097 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1098 diag::err_toomany_element_decls));
1099
John McCall31168b02011-06-15 23:02:42 +00001100 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1101 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001102 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1103 // declare identifiers for objects having storage class 'auto' or
1104 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001105 if (!D->hasLocalStorage())
1106 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001107 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001108 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001109 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001110 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001111 return StmtError(Diag(First->getLocStart(),
1112 diag::err_selector_element_not_lvalue)
1113 << First->getSourceRange());
1114
Mike Stump11289f42009-09-09 15:08:12 +00001115 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001116 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001117 if (!FirstType->isDependentType() &&
1118 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001119 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +00001120 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001121 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001122 }
John McCall53848232011-07-27 01:07:15 +00001123
Ted Kremenek5a201952009-02-07 01:47:29 +00001124 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1125 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001126}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001127
Richard Smith02e85f32011-04-14 22:09:26 +00001128namespace {
1129
1130enum BeginEndFunction {
1131 BEF_begin,
1132 BEF_end
1133};
1134
1135/// Build a variable declaration for a for-range statement.
1136static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1137 QualType Type, const char *Name) {
1138 DeclContext *DC = SemaRef.CurContext;
1139 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1140 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1141 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1142 TInfo, SC_Auto, SC_None);
Richard Smith0c502d22011-04-18 15:49:25 +00001143 Decl->setImplicit();
Richard Smith02e85f32011-04-14 22:09:26 +00001144 return Decl;
1145}
1146
1147/// Finish building a variable declaration for a for-range statement.
1148/// \return true if an error occurs.
1149static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1150 SourceLocation Loc, int diag) {
1151 // Deduce the type for the iterator variable now rather than leaving it to
1152 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1153 TypeSourceInfo *InitTSI = 0;
1154 if (Init->getType()->isVoidType() ||
1155 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
1156 SemaRef.Diag(Loc, diag) << Init->getType();
1157 if (!InitTSI) {
1158 Decl->setInvalidDecl();
1159 return true;
1160 }
1161 Decl->setTypeSourceInfo(InitTSI);
1162 Decl->setType(InitTSI->getType());
1163
John McCall31168b02011-06-15 23:02:42 +00001164 // In ARC, infer lifetime.
1165 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1166 // we're doing the equivalent of fast iteration.
1167 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1168 SemaRef.inferObjCARCLifetime(Decl))
1169 Decl->setInvalidDecl();
1170
Richard Smith02e85f32011-04-14 22:09:26 +00001171 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1172 /*TypeMayContainAuto=*/false);
1173 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001174 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001175 return false;
1176}
1177
1178/// Produce a note indicating which begin/end function was implicitly called
1179/// by a C++0x for-range statement. This is often not obvious from the code,
1180/// nor from the diagnostics produced when analysing the implicit expressions
1181/// required in a for-range statement.
1182void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1183 BeginEndFunction BEF) {
1184 CallExpr *CE = dyn_cast<CallExpr>(E);
1185 if (!CE)
1186 return;
1187 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1188 if (!D)
1189 return;
1190 SourceLocation Loc = D->getLocation();
1191
1192 std::string Description;
1193 bool IsTemplate = false;
1194 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1195 Description = SemaRef.getTemplateArgumentBindingsText(
1196 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1197 IsTemplate = true;
1198 }
1199
1200 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1201 << BEF << IsTemplate << Description << E->getType();
1202}
1203
1204/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1205/// given LookupResult is non-empty, it is assumed to describe a member which
1206/// will be invoked. Otherwise, the function will be found via argument
1207/// dependent lookup.
1208static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1209 SourceLocation Loc,
1210 VarDecl *Decl,
1211 BeginEndFunction BEF,
1212 const DeclarationNameInfo &NameInfo,
1213 LookupResult &MemberLookup,
1214 Expr *Range) {
1215 ExprResult CallExpr;
1216 if (!MemberLookup.empty()) {
1217 ExprResult MemberRef =
1218 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1219 /*IsPtr=*/false, CXXScopeSpec(),
1220 /*Qualifier=*/0, MemberLookup,
1221 /*TemplateArgs=*/0);
1222 if (MemberRef.isInvalid())
1223 return ExprError();
1224 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1225 Loc, 0);
1226 if (CallExpr.isInvalid())
1227 return ExprError();
1228 } else {
1229 UnresolvedSet<0> FoundNames;
1230 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1231 // std is an associated namespace.
1232 UnresolvedLookupExpr *Fn =
1233 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1234 NestedNameSpecifierLoc(), NameInfo,
1235 /*NeedsADL=*/true, /*Overloaded=*/false,
1236 FoundNames.begin(), FoundNames.end(),
1237 /*LookInStdNamespace=*/true);
1238 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1239 0);
1240 if (CallExpr.isInvalid()) {
1241 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1242 << Range->getType();
1243 return ExprError();
1244 }
1245 }
1246 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1247 diag::err_for_range_iter_deduction_failure)) {
1248 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1249 return ExprError();
1250 }
1251 return CallExpr;
1252}
1253
1254}
1255
1256/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1257///
1258/// C++0x [stmt.ranged]:
1259/// A range-based for statement is equivalent to
1260///
1261/// {
1262/// auto && __range = range-init;
1263/// for ( auto __begin = begin-expr,
1264/// __end = end-expr;
1265/// __begin != __end;
1266/// ++__begin ) {
1267/// for-range-declaration = *__begin;
1268/// statement
1269/// }
1270/// }
1271///
1272/// The body of the loop is not available yet, since it cannot be analysed until
1273/// we have determined the type of the for-range-declaration.
1274StmtResult
1275Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1276 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1277 SourceLocation RParenLoc) {
1278 if (!First || !Range)
1279 return StmtError();
1280
1281 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1282 assert(DS && "first part of for range not a decl stmt");
1283
1284 if (!DS->isSingleDecl()) {
1285 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1286 return StmtError();
1287 }
1288 if (DS->getSingleDecl()->isInvalidDecl())
1289 return StmtError();
1290
1291 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1292 return StmtError();
1293
1294 // Build auto && __range = range-init
1295 SourceLocation RangeLoc = Range->getLocStart();
1296 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1297 Context.getAutoRRefDeductType(),
1298 "__range");
1299 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1300 diag::err_for_range_deduction_failure))
1301 return StmtError();
1302
1303 // Claim the type doesn't contain auto: we've already done the checking.
1304 DeclGroupPtrTy RangeGroup =
1305 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1306 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1307 if (RangeDecl.isInvalid())
1308 return StmtError();
1309
1310 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1311 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1312 RParenLoc);
1313}
1314
1315/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1316StmtResult
1317Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1318 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1319 Expr *Inc, Stmt *LoopVarDecl,
1320 SourceLocation RParenLoc) {
1321 Scope *S = getCurScope();
1322
1323 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1324 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1325 QualType RangeVarType = RangeVar->getType();
1326
1327 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1328 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1329
1330 StmtResult BeginEndDecl = BeginEnd;
1331 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1332
1333 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1334 SourceLocation RangeLoc = RangeVar->getLocation();
1335
1336 ExprResult RangeRef = BuildDeclRefExpr(RangeVar,
1337 RangeVarType.getNonReferenceType(),
1338 VK_LValue, ColonLoc);
1339 if (RangeRef.isInvalid())
1340 return StmtError();
1341
1342 QualType AutoType = Context.getAutoDeductType();
1343 Expr *Range = RangeVar->getInit();
1344 if (!Range)
1345 return StmtError();
1346 QualType RangeType = Range->getType();
1347
1348 if (RequireCompleteType(RangeLoc, RangeType,
1349 PDiag(diag::err_for_range_incomplete_type)))
1350 return StmtError();
1351
1352 // Build auto __begin = begin-expr, __end = end-expr.
1353 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1354 "__begin");
1355 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1356 "__end");
1357
1358 // Build begin-expr and end-expr and attach to __begin and __end variables.
1359 ExprResult BeginExpr, EndExpr;
1360 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1361 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1362 // __range + __bound, respectively, where __bound is the array bound. If
1363 // _RangeT is an array of unknown size or an array of incomplete type,
1364 // the program is ill-formed;
1365
1366 // begin-expr is __range.
1367 BeginExpr = RangeRef;
1368 if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc,
1369 diag::err_for_range_iter_deduction_failure)) {
1370 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1371 return StmtError();
1372 }
1373
1374 // Find the array bound.
1375 ExprResult BoundExpr;
1376 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1377 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001378 Context.getPointerDiffType(),
1379 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001380 else if (const VariableArrayType *VAT =
1381 dyn_cast<VariableArrayType>(UnqAT))
1382 BoundExpr = VAT->getSizeExpr();
1383 else {
1384 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1385 // UnqAT is not incomplete and Range is not type-dependent.
1386 assert(0 && "Unexpected array type in for-range");
1387 return StmtError();
1388 }
1389
1390 // end-expr is __range + __bound.
1391 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(),
1392 BoundExpr.get());
1393 if (EndExpr.isInvalid())
1394 return StmtError();
1395 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1396 diag::err_for_range_iter_deduction_failure)) {
1397 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1398 return StmtError();
1399 }
1400 } else {
1401 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1402 ColonLoc);
1403 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1404 ColonLoc);
1405
1406 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1407 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1408
1409 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1410 // - if _RangeT is a class type, the unqualified-ids begin and end are
1411 // looked up in the scope of class _RangeT as if by class member access
1412 // lookup (3.4.5), and if either (or both) finds at least one
1413 // declaration, begin-expr and end-expr are __range.begin() and
1414 // __range.end(), respectively;
1415 LookupQualifiedName(BeginMemberLookup, D);
1416 LookupQualifiedName(EndMemberLookup, D);
1417
1418 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1419 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1420 << RangeType << BeginMemberLookup.empty();
1421 return StmtError();
1422 }
1423 } else {
1424 // - otherwise, begin-expr and end-expr are begin(__range) and
1425 // end(__range), respectively, where begin and end are looked up with
1426 // argument-dependent lookup (3.4.2). For the purposes of this name
1427 // lookup, namespace std is an associated namespace.
1428 }
1429
1430 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1431 BEF_begin, BeginNameInfo,
1432 BeginMemberLookup, RangeRef.get());
1433 if (BeginExpr.isInvalid())
1434 return StmtError();
1435
1436 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1437 BEF_end, EndNameInfo,
1438 EndMemberLookup, RangeRef.get());
1439 if (EndExpr.isInvalid())
1440 return StmtError();
1441 }
1442
1443 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1444 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1445 if (!Context.hasSameType(BeginType, EndType)) {
1446 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1447 << BeginType << EndType;
1448 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1449 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1450 }
1451
1452 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1453 // Claim the type doesn't contain auto: we've already done the checking.
1454 DeclGroupPtrTy BeginEndGroup =
1455 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1456 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1457
1458 ExprResult BeginRef = BuildDeclRefExpr(BeginVar,
1459 BeginType.getNonReferenceType(),
1460 VK_LValue, ColonLoc);
1461 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1462 VK_LValue, ColonLoc);
1463
1464 // Build and check __begin != __end expression.
1465 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1466 BeginRef.get(), EndRef.get());
1467 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1468 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1469 if (NotEqExpr.isInvalid()) {
1470 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1471 if (!Context.hasSameType(BeginType, EndType))
1472 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1473 return StmtError();
1474 }
1475
1476 // Build and check ++__begin expression.
1477 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1478 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1479 if (IncrExpr.isInvalid()) {
1480 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1481 return StmtError();
1482 }
1483
1484 // Build and check *__begin expression.
1485 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1486 if (DerefExpr.isInvalid()) {
1487 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1488 return StmtError();
1489 }
1490
1491 // Attach *__begin as initializer for VD.
1492 if (!LoopVar->isInvalidDecl()) {
1493 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1494 /*TypeMayContainAuto=*/true);
1495 if (LoopVar->isInvalidDecl())
1496 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1497 }
Richard Smithf9603352011-06-21 23:07:19 +00001498 } else {
1499 // The range is implicitly used as a placeholder when it is dependent.
1500 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00001501 }
1502
1503 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1504 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1505 NotEqExpr.take(), IncrExpr.take(),
1506 LoopVarDS, /*Body=*/0, ForLoc,
1507 ColonLoc, RParenLoc));
1508}
1509
1510/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1511/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1512/// body cannot be performed until after the type of the range variable is
1513/// determined.
1514StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1515 if (!S || !B)
1516 return StmtError();
1517
1518 cast<CXXForRangeStmt>(S)->setBody(B);
1519 return S;
1520}
1521
Chris Lattnercab02a62011-02-17 20:34:02 +00001522StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1523 SourceLocation LabelLoc,
1524 LabelDecl *TheDecl) {
1525 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001526 TheDecl->setUsed();
1527 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001528}
Chris Lattner1c310502007-05-31 06:00:00 +00001529
John McCalldadc5752010-08-24 06:29:42 +00001530StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001531Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001532 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001533 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001534 if (!E->isTypeDependent()) {
1535 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001536 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001537 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001538 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001539 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1540 if (ExprRes.isInvalid())
1541 return StmtError();
1542 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001543 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001544 return StmtError();
1545 }
John McCalla95172b2010-08-01 00:26:45 +00001546
John McCallaab3e412010-08-25 08:40:02 +00001547 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001548
Douglas Gregor30776d42009-05-16 00:20:29 +00001549 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001550}
1551
John McCalldadc5752010-08-24 06:29:42 +00001552StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001553Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001554 Scope *S = CurScope->getContinueParent();
1555 if (!S) {
1556 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001557 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001558 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001559
Ted Kremenek5a201952009-02-07 01:47:29 +00001560 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001561}
1562
John McCalldadc5752010-08-24 06:29:42 +00001563StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001564Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001565 Scope *S = CurScope->getBreakParent();
1566 if (!S) {
1567 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001568 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001569 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001570
Ted Kremenek5a201952009-02-07 01:47:29 +00001571 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001572}
1573
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001574/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001575/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001576///
Douglas Gregor5d369002011-01-21 18:05:27 +00001577/// \param ReturnType If we're determining the copy elision candidate for
1578/// a return statement, this is the return type of the function. If we're
1579/// determining the copy elision candidate for a throw expression, this will
1580/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001581///
Douglas Gregor5d369002011-01-21 18:05:27 +00001582/// \param E The expression being returned from the function or block, or
1583/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001584///
Douglas Gregor86394412011-05-20 15:00:53 +00001585/// \param AllowFunctionParameter Whether we allow function parameters to
1586/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1587/// we re-use this logic to determine whether we should try to move as part of
1588/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001589///
1590/// \returns The NRVO candidate variable, if the return statement may use the
1591/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001592const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1593 Expr *E,
1594 bool AllowFunctionParameter) {
1595 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001596 // - in a return statement in a function with ...
1597 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001598 if (!ReturnType.isNull()) {
1599 if (!ReturnType->isRecordType())
1600 return 0;
1601 // ... the same cv-unqualified type as the function return type ...
1602 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1603 return 0;
1604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001605
1606 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00001607 // (other than a function or catch-clause parameter)) ...
1608 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001609 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001610 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001611 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1612 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001613 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614
Douglas Gregor5d369002011-01-21 18:05:27 +00001615 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
Douglas Gregor290c93e2010-05-15 06:46:45 +00001616 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
Douglas Gregor5d369002011-01-21 18:05:27 +00001617 !VD->getType().isVolatileQualified() &&
Douglas Gregor732abf12011-01-21 18:20:49 +00001618 ((VD->getKind() == Decl::Var) ||
1619 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001620 return VD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001622 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001623}
1624
Douglas Gregor626fbed2011-01-21 21:08:57 +00001625/// \brief Perform the initialization of a potentially-movable value, which
1626/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00001627///
1628/// This routine implements C++0x [class.copy]p33, which attempts to treat
1629/// returned lvalues as rvalues in certain cases (to prefer move construction),
1630/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00001632Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1633 const VarDecl *NRVOCandidate,
1634 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001635 Expr *Value,
1636 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001637 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638 // When the criteria for elision of a copy operation are met or would
1639 // be met save for the fact that the source object is a function
1640 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00001641 // overload resolution to select the constructor for the copy is first
1642 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00001643 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001644 if (AllowNRVO &&
1645 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001647 Value->getType(), CK_LValueToRValue,
1648 Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649
Douglas Gregorf282a762011-01-21 19:38:21 +00001650 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00001652 = InitializationKind::CreateCopy(Value->getLocStart(),
1653 Value->getLocStart());
1654 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
1656 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00001657 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001658 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00001659 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001660 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001661 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1662 StepEnd = Seq.step_end();
1663 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001664 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00001665 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666
1667 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00001668 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001669
Douglas Gregorf282a762011-01-21 19:38:21 +00001670 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00001671 = Constructor->getParamDecl(0)->getType()
1672 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673
Douglas Gregorf282a762011-01-21 19:38:21 +00001674 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00001676 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1677 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00001678 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
Douglas Gregorf282a762011-01-21 19:38:21 +00001680 // Promote "AsRvalue" to the heap, since we now need this
1681 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001682 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683 CK_LValueToRValue, Value, 0,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001684 VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685
Douglas Gregorf282a762011-01-21 19:38:21 +00001686 // Complete type-checking the initialization of the return type
1687 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001688 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00001689 }
1690 }
1691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692
Douglas Gregorf282a762011-01-21 19:38:21 +00001693 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001694 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00001695 // (again) now with the return value expression as written.
1696 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00001697 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698
Douglas Gregorf282a762011-01-21 19:38:21 +00001699 return Res;
1700}
1701
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001702/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +00001703///
John McCalldadc5752010-08-24 06:29:42 +00001704StmtResult
Steve Naroffc540d662008-09-03 18:15:37 +00001705Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +00001706 // If this is the first return we've seen in the block, infer the type of
1707 // the block from it.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001708 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001709 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +00001710 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +00001711 // Don't call UsualUnaryConversions(), since we don't want to do
1712 // integer promotions here.
John Wiegley01296292011-04-08 18:41:53 +00001713 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1714 if (Result.isInvalid())
1715 return StmtError();
1716 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00001717
1718 if (!RetValExp->isTypeDependent()) {
1719 CurBlock->ReturnType = RetValExp->getType();
1720 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1721 // We have to remove a 'const' added to copied-in variable which was
1722 // part of the implementation spec. and not the actual qualifier for
1723 // the variable.
1724 if (CDRE->isConstQualAdded())
1725 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1726 }
1727 } else
1728 CurBlock->ReturnType = Context.DependentTy;
Steve Naroff3b1e1722008-09-16 22:25:10 +00001729 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001730 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +00001731 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001732 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +00001733
John McCall3882ace2011-01-05 12:14:39 +00001734 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +00001735 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1736 << getCurFunctionOrMethodDecl()->getDeclName();
1737 return StmtError();
1738 }
1739
Steve Naroffc540d662008-09-03 18:15:37 +00001740 // Otherwise, verify that this result type matches the previous one. We are
1741 // pickier with blocks than for normal functions because we don't have GCC
1742 // compatibility to worry about here.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001743 ReturnStmt *Result = 0;
John McCall75f92b52011-08-17 21:34:14 +00001744 const VarDecl *NRVOCandidate = 0;
Steve Naroffc540d662008-09-03 18:15:37 +00001745 if (CurBlock->ReturnType->isVoidType()) {
Douglas Gregor7f139d82011-06-05 05:14:41 +00001746 if (RetValExp && !RetValExp->isTypeDependent() &&
1747 (!getLangOptions().CPlusPlus || !RetValExp->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00001748 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroffc540d662008-09-03 18:15:37 +00001749 RetValExp = 0;
1750 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001751 } else if (!RetValExp) {
Douglas Gregor7f139d82011-06-05 05:14:41 +00001752 if (!CurBlock->ReturnType->isDependentType())
1753 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001754 } else {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001755 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1756 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001757
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001758 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1759 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1760 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001761
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001762 // In C++ the return statement is handled via a copy initialization.
1763 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001764 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001765 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001766 FnRetType,
1767 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001768 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001769 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001770 if (Res.isInvalid()) {
1771 // FIXME: Cleanup temporaries here, anyway?
1772 return StmtError();
1773 }
John McCall75f92b52011-08-17 21:34:14 +00001774 RetValExp = Res.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001777 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlsson6f923f82010-01-29 18:30:20 +00001778 }
Steve Naroffc540d662008-09-03 18:15:37 +00001779 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001780
John McCall75f92b52011-08-17 21:34:14 +00001781 if (RetValExp) {
1782 CheckImplicitConversions(RetValExp, ReturnLoc);
1783 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1784 }
1785 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1786
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001788 // return statement in our scope for later processing.
Douglas Gregor0aa91e02011-06-05 05:04:23 +00001789 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001790 !CurContext->isDependentContext())
1791 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001793 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00001794}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001795
John McCalldadc5752010-08-24 06:29:42 +00001796StmtResult
John McCallb268a282010-08-23 23:25:46 +00001797Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00001798 // Check for unexpanded parameter packs.
1799 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
1800 return StmtError();
1801
Douglas Gregor9a28e842010-03-01 23:15:13 +00001802 if (getCurBlock())
Steve Naroffc540d662008-09-03 18:15:37 +00001803 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00001804
Chris Lattner79413952008-12-04 23:50:19 +00001805 QualType FnRetType;
Douglas Gregor33823722011-06-11 01:09:30 +00001806 QualType DeclaredRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001807 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00001808 FnRetType = FD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00001809 DeclaredRetType = FnRetType;
John McCallab26cfa2010-02-05 21:31:56 +00001810 if (FD->hasAttr<NoReturnAttr>() ||
1811 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00001812 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001813 << getCurFunctionOrMethodDecl()->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00001814 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1815 DeclaredRetType = MD->getResultType();
1816 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
1817 // In the implementation of a method with a related return type, the
1818 // type used to type-check the validity of return statements within the
1819 // method body is a pointer to the type of the class being implemented.
1820 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface());
1821 FnRetType = Context.getObjCObjectPointerType(FnRetType);
1822 } else {
1823 FnRetType = DeclaredRetType;
1824 }
1825 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00001826 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001827
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001828 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00001829 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00001830 if (RetValExp) {
1831 if (!RetValExp->isTypeDependent()) {
1832 // C99 6.8.6.4p1 (ext_ since GCC warns)
1833 unsigned D = diag::ext_return_has_expr;
1834 if (RetValExp->getType()->isVoidType())
1835 D = diag::ext_return_has_void_expr;
1836 else {
1837 ExprResult Result = Owned(RetValExp);
1838 Result = IgnoredValueConversions(Result.take());
1839 if (Result.isInvalid())
1840 return StmtError();
1841 RetValExp = Result.take();
1842 RetValExp = ImpCastExprToType(RetValExp,
1843 Context.VoidTy, CK_ToVoid).take();
1844 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001845
Nick Lewycky1be750a2011-06-01 07:44:31 +00001846 // return (some void expression); is legal in C++.
1847 if (D != diag::ext_return_has_void_expr ||
1848 !getLangOptions().CPlusPlus) {
1849 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00001850
1851 int FunctionKind = 0;
1852 if (isa<ObjCMethodDecl>(CurDecl))
1853 FunctionKind = 1;
1854 else if (isa<CXXConstructorDecl>(CurDecl))
1855 FunctionKind = 2;
1856 else if (isa<CXXDestructorDecl>(CurDecl))
1857 FunctionKind = 3;
1858
Nick Lewycky1be750a2011-06-01 07:44:31 +00001859 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00001860 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00001861 << RetValExp->getSourceRange();
1862 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00001863 }
Mike Stump11289f42009-09-09 15:08:12 +00001864
John McCallacf0ee52010-10-08 02:01:28 +00001865 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001866 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001869 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1870 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001871 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1872 // C99 6.8.6.4p1 (ext_ since GCC warns)
1873 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1874
1875 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001876 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001877 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001878 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001879 Result = new (Context) ReturnStmt(ReturnLoc);
1880 } else {
1881 const VarDecl *NRVOCandidate = 0;
1882 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1883 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001884
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001885 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1886 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1887 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001888
John McCallfa272342011-06-16 23:24:51 +00001889 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001890 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001891 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001893 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00001894 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001896 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001897 if (Res.isInvalid()) {
1898 // FIXME: Cleanup temporaries here, anyway?
1899 return StmtError();
1900 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001901
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001902 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001904 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906
John McCallacf0ee52010-10-08 02:01:28 +00001907 if (RetValExp) {
Douglas Gregor33823722011-06-11 01:09:30 +00001908 // If we type-checked an Objective-C method's return type based
1909 // on a related return type, we may need to adjust the return
1910 // type again. Do so now.
1911 if (DeclaredRetType != FnRetType) {
1912 ExprResult result = PerformImplicitConversion(RetValExp,
1913 DeclaredRetType,
1914 AA_Returning);
1915 if (result.isInvalid()) return StmtError();
1916 RetValExp = result.take();
1917 }
1918
John McCallacf0ee52010-10-08 02:01:28 +00001919 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001920 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001921 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001922 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00001923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924
1925 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001926 // return statement in our scope for later processing.
1927 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1928 !CurContext->isDependentContext())
1929 FunctionScopes.back()->Returns.push_back(Result);
John McCall31168b02011-06-15 23:02:42 +00001930
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001931 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001932}
1933
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001934/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1935/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1936/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1937/// provide a strong guidance to not use it.
1938///
1939/// This method checks to see if the argument is an acceptable l-value and
1940/// returns false if it is a case we can handle.
1941static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00001942 // Type dependent expressions will be checked during instantiation.
1943 if (E->isTypeDependent())
1944 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
John McCall086a4642010-11-24 05:12:34 +00001946 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001947 return false; // Cool, this is an lvalue.
1948
1949 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1950 // are supposed to allow.
1951 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00001952 if (E != E2 && E2->isLValue()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001953 if (!S.getLangOptions().HeinousExtensions)
1954 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1955 << E->getSourceRange();
1956 else
1957 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1958 << E->getSourceRange();
1959 // Accept, even if we emitted an error diagnostic.
1960 return false;
1961 }
1962
1963 // None of the above, just randomly invalid non-lvalue.
1964 return true;
1965}
1966
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001967/// isOperandMentioned - Return true if the specified operand # is mentioned
1968/// anywhere in the decomposed asm string.
1969static bool isOperandMentioned(unsigned OpNo,
Chris Lattner54b16772011-07-23 17:14:25 +00001970 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001971 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1972 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1973 if (!Piece.isOperand()) continue;
1974
1975 // If this is a reference to the input and if the input was the smaller
1976 // one, then we have to reject this asm.
1977 if (Piece.getOperandNo() == OpNo)
1978 return true;
1979 }
1980
1981 return false;
1982}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001983
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001984StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1985 bool IsVolatile, unsigned NumOutputs,
1986 unsigned NumInputs, IdentifierInfo **Names,
1987 MultiExprArg constraints, MultiExprArg exprs,
1988 Expr *asmString, MultiExprArg clobbers,
1989 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001990 unsigned NumClobbers = clobbers.size();
1991 StringLiteral **Constraints =
1992 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00001993 Expr **Exprs = exprs.get();
1994 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00001995 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1996
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001997 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00001998
Chris Lattner496acc12008-08-18 19:55:17 +00001999 // The parser verifies that there is a string literal here.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002000 if (!AsmString->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002001 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2002 << AsmString->getSourceRange());
2003
Chris Lattner496acc12008-08-18 19:55:17 +00002004 for (unsigned i = 0; i != NumOutputs; i++) {
2005 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002006 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002007 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2008 << Literal->getSourceRange());
2009
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002010 StringRef OutputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002011 if (Names[i])
2012 OutputName = Names[i]->getName();
2013
2014 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002015 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002016 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002017 diag::err_asm_invalid_output_constraint)
2018 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00002019
Anders Carlssonf511f642007-11-27 04:11:28 +00002020 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00002021 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002022 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00002023 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002024 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00002025 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002026 }
Mike Stump11289f42009-09-09 15:08:12 +00002027
Chris Lattnerd9725f72009-04-26 07:16:29 +00002028 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002029 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002030
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002031 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner34b51e82009-05-03 05:55:43 +00002032
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002033 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00002034 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002035 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002036 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2037 << Literal->getSourceRange());
2038
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002039 StringRef InputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002040 if (Names[i])
2041 InputName = Names[i]->getName();
2042
2043 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foad7d0479f2009-05-21 09:52:38 +00002044 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00002045 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002046 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002047 diag::err_asm_invalid_input_constraint)
2048 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00002049 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002050
Eli Friedman47e78572009-05-03 07:49:42 +00002051 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00002052
Anders Carlsson224fca82009-01-20 20:49:22 +00002053 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00002054 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002055 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00002056 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002057 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002058 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002059 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002060 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002061
Chris Lattnerd9725f72009-04-26 07:16:29 +00002062 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00002063 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00002064 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002065 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00002066 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002067 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00002068 }
Anders Carlsson224fca82009-01-20 20:49:22 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
John Wiegley01296292011-04-08 18:41:53 +00002071 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2072 if (Result.isInvalid())
2073 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002074
John Wiegley01296292011-04-08 18:41:53 +00002075 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00002076 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002077 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002078
Anders Carlsson290aa852007-11-25 00:25:21 +00002079 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00002080 for (unsigned i = 0; i != NumClobbers; i++) {
2081 StringLiteral *Literal = Clobbers[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002082 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002083 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2084 << Literal->getSourceRange());
2085
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002086 StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00002087
Eric Christopherfd9a5f42011-06-28 18:20:53 +00002088 if (!Context.Target.isValidClobber(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002089 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00002090 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00002091 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002092
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002093 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2095 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00002096 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002097 // Validate the asm string, ensuring it makes sense given the operands we
2098 // have.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002099 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002100 unsigned DiagOffs;
2101 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00002102 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2103 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002104 return StmtError();
2105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattner34b51e82009-05-03 05:55:43 +00002107 // Validate tied input operands for type mismatches.
2108 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2109 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00002110
Chris Lattner34b51e82009-05-03 05:55:43 +00002111 // If this is a tied constraint, verify that the output and input have
2112 // either exactly the same type, or that they are int/ptr operands with the
2113 // same size (int/long, int*/long, are ok etc).
2114 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattner34b51e82009-05-03 05:55:43 +00002116 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00002117 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00002118 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00002119 Expr *InputExpr = Exprs[InputOpNo];
Chris Lattner2c295cf2009-05-03 05:59:17 +00002120 QualType InTy = InputExpr->getType();
2121 QualType OutTy = OutputExpr->getType();
2122 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00002123 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002125 // Decide if the input and output are in the same domain (integer/ptr or
2126 // floating point.
2127 enum AsmDomain {
2128 AD_Int, AD_FP, AD_Other
2129 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002131 if (InTy->isIntegerType() || InTy->isPointerType())
2132 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002133 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002134 InputDomain = AD_FP;
2135 else
2136 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00002137
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002138 if (OutTy->isIntegerType() || OutTy->isPointerType())
2139 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002140 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002141 OutputDomain = AD_FP;
2142 else
2143 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002145 // They are ok if they are the same size and in the same domain. This
2146 // allows tying things like:
2147 // void* to int*
2148 // void* to int if they are the same size.
2149 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002151 uint64_t OutSize = Context.getTypeSize(OutTy);
2152 uint64_t InSize = Context.getTypeSize(InTy);
2153 if (OutSize == InSize && InputDomain == OutputDomain &&
2154 InputDomain != AD_Other)
2155 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002157 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00002158 // then we can promote the smaller one to a larger input and the asm string
2159 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002160 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002161
2162 // If this is a reference to the input and if the input was the smaller
2163 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00002164 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002165 // This is a use in the asm string of the smaller operand. Since we
2166 // codegen this by promoting to a wider value, the asm will get printed
2167 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00002168 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002169 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002170 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002171 // If this is a reference to the output, and if the output is the larger
2172 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002173 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002176 // If the smaller value wasn't mentioned in the asm string, and if the
2177 // output was a register, just extend the shorter one to the size of the
2178 // larger one.
2179 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2180 OutputConstraintInfos[TiedTo].allowsRegister())
2181 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00002182
Chris Lattner93ede022011-02-21 22:09:29 +00002183 // Either both of the operands were mentioned or the smaller one was
2184 // mentioned. One more special case that we'll allow: if the tied input is
2185 // integer, unmentioned, and is a constant, then we'll allow truncating it
2186 // down to the size of the destination.
2187 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2188 !isOperandMentioned(InputOpNo, Pieces) &&
2189 InputExpr->isEvaluatable(Context)) {
John McCalldfbf9342011-05-10 23:39:47 +00002190 CastKind castKind =
2191 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2192 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002193 Exprs[InputOpNo] = InputExpr;
2194 NS->setInputExpr(i, InputExpr);
2195 continue;
2196 }
2197
Chris Lattner28b05c82009-05-03 06:50:40 +00002198 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002199 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002200 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002201 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002202 return StmtError();
2203 }
Mike Stump11289f42009-09-09 15:08:12 +00002204
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002205 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002206}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002207
John McCalldadc5752010-08-24 06:29:42 +00002208StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002209Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002210 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002211 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002212 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002213 if (Var && Var->isInvalidDecl())
2214 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002215
John McCallb268a282010-08-23 23:25:46 +00002216 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002217}
2218
John McCalldadc5752010-08-24 06:29:42 +00002219StmtResult
John McCallb268a282010-08-23 23:25:46 +00002220Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2221 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002222}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002223
John McCalldadc5752010-08-24 06:29:42 +00002224StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002225Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002226 MultiStmtArg CatchStmts, Stmt *Finally) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002227 if (!getLangOptions().ObjCExceptions)
2228 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2229
John McCallaab3e412010-08-25 08:40:02 +00002230 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002231 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002232 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2233 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002234 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002235 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002236}
2237
John McCalldadc5752010-08-24 06:29:42 +00002238StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCallb268a282010-08-23 23:25:46 +00002239 Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002240 if (Throw) {
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002241 Throw = MaybeCreateExprWithCleanups(Throw);
John Wiegley01296292011-04-08 18:41:53 +00002242 ExprResult Result = DefaultLvalueConversion(Throw);
2243 if (Result.isInvalid())
2244 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002245
John Wiegley01296292011-04-08 18:41:53 +00002246 Throw = Result.take();
Douglas Gregor2900c162010-04-22 21:44:01 +00002247 QualType ThrowType = Throw->getType();
2248 // Make sure the expression type is an ObjC pointer or "void *".
2249 if (!ThrowType->isDependentType() &&
2250 !ThrowType->isObjCObjectPointerType()) {
2251 const PointerType *PT = ThrowType->getAs<PointerType>();
2252 if (!PT || !PT->getPointeeType()->isVoidType())
2253 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2254 << Throw->getType() << Throw->getSourceRange());
2255 }
2256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002257
John McCallb268a282010-08-23 23:25:46 +00002258 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002259}
2260
John McCalldadc5752010-08-24 06:29:42 +00002261StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002263 Scope *CurScope) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002264 if (!getLangOptions().ObjCExceptions)
2265 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2266
John McCallb268a282010-08-23 23:25:46 +00002267 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002268 // @throw without an expression designates a rethrow (which much occur
2269 // in the context of an @catch clause).
2270 Scope *AtCatchParent = CurScope;
2271 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2272 AtCatchParent = AtCatchParent->getParent();
2273 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002274 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002275 }
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002276
John McCallb268a282010-08-23 23:25:46 +00002277 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002278}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002279
John McCalld9bb7432011-07-27 21:50:02 +00002280ExprResult
2281Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2282 ExprResult result = DefaultLvalueConversion(operand);
2283 if (result.isInvalid())
2284 return ExprError();
2285 operand = result.take();
2286
2287 // Make sure the expression type is an ObjC pointer or "void *".
2288 QualType type = operand->getType();
2289 if (!type->isDependentType() &&
2290 !type->isObjCObjectPointerType()) {
2291 const PointerType *pointerType = type->getAs<PointerType>();
2292 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2293 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2294 << type << operand->getSourceRange();
2295 }
2296
2297 // The operand to @synchronized is a full-expression.
2298 return MaybeCreateExprWithCleanups(operand);
2299}
2300
John McCalldadc5752010-08-24 06:29:42 +00002301StmtResult
John McCallb268a282010-08-23 23:25:46 +00002302Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2303 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00002304 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00002305 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00002306 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002307}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002308
2309/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2310/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002311StmtResult
John McCall48871652010-08-21 09:40:31 +00002312Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002313 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002314 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002315 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002316 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002317 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002318}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002319
John McCall31168b02011-06-15 23:02:42 +00002320StmtResult
2321Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2322 getCurFunction()->setHasBranchProtectedScope();
2323 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2324}
2325
Dan Gohman28ade552010-07-26 21:25:24 +00002326namespace {
2327
Sebastian Redl63c4da02009-07-29 17:15:45 +00002328class TypeWithHandler {
2329 QualType t;
2330 CXXCatchStmt *stmt;
2331public:
2332 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2333 : t(type), stmt(statement) {}
2334
John McCall8ccfcb52009-09-24 19:53:00 +00002335 // An arbitrary order is fine as long as it places identical
2336 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002337 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002338 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002339 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002340 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002341 return false;
2342 else
2343 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2344 }
Mike Stump11289f42009-09-09 15:08:12 +00002345
Sebastian Redl63c4da02009-07-29 17:15:45 +00002346 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002347 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002348 }
Mike Stump11289f42009-09-09 15:08:12 +00002349
Sebastian Redl63c4da02009-07-29 17:15:45 +00002350 CXXCatchStmt *getCatchStmt() const { return stmt; }
2351 SourceLocation getTypeSpecStartLoc() const {
2352 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2353 }
2354};
2355
Dan Gohman28ade552010-07-26 21:25:24 +00002356}
2357
Sebastian Redl9b244a82008-12-22 21:35:02 +00002358/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2359/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002360StmtResult
John McCallb268a282010-08-23 23:25:46 +00002361Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002362 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002363 // Don't report an error if 'try' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +00002364 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002365 !getSourceManager().isInSystemHeader(TryLoc))
2366 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002367
Sebastian Redl9b244a82008-12-22 21:35:02 +00002368 unsigned NumHandlers = RawHandlers.size();
2369 assert(NumHandlers > 0 &&
2370 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00002371 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002372
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002373 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002374
2375 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002376 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002377 if (!Handler->getExceptionDecl()) {
2378 if (i < NumHandlers - 1)
2379 return StmtError(Diag(Handler->getLocStart(),
2380 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002381
Sebastian Redl63c4da02009-07-29 17:15:45 +00002382 continue;
2383 }
Mike Stump11289f42009-09-09 15:08:12 +00002384
Sebastian Redl63c4da02009-07-29 17:15:45 +00002385 const QualType CaughtType = Handler->getCaughtType();
2386 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2387 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002388 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002389
2390 // Detect handlers for the same type as an earlier one.
2391 if (NumHandlers > 1) {
2392 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002393
Sebastian Redl63c4da02009-07-29 17:15:45 +00002394 TypeWithHandler prev = TypesWithHandlers[0];
2395 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2396 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002397
Sebastian Redl63c4da02009-07-29 17:15:45 +00002398 if (curr == prev) {
2399 Diag(curr.getTypeSpecStartLoc(),
2400 diag::warn_exception_caught_by_earlier_handler)
2401 << curr.getCatchStmt()->getCaughtType().getAsString();
2402 Diag(prev.getTypeSpecStartLoc(),
2403 diag::note_previous_exception_handler)
2404 << prev.getCatchStmt()->getCaughtType().getAsString();
2405 }
Mike Stump11289f42009-09-09 15:08:12 +00002406
Sebastian Redl63c4da02009-07-29 17:15:45 +00002407 prev = curr;
2408 }
2409 }
Mike Stump11289f42009-09-09 15:08:12 +00002410
John McCallaab3e412010-08-25 08:40:02 +00002411 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002412
Sebastian Redl9b244a82008-12-22 21:35:02 +00002413 // FIXME: We should detect handlers that cannot catch anything because an
2414 // earlier handler catches a superclass. Need to find a method that is not
2415 // quadratic for this.
2416 // Neither of these are explicitly forbidden, but every compiler detects them
2417 // and warns.
2418
John McCallb268a282010-08-23 23:25:46 +00002419 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002420 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002421}
John Wiegley1c0675e2011-04-28 01:08:34 +00002422
2423StmtResult
2424Sema::ActOnSEHTryBlock(bool IsCXXTry,
2425 SourceLocation TryLoc,
2426 Stmt *TryBlock,
2427 Stmt *Handler) {
2428 assert(TryBlock && Handler);
2429
2430 getCurFunction()->setHasBranchProtectedScope();
2431
2432 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2433}
2434
2435StmtResult
2436Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2437 Expr *FilterExpr,
2438 Stmt *Block) {
2439 assert(FilterExpr && Block);
2440
2441 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00002442 return StmtError(Diag(FilterExpr->getExprLoc(),
2443 diag::err_filter_expression_integral)
2444 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00002445 }
2446
2447 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2448}
2449
2450StmtResult
2451Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2452 Stmt *Block) {
2453 assert(Block);
2454 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2455}