blob: e957a4b93f85385f78ca7120f6e77db130a93bae [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"
Anders Carlsson59689ed2008-11-22 21:04:56 +000018#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000023#include "clang/AST/StmtObjC.h"
24#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000026#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000027#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000028#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000031using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000032using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000033
John McCalldadc5752010-08-24 06:29:42 +000034StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000035 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000036 if (!E) // FIXME: FullExprArg has no error state?
37 return StmtError();
38
Chris Lattner903eb512008-07-25 23:18:17 +000039 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
40 // void expression for its side effects. Conversion to void allows any
41 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000042
Chris Lattner903eb512008-07-25 23:18:17 +000043 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000044 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000045}
46
47
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +000048StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool LeadingEmptyMacro) {
49 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000050}
51
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000052StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
53 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000054 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000055
Chris Lattnercbafe8d2009-04-12 20:13:14 +000056 // If we have an invalid decl, just return an error.
57 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000058
Chris Lattner34a22092009-03-04 04:23:07 +000059 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000060}
Chris Lattneraf8d5812006-11-10 05:07:45 +000061
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000062void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
63 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000064
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000065 // If we have an invalid decl, just return.
66 if (DG.isNull() || !DG.isSingleDecl()) return;
67 // suppress any potential 'unused variable' warning.
68 DG.getSingleDecl()->setUsed();
69}
70
Anders Carlsson59a2ab92009-07-30 22:17:18 +000071void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +000072 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
73 return DiagnoseUnusedExprResult(Label->getSubStmt());
74
Anders Carlsson5c5f1602009-07-30 22:39:03 +000075 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +000076 if (!E)
77 return;
78
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000079 if (E->isBoundMemberFunction(Context)) {
80 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
81 << E->getSourceRange();
82 return;
83 }
84
Anders Carlsson59a2ab92009-07-30 22:17:18 +000085 SourceLocation Loc;
86 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +000087 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +000088 return;
Mike Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner2ba5ca92009-08-16 16:57:27 +000090 // Okay, we have an unused result. Depending on what the base expression is,
91 // we might want to make a more specific diagnostic. Check for one of these
92 // cases now.
93 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +000094 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +000095 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +000096 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
97 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +000098
John McCall34376a62010-12-04 03:47:34 +000099 E = E->IgnoreParenImpCasts();
Chris Lattner1a6babf2009-10-13 04:53:48 +0000100 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000101 if (E->getType()->isVoidType())
102 return;
103
Chris Lattner1a6babf2009-10-13 04:53:48 +0000104 // If the callee has attribute pure, const, or warn_unused_result, warn with
105 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000106 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000107 if (FD->getAttr<WarnUnusedResultAttr>()) {
108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
109 return;
110 }
111 if (FD->getAttr<PureAttr>()) {
112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
113 return;
114 }
115 if (FD->getAttr<ConstAttr>()) {
116 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
117 return;
118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000119 }
John McCallb7bd14f2010-12-02 01:19:52 +0000120 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000121 const ObjCMethodDecl *MD = ME->getMethodDecl();
122 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
123 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
124 return;
125 }
John McCallb7bd14f2010-12-02 01:19:52 +0000126 } else if (isa<ObjCPropertyRefExpr>(E)) {
127 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000128 } else if (const CXXFunctionalCastExpr *FC
129 = dyn_cast<CXXFunctionalCastExpr>(E)) {
130 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
131 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
132 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000133 }
John McCall2351cb92010-04-06 22:24:14 +0000134 // Diagnose "(void*) blah" as a typo for "(void) blah".
135 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
136 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
137 QualType T = TI->getType();
138
139 // We really do want to use the non-canonical type here.
140 if (T == Context.VoidPtrTy) {
141 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
142
143 Diag(Loc, diag::warn_unused_voidptr)
144 << FixItHint::CreateRemoval(TL.getStarLoc());
145 return;
146 }
147 }
148
Ted Kremenek3427fac2011-02-23 01:52:04 +0000149 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000150}
151
John McCalldadc5752010-08-24 06:29:42 +0000152StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000153Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000154 MultiStmtArg elts, bool isStmtExpr) {
155 unsigned NumElts = elts.size();
156 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000157 // If we're in C89 mode, check that we don't have any decls after stmts. If
158 // so, emit an extension diagnostic.
159 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
160 // Note that __extension__ can be around a decl.
161 unsigned i = 0;
162 // Skip over all declarations.
163 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
164 /*empty*/;
165
166 // We found the end of the list or a statement. Scan for another declstmt.
167 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
168 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattnerd864daf2007-08-27 04:29:41 +0000170 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000171 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000172 Diag(D->getLocation(), diag::ext_mixed_decls_code);
173 }
174 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000175 // Warn about unused expressions in statements.
176 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000177 // Ignore statements that are last in a statement expression.
178 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000179 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000180
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000181 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000182 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000183
Ted Kremenek5a201952009-02-07 01:47:29 +0000184 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000185}
186
John McCalldadc5752010-08-24 06:29:42 +0000187StmtResult
John McCallb268a282010-08-23 23:25:46 +0000188Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
189 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000190 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000191 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000192
Steve Naroff8eeeb132007-05-08 21:09:37 +0000193 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000194 // However, GCC allows any evaluatable integer expression.
Mike Stump11289f42009-09-09 15:08:12 +0000195 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000196 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000197 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000198
Chris Lattner46eeb222007-07-18 02:28:47 +0000199 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000200
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000201 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
202 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000203 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000204 }
205
John McCallaab3e412010-08-25 08:40:02 +0000206 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000207 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000208 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000209 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000210
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000211 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
212 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000213 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000214 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000215}
216
Chris Lattner34a22092009-03-04 04:23:07 +0000217/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000218void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chris Lattner34a22092009-03-04 04:23:07 +0000219 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000220 CS->setSubStmt(SubStmt);
221}
222
John McCalldadc5752010-08-24 06:29:42 +0000223StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000224Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000225 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000226 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000227 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000228 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000229 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000230
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000231 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000232 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000233 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000234}
235
John McCalldadc5752010-08-24 06:29:42 +0000236StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000237Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
238 SourceLocation ColonLoc, Stmt *SubStmt) {
239
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000240 // If the label was multiply defined, reject it now.
241 if (TheDecl->getStmt()) {
242 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
243 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000244 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000245 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000246
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000247 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000248 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
249 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000250 if (!TheDecl->isGnuLocal())
251 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000252 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000253}
254
John McCalldadc5752010-08-24 06:29:42 +0000255StmtResult
John McCall48871652010-08-21 09:40:31 +0000256Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000257 Stmt *thenStmt, SourceLocation ElseLoc,
258 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000259 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregor633caca2009-11-23 23:44:04 +0000261 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000262 if (CondVar) {
263 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000264 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000265 if (CondResult.isInvalid())
266 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000267 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000268 Expr *ConditionExpr = CondResult.takeAs<Expr>();
269 if (!ConditionExpr)
270 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000271
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000272 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000273
Anders Carlssondb83d772007-10-10 20:50:11 +0000274 // Warn if the if block has a null body without an else value.
275 // this helps prevent bugs due to typos, such as
276 // if (condition);
277 // do_stuff();
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000278 //
John McCallb268a282010-08-23 23:25:46 +0000279 if (!elseStmt) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000280 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Argyrios Kyrtzidis90ee2a42010-11-19 20:54:25 +0000281 // But do not warn if the body is a macro that expands to nothing, e.g:
282 //
283 // #define CALL(x)
284 // if (condition)
285 // CALL(0);
286 //
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000287 if (!stmt->hasLeadingEmptyMacro())
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000288 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000289 }
290
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000291 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000292
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000294 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000295}
Steve Naroff86272ea2007-05-29 02:14:17 +0000296
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000297/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
298/// the specified width and sign. If an overflow occurs, detect it and emit
299/// the specified diagnostic.
300void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
301 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000302 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000303 unsigned DiagID) {
304 // Perform a conversion to the promoted condition type if needed.
305 if (NewWidth > Val.getBitWidth()) {
306 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000307 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000308 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000309
310 // If the input was signed and negative and the output is
311 // unsigned, don't bother to warn: this is implementation-defined
312 // behavior.
313 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000314 } else if (NewWidth < Val.getBitWidth()) {
315 // If this is a truncation, check for overflow.
316 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000317 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000318 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000319 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000320 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000321 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000322 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000324 // Regardless of whether a diagnostic was emitted, really do the
325 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000326 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000327 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000328 } else if (NewSign != Val.isSigned()) {
329 // Convert the sign to match the sign of the condition. This can cause
330 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000332 // behavior.
333 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000334 llvm::APSInt OldVal(Val);
335 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000336 }
337}
338
Chris Lattner67998452007-08-23 18:29:20 +0000339namespace {
340 struct CaseCompareFunctor {
341 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
342 const llvm::APSInt &RHS) {
343 return LHS.first < RHS;
344 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000345 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
346 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
347 return LHS.first < RHS.first;
348 }
Chris Lattner67998452007-08-23 18:29:20 +0000349 bool operator()(const llvm::APSInt &LHS,
350 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
351 return LHS < RHS.first;
352 }
353 };
354}
355
Chris Lattner4b2ff022007-09-21 18:15:22 +0000356/// CmpCaseVals - Comparison predicate for sorting case values.
357///
358static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
359 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
360 if (lhs.first < rhs.first)
361 return true;
362
363 if (lhs.first == rhs.first &&
364 lhs.second->getCaseLoc().getRawEncoding()
365 < rhs.second->getCaseLoc().getRawEncoding())
366 return true;
367 return false;
368}
369
Douglas Gregorbd6839732010-02-08 22:24:16 +0000370/// CmpEnumVals - Comparison predicate for sorting enumeration values.
371///
372static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
373 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
374{
375 return lhs.first < rhs.first;
376}
377
378/// EqEnumVals - Comparison preficate for uniqing enumeration values.
379///
380static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
381 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
382{
383 return lhs.first == rhs.first;
384}
385
Chris Lattnera96d4272009-10-16 16:45:22 +0000386/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
387/// potentially integral-promoted expression @p expr.
388static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
John McCall45d30c32010-06-12 01:56:02 +0000389 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
Chris Lattnera96d4272009-10-16 16:45:22 +0000390 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
391 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000392 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
Chris Lattnera96d4272009-10-16 16:45:22 +0000393 return TypeBeforePromotion;
394 }
395 }
396 return expr->getType();
397}
398
John McCalldadc5752010-08-24 06:29:42 +0000399StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000401 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000402 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000403
Douglas Gregore60e41a2010-05-06 17:25:47 +0000404 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000405 if (CondVar) {
406 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000407 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
408 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000409 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
John McCallb268a282010-08-23 23:25:46 +0000411 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
John McCallb268a282010-08-23 23:25:46 +0000414 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000415 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
John McCallb268a282010-08-23 23:25:46 +0000417 CondResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000419 PDiag(diag::err_typecheck_statement_requires_integer),
420 PDiag(diag::err_switch_incomplete_class_type)
John McCallb268a282010-08-23 23:25:46 +0000421 << Cond->getSourceRange(),
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000422 PDiag(diag::err_switch_explicit_conversion),
423 PDiag(diag::note_switch_conversion),
424 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000425 PDiag(diag::note_switch_conversion),
426 PDiag(0));
John McCallb268a282010-08-23 23:25:46 +0000427 if (CondResult.isInvalid()) return StmtError();
428 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429
John McCall48871652010-08-21 09:40:31 +0000430 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000431 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000432 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000433 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000434 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000435 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000436 }
John McCalla95172b2010-08-01 00:26:45 +0000437
John McCallaab3e412010-08-25 08:40:02 +0000438 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439
John McCallb268a282010-08-23 23:25:46 +0000440 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000441 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000442 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000443}
444
Gabor Greif16e02862010-10-01 22:05:14 +0000445static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
446 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000447 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000448 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000449 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000450 Val.setIsSigned(IsSigned);
451}
452
John McCalldadc5752010-08-24 06:29:42 +0000453StmtResult
John McCallb268a282010-08-23 23:25:46 +0000454Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
455 Stmt *BodyStmt) {
456 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000457 assert(SS == getCurFunction()->SwitchStack.back() &&
458 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000459
Steve Naroff42a350a2007-09-01 21:08:38 +0000460 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000461 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000462
Douglas Gregorb412e172010-07-25 18:17:45 +0000463 if (SS->getCond() == 0)
Douglas Gregor3ff3af42009-11-25 06:20:02 +0000464 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000466 Expr *CondExpr = SS->getCond();
John McCalld3dfbd62010-05-18 03:19:21 +0000467 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000468 QualType CondTypeBeforePromotion =
469 GetTypeBeforeIntegralPromotion(CondExpr);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000470
Douglas Gregor7fdcbaf22009-11-25 15:17:36 +0000471 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
John Wiegley01296292011-04-08 18:41:53 +0000472 ExprResult CondResult = UsualUnaryConversions(CondExpr);
473 if (CondResult.isInvalid())
474 return StmtError();
475 CondExpr = CondResult.take();
Douglas Gregor11075552009-11-25 05:02:21 +0000476 QualType CondType = CondExpr->getType();
Douglas Gregord0c22e02009-11-23 13:46:08 +0000477 SS->setCond(CondExpr);
478
Chris Lattnera96d4272009-10-16 16:45:22 +0000479 // C++ 6.4.2.p2:
480 // Integral promotions are performed (on the switch condition).
481 //
482 // A case value unrepresentable by the original switch condition
483 // type (before the promotion) doesn't make sense, even when it can
484 // be represented by the promoted type. Therefore we need to find
485 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000486 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000487 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000489 // appropriate type now, just return an error.
490 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000491 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000492
Chris Lattner4ebae652010-04-16 23:34:13 +0000493 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000494 // switch(bool_expr) {...} is often a programmer error, e.g.
495 // switch(n && mask) { ... } // Doh - should be "n & mask".
496 // One can always use an if statement instead of switch(bool_expr).
497 Diag(SwitchLoc, diag::warn_bool_switch_condition)
498 << CondExpr->getSourceRange();
499 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000500 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000501
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000502 // Get the bitwidth of the switched-on value before promotions. We must
503 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000504 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000505 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000506 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000507 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chris Lattnera96d4272009-10-16 16:45:22 +0000508 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000510 // Accumulate all of the case values in a vector so that we can sort them
511 // and detect duplicates. This vector contains the APInt for the case after
512 // it has been converted to the condition type.
Chris Lattner67998452007-08-23 18:29:20 +0000513 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
514 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000516 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000517 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
518 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000520 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattner10cb5e52007-08-23 06:23:56 +0000522 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000524 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000525 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000526
Anders Carlsson51873c22007-07-22 07:07:56 +0000527 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000528 if (TheDefaultStmt) {
529 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000530 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000531
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000532 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000533 // we'll return a valid AST. This requires recursing down the AST and
534 // finding it, not something we are set up to do right now. For now,
535 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000536 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000537 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000538 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000540 } else {
541 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000542
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000543 // We already verified that the expression has a i-c-e value (C99
544 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000545 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000546
547 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
548 HasDependentValue = true;
549 break;
550 }
Mike Stump11289f42009-09-09 15:08:12 +0000551
Anders Carlsson59689ed2008-11-22 21:04:56 +0000552 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000553
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000554 // Convert the value to the same width/sign as the condition.
555 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000556 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000557 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000558
Chris Lattnera65e1f32008-01-16 19:17:22 +0000559 // If the LHS is not the same type as the condition, insert an implicit
560 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000561 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
Chris Lattnera65e1f32008-01-16 19:17:22 +0000562 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattner10cb5e52007-08-23 06:23:56 +0000564 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000565 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000566 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000567 CS->getRHS()->isValueDependent()) {
568 HasDependentValue = true;
569 break;
570 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000571 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000572 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000573 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000574 }
575 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000576
577 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000578 // If we don't have a default statement, check whether the
579 // condition is constant.
580 llvm::APSInt ConstantCondValue;
581 bool HasConstantCond = false;
582 bool ShouldCheckConstantCond = false;
583 if (!HasDependentValue && !TheDefaultStmt) {
584 Expr::EvalResult Result;
585 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
586 if (HasConstantCond) {
587 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
588 ConstantCondValue = Result.Val.getInt();
589 ShouldCheckConstantCond = true;
590
591 assert(ConstantCondValue.getBitWidth() == CondWidth &&
592 ConstantCondValue.isSigned() == CondIsSigned);
593 }
594 }
595
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000596 // Sort all the scalar case values so we can easily detect duplicates.
597 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
598
599 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000600 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
601 if (ShouldCheckConstantCond &&
602 CaseVals[i].first == ConstantCondValue)
603 ShouldCheckConstantCond = false;
604
605 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000606 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000607 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000608 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
609 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000610 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000611 // FIXME: We really want to remove the bogus case stmt from the
612 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000613 CaseListIsErroneous = true;
614 }
615 }
616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000618 // Detect duplicate case ranges, which usually don't exist at all in
619 // the first place.
620 if (!CaseRanges.empty()) {
621 // Sort all the case ranges by their low value so we can easily detect
622 // overlaps between ranges.
623 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000624
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000625 // Scan the ranges, computing the high values and removing empty ranges.
626 std::vector<llvm::APSInt> HiVals;
627 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000628 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000629 CaseStmt *CR = CaseRanges[i].second;
630 Expr *Hi = CR->getRHS();
631 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000632
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000633 // Convert the value to the same width/sign as the condition.
634 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000635 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000636 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000637
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000638 // If the LHS is not the same type as the condition, insert an implicit
639 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000640 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000641 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000642
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000643 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000644 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000645 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
646 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000647 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000648 CaseRanges.erase(CaseRanges.begin()+i);
649 --i, --e;
650 continue;
651 }
John McCalld3dfbd62010-05-18 03:19:21 +0000652
653 if (ShouldCheckConstantCond &&
654 LoVal <= ConstantCondValue &&
655 ConstantCondValue <= HiVal)
656 ShouldCheckConstantCond = false;
657
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000658 HiVals.push_back(HiVal);
659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000661 // Rescan the ranges, looking for overlap with singleton values and other
662 // ranges. Since the range list is sorted, we only need to compare case
663 // ranges with their neighbors.
664 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
665 llvm::APSInt &CRLo = CaseRanges[i].first;
666 llvm::APSInt &CRHi = HiVals[i];
667 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000668
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000669 // Check to see whether the case range overlaps with any
670 // singleton cases.
671 CaseStmt *OverlapStmt = 0;
672 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000673
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000674 // Find the smallest value >= the lower bound. If I is in the
675 // case range, then we have overlap.
676 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
677 CaseVals.end(), CRLo,
678 CaseCompareFunctor());
679 if (I != CaseVals.end() && I->first < CRHi) {
680 OverlapVal = I->first; // Found overlap with scalar.
681 OverlapStmt = I->second;
682 }
Mike Stump11289f42009-09-09 15:08:12 +0000683
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000684 // Find the smallest value bigger than the upper bound.
685 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
686 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
687 OverlapVal = (I-1)->first; // Found overlap with scalar.
688 OverlapStmt = (I-1)->second;
689 }
Mike Stump11289f42009-09-09 15:08:12 +0000690
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000691 // Check to see if this case stmt overlaps with the subsequent
692 // case range.
693 if (i && CRLo <= HiVals[i-1]) {
694 OverlapVal = HiVals[i-1]; // Found overlap with range.
695 OverlapStmt = CaseRanges[i-1].second;
696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000698 if (OverlapStmt) {
699 // If we have a duplicate, report it.
700 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
701 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000702 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000703 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000704 // FIXME: We really want to remove the bogus case stmt from the
705 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000706 CaseListIsErroneous = true;
707 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000708 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000709 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000710
John McCalld3dfbd62010-05-18 03:19:21 +0000711 // Complain if we have a constant condition and we didn't find a match.
712 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
713 // TODO: it would be nice if we printed enums as enums, chars as
714 // chars, etc.
715 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
716 << ConstantCondValue.toString(10)
717 << CondExpr->getSourceRange();
718 }
719
720 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000721 // values. We only issue a warning if there is not 'default:', but
722 // we still do the analysis to preserve this information in the AST
723 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000724 //
Chris Lattner51679082010-09-16 17:09:42 +0000725 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000726
Douglas Gregorbd6839732010-02-08 22:24:16 +0000727 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000728 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000729 const EnumDecl *ED = ET->getDecl();
730 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
731 EnumValsTy EnumVals;
732
John McCalld3dfbd62010-05-18 03:19:21 +0000733 // Gather all enum values, set their type and sort them,
734 // allowing easier comparison with CaseVals.
735 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000736 EDI != ED->enumerator_end(); ++EDI) {
737 llvm::APSInt Val = EDI->getInitVal();
738 AdjustAPSInt(Val, CondWidth, CondIsSigned);
739 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000740 }
741 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000742 EnumValsTy::iterator EIend =
743 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000744
745 // See which case values aren't in enum.
746 // TODO: we might want to check whether case values are out of the
747 // enum even if we don't want to check whether all cases are handled.
748 if (!TheDefaultStmt) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000749 EnumValsTy::const_iterator EI = EnumVals.begin();
750 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000751 CI != CaseVals.end(); CI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000752 while (EI != EIend && EI->first < CI->first)
753 EI++;
754 if (EI == EIend || EI->first > CI->first)
John McCalld3dfbd62010-05-18 03:19:21 +0000755 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
756 << ED->getDeclName();
Ted Kremenek02627a22010-09-09 06:53:59 +0000757 }
758 // See which of case ranges aren't in enum
759 EI = EnumVals.begin();
760 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000761 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000762 while (EI != EIend && EI->first < RI->first)
763 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764
Ted Kremenek02627a22010-09-09 06:53:59 +0000765 if (EI == EIend || EI->first != RI->first) {
766 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
767 << ED->getDeclName();
768 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000769
Ted Kremenek02627a22010-09-09 06:53:59 +0000770 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000771 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Ted Kremenek02627a22010-09-09 06:53:59 +0000772 while (EI != EIend && EI->first < Hi)
773 EI++;
774 if (EI == EIend || EI->first != Hi)
775 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
776 << ED->getDeclName();
777 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Ted Kremenekc42f3452010-09-09 00:05:53 +0000780 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000781 CaseValsTy::const_iterator CI = CaseVals.begin();
782 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000783 bool hasCasesNotInSwitch = false;
784
Chris Lattner51679082010-09-16 17:09:42 +0000785 llvm::SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000786
Ted Kremenekc42f3452010-09-09 00:05:53 +0000787 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000788 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000789 llvm::APSInt CIVal;
790 while (CI != CaseVals.end() && CI->first < EI->first)
791 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000792
Douglas Gregorbd6839732010-02-08 22:24:16 +0000793 if (CI != CaseVals.end() && CI->first == EI->first)
794 continue;
795
Ted Kremenekc42f3452010-09-09 00:05:53 +0000796 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +0000797 for (; RI != CaseRanges.end(); RI++) {
798 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000799 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000800 if (EI->first <= Hi)
801 break;
802 }
803
Ted Kremenekc42f3452010-09-09 00:05:53 +0000804 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000805 hasCasesNotInSwitch = true;
806 if (!TheDefaultStmt)
Chris Lattner51679082010-09-16 17:09:42 +0000807 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +0000808 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Chris Lattner51679082010-09-16 17:09:42 +0000811 // Produce a nice diagnostic if multiple values aren't handled.
812 switch (UnhandledNames.size()) {
813 case 0: break;
814 case 1:
815 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
816 << UnhandledNames[0];
817 break;
818 case 2:
819 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
820 << UnhandledNames[0] << UnhandledNames[1];
821 break;
822 case 3:
823 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
824 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
825 break;
826 default:
827 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
828 << (unsigned)UnhandledNames.size()
829 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
830 break;
831 }
Ted Kremenekc42f3452010-09-09 00:05:53 +0000832
833 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +0000834 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000835 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000836 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000837
Mike Stump87c57ac2009-05-16 07:39:55 +0000838 // FIXME: If the case list was broken is some way, we don't have a good system
839 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000840 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000841 return StmtError();
842
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000843 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000844}
845
John McCalldadc5752010-08-24 06:29:42 +0000846StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +0000848 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +0000849 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Douglas Gregor680f8612009-11-24 21:15:44 +0000851 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000852 if (CondVar) {
853 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000854 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000855 if (CondResult.isInvalid())
856 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +0000857 }
John McCallb268a282010-08-23 23:25:46 +0000858 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000859 if (!ConditionExpr)
860 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861
John McCallb268a282010-08-23 23:25:46 +0000862 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +0000863
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000864 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +0000865 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000866}
867
John McCalldadc5752010-08-24 06:29:42 +0000868StmtResult
John McCallb268a282010-08-23 23:25:46 +0000869Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000870 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +0000871 Expr *Cond, SourceLocation CondRParen) {
872 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000873
John Wiegley01296292011-04-08 18:41:53 +0000874 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
875 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +0000876 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +0000877 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +0000878
John McCallacf0ee52010-10-08 02:01:28 +0000879 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +0000880 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000881 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000882 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000883 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
John McCallb268a282010-08-23 23:25:46 +0000885 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000886
John McCallb268a282010-08-23 23:25:46 +0000887 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000888}
889
John McCalldadc5752010-08-24 06:29:42 +0000890StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000891Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +0000892 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000893 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +0000894 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000895 if (!getLangOptions().CPlusPlus) {
896 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000897 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
898 // declare identifiers for objects having storage class 'auto' or
899 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000900 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
901 DI!=DE; ++DI) {
902 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +0000903 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000904 VD = 0;
905 if (VD == 0)
906 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
907 // FIXME: mark decl erroneous!
908 }
Chris Lattner39f920f2007-08-28 05:03:08 +0000909 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000910 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000911
John McCalldadc5752010-08-24 06:29:42 +0000912 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000913 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000914 if (secondVar) {
915 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000916 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000917 if (SecondResult.isInvalid())
918 return StmtError();
919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000921 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000922
Anders Carlsson1682af52009-08-01 01:39:59 +0000923 DiagnoseUnusedExprResult(First);
924 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000925 DiagnoseUnusedExprResult(Body);
926
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 return Owned(new (Context) ForStmt(Context, First,
928 SecondResult.take(), ConditionVar,
929 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000930 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000931}
932
John McCall34376a62010-12-04 03:47:34 +0000933/// In an Objective C collection iteration statement:
934/// for (x in y)
935/// x can be an arbitrary l-value expression. Bind it up as a
936/// full-expression.
937StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
938 CheckImplicitConversions(E);
John McCall5d413782010-12-06 08:20:24 +0000939 ExprResult Result = MaybeCreateExprWithCleanups(E);
John McCall34376a62010-12-04 03:47:34 +0000940 if (Result.isInvalid()) return StmtError();
941 return Owned(static_cast<Stmt*>(Result.get()));
942}
943
John McCalldadc5752010-08-24 06:29:42 +0000944StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000945Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
946 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +0000947 Stmt *First, Expr *Second,
948 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +0000949 if (First) {
950 QualType FirstType;
951 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +0000952 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000953 return StmtError(Diag((*DS->decl_begin())->getLocation(),
954 diag::err_toomany_element_decls));
955
Chris Lattner529efc72009-03-28 06:33:19 +0000956 Decl *D = DS->getSingleDecl();
Ted Kremenek11b00422008-10-06 20:58:11 +0000957 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +0000958 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
959 // declare identifiers for objects having storage class 'auto' or
960 // 'register'.
Steve Naroff08899ff2008-04-15 22:42:06 +0000961 VarDecl *VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000962 if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000963 return StmtError(Diag(VD->getLocation(),
964 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000965 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +0000966 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +0000967 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000968 return StmtError(Diag(First->getLocStart(),
969 diag::err_selector_element_not_lvalue)
970 << First->getSourceRange());
971
Mike Stump11289f42009-09-09 15:08:12 +0000972 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000973 }
Douglas Gregorf68a5082010-04-22 23:10:45 +0000974 if (!FirstType->isDependentType() &&
975 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +0000976 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000977 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000978 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000979 }
Douglas Gregorf68a5082010-04-22 23:10:45 +0000980 if (Second && !Second->isTypeDependent()) {
John Wiegley01296292011-04-08 18:41:53 +0000981 ExprResult Result = DefaultFunctionArrayLvalueConversion(Second);
982 if (Result.isInvalid())
983 return StmtError();
984 Second = Result.take();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000985 QualType SecondType = Second->getType();
Steve Naroff79d12152009-07-16 15:41:00 +0000986 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000987 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000988 << SecondType << Second->getSourceRange();
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +0000989 else if (const ObjCObjectPointerType *OPT =
990 SecondType->getAsObjCInterfacePointerType()) {
991 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992 IdentifierInfo* selIdent =
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +0000993 &Context.Idents.get("countByEnumeratingWithState");
994 KeyIdents.push_back(selIdent);
995 selIdent = &Context.Idents.get("objects");
996 KeyIdents.push_back(selIdent);
997 selIdent = &Context.Idents.get("count");
998 KeyIdents.push_back(selIdent);
999 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
1000 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001 if (!IDecl->isForwardDecl() &&
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001002 !IDecl->lookupInstanceMethod(CSelector) &&
1003 !LookupMethodInQualifiedType(CSelector, OPT, true)) {
Fariborz Jahanianb5a62462010-08-12 22:33:42 +00001004 // Must further look into private implementation methods.
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +00001005 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
1006 Diag(ForLoc, diag::warn_collection_expr_type)
1007 << SecondType << CSelector << Second->getSourceRange();
1008 }
1009 }
1010 }
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001011 }
Ted Kremenek5a201952009-02-07 01:47:29 +00001012 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1013 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001014}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001015
Chris Lattnercab02a62011-02-17 20:34:02 +00001016StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1017 SourceLocation LabelLoc,
1018 LabelDecl *TheDecl) {
1019 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001020 TheDecl->setUsed();
1021 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001022}
Chris Lattner1c310502007-05-31 06:00:00 +00001023
John McCalldadc5752010-08-24 06:29:42 +00001024StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001025Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001026 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001027 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001028 if (!E->isTypeDependent()) {
1029 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001030 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001031 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001032 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001033 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1034 if (ExprRes.isInvalid())
1035 return StmtError();
1036 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001037 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001038 return StmtError();
1039 }
John McCalla95172b2010-08-01 00:26:45 +00001040
John McCallaab3e412010-08-25 08:40:02 +00001041 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001042
Douglas Gregor30776d42009-05-16 00:20:29 +00001043 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001044}
1045
John McCalldadc5752010-08-24 06:29:42 +00001046StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001047Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001048 Scope *S = CurScope->getContinueParent();
1049 if (!S) {
1050 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001051 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001052 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001053
Ted Kremenek5a201952009-02-07 01:47:29 +00001054 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001055}
1056
John McCalldadc5752010-08-24 06:29:42 +00001057StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001058Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001059 Scope *S = CurScope->getBreakParent();
1060 if (!S) {
1061 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001062 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001063 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001064
Ted Kremenek5a201952009-02-07 01:47:29 +00001065 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001066}
1067
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001069/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001070///
Douglas Gregor5d369002011-01-21 18:05:27 +00001071/// \param ReturnType If we're determining the copy elision candidate for
1072/// a return statement, this is the return type of the function. If we're
1073/// determining the copy elision candidate for a throw expression, this will
1074/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001075///
Douglas Gregor5d369002011-01-21 18:05:27 +00001076/// \param E The expression being returned from the function or block, or
1077/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001078///
Douglas Gregor5d369002011-01-21 18:05:27 +00001079/// \param AllowFunctionParameter
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001080///
1081/// \returns The NRVO candidate variable, if the return statement may use the
1082/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001083const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1084 Expr *E,
1085 bool AllowFunctionParameter) {
1086 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001087 // - in a return statement in a function with ...
1088 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001089 if (!ReturnType.isNull()) {
1090 if (!ReturnType->isRecordType())
1091 return 0;
1092 // ... the same cv-unqualified type as the function return type ...
1093 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1094 return 0;
1095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
1097 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00001098 // (other than a function or catch-clause parameter)) ...
1099 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001100 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001101 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001102 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1103 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001104 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Douglas Gregor5d369002011-01-21 18:05:27 +00001106 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
Douglas Gregor290c93e2010-05-15 06:46:45 +00001107 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
Douglas Gregor5d369002011-01-21 18:05:27 +00001108 !VD->getType().isVolatileQualified() &&
Douglas Gregor732abf12011-01-21 18:20:49 +00001109 ((VD->getKind() == Decl::Var) ||
1110 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001111 return VD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001113 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001114}
1115
Douglas Gregor626fbed2011-01-21 21:08:57 +00001116/// \brief Perform the initialization of a potentially-movable value, which
1117/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00001118///
1119/// This routine implements C++0x [class.copy]p33, which attempts to treat
1120/// returned lvalues as rvalues in certain cases (to prefer move construction),
1121/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00001123Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1124 const VarDecl *NRVOCandidate,
1125 QualType ResultType,
1126 Expr *Value) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001127 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128 // When the criteria for elision of a copy operation are met or would
1129 // be met save for the fact that the source object is a function
1130 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00001131 // overload resolution to select the constructor for the copy is first
1132 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00001133 ExprResult Res = ExprError();
Douglas Gregor626fbed2011-01-21 21:08:57 +00001134 if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001136 Value->getType(), CK_LValueToRValue,
1137 Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregorf282a762011-01-21 19:38:21 +00001139 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00001141 = InitializationKind::CreateCopy(Value->getLocStart(),
1142 Value->getLocStart());
1143 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144
1145 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00001146 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001147 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00001148 // is performed again, considering the object as an lvalue.
1149 if (Seq.getKind() != InitializationSequence::FailedSequence) {
1150 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1151 StepEnd = Seq.step_end();
1152 Step != StepEnd; ++Step) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153 if (Step->Kind
Douglas Gregorf282a762011-01-21 19:38:21 +00001154 != InitializationSequence::SK_ConstructorInitialization)
1155 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
1157 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00001158 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001159
Douglas Gregorf282a762011-01-21 19:38:21 +00001160 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00001161 = Constructor->getParamDecl(0)->getType()
1162 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163
Douglas Gregorf282a762011-01-21 19:38:21 +00001164 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00001166 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1167 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00001168 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
Douglas Gregorf282a762011-01-21 19:38:21 +00001170 // Promote "AsRvalue" to the heap, since we now need this
1171 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001172 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173 CK_LValueToRValue, Value, 0,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001174 VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Douglas Gregorf282a762011-01-21 19:38:21 +00001176 // Complete type-checking the initialization of the return type
1177 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001178 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00001179 }
1180 }
1181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182
Douglas Gregorf282a762011-01-21 19:38:21 +00001183 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001184 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00001185 // (again) now with the return value expression as written.
1186 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00001187 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001188
Douglas Gregorf282a762011-01-21 19:38:21 +00001189 return Res;
1190}
1191
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001192/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +00001193///
John McCalldadc5752010-08-24 06:29:42 +00001194StmtResult
Steve Naroffc540d662008-09-03 18:15:37 +00001195Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +00001196 // If this is the first return we've seen in the block, infer the type of
1197 // the block from it.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001198 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001199 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +00001200 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +00001201 // Don't call UsualUnaryConversions(), since we don't want to do
1202 // integer promotions here.
John Wiegley01296292011-04-08 18:41:53 +00001203 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1204 if (Result.isInvalid())
1205 return StmtError();
1206 RetValExp = Result.take();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001207 CurBlock->ReturnType = RetValExp->getType();
1208 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1209 // We have to remove a 'const' added to copied-in variable which was
1210 // part of the implementation spec. and not the actual qualifier for
1211 // the variable.
1212 if (CDRE->isConstQualAdded())
John McCall717d9b02010-12-10 11:01:00 +00001213 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001214 }
Steve Naroff3b1e1722008-09-16 22:25:10 +00001215 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001216 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +00001217 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001218 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +00001219
John McCall3882ace2011-01-05 12:14:39 +00001220 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +00001221 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1222 << getCurFunctionOrMethodDecl()->getDeclName();
1223 return StmtError();
1224 }
1225
Steve Naroffc540d662008-09-03 18:15:37 +00001226 // Otherwise, verify that this result type matches the previous one. We are
1227 // pickier with blocks than for normal functions because we don't have GCC
1228 // compatibility to worry about here.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001229 ReturnStmt *Result = 0;
Steve Naroffc540d662008-09-03 18:15:37 +00001230 if (CurBlock->ReturnType->isVoidType()) {
1231 if (RetValExp) {
1232 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroffc540d662008-09-03 18:15:37 +00001233 RetValExp = 0;
1234 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001235 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1236 } else if (!RetValExp) {
Sebastian Redl573feed2009-01-18 13:19:59 +00001237 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001238 } else {
1239 const VarDecl *NRVOCandidate = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001241 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1242 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001243
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001244 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1245 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1246 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001247
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001248 // In C++ the return statement is handled via a copy initialization.
1249 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001250 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001252 FnRetType,
1253 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001255 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001256 if (Res.isInvalid()) {
1257 // FIXME: Cleanup temporaries here, anyway?
1258 return StmtError();
1259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
John McCallacf0ee52010-10-08 02:01:28 +00001261 if (RetValExp) {
1262 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001263 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001264 }
Mike Stump82f071f2009-02-04 22:31:32 +00001265
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001266 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001267 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001268 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlsson6f923f82010-01-29 18:30:20 +00001269 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001271 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Steve Naroffc540d662008-09-03 18:15:37 +00001272 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001273
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001275 // return statement in our scope for later processing.
1276 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1277 !CurContext->isDependentContext())
1278 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001279
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001280 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00001281}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001282
John McCalldadc5752010-08-24 06:29:42 +00001283StmtResult
John McCallb268a282010-08-23 23:25:46 +00001284Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00001285 if (getCurBlock())
Steve Naroffc540d662008-09-03 18:15:37 +00001286 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00001287
Chris Lattner79413952008-12-04 23:50:19 +00001288 QualType FnRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001289 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00001290 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00001291 if (FD->hasAttr<NoReturnAttr>() ||
1292 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00001293 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001294 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001295 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Narofff3833d72009-03-03 00:45:38 +00001296 FnRetType = MD->getResultType();
1297 else // If we don't have a function/method context, bail.
1298 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001299
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001300 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00001301 if (FnRetType->isVoidType()) {
Douglas Gregor78b691a2009-10-01 23:25:31 +00001302 if (RetValExp && !RetValExp->isTypeDependent()) {
1303 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner27e5bef2008-12-18 02:01:17 +00001304 unsigned D = diag::ext_return_has_expr;
1305 if (RetValExp->getType()->isVoidType())
1306 D = diag::ext_return_has_void_expr;
John McCall34376a62010-12-04 03:47:34 +00001307 else {
John Wiegley01296292011-04-08 18:41:53 +00001308 ExprResult Result = Owned(RetValExp);
1309 Result = IgnoredValueConversions(Result.take());
1310 if (Result.isInvalid())
1311 return StmtError();
1312 RetValExp = Result.take();
1313 RetValExp = ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid).take();
John McCall34376a62010-12-04 03:47:34 +00001314 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001315
Chris Lattner0cb00d62008-12-18 02:03:48 +00001316 // return (some void expression); is legal in C++.
1317 if (D != diag::ext_return_has_void_expr ||
1318 !getLangOptions().CPlusPlus) {
1319 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1320 Diag(ReturnLoc, D)
1321 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1322 << RetValExp->getSourceRange();
1323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
John McCallacf0ee52010-10-08 02:01:28 +00001325 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001326 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001329 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1330 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001331 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1332 // C99 6.8.6.4p1 (ext_ since GCC warns)
1333 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1334
1335 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001336 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001337 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001338 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001339 Result = new (Context) ReturnStmt(ReturnLoc);
1340 } else {
1341 const VarDecl *NRVOCandidate = 0;
1342 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1343 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001344
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001345 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1346 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1347 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001348
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001349 // In C++ the return statement is handled via a copy initialization.
1350 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001351 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001353 FnRetType,
1354 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001356 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001357 if (Res.isInvalid()) {
1358 // FIXME: Cleanup temporaries here, anyway?
1359 return StmtError();
1360 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001361
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001362 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001364 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
John McCallacf0ee52010-10-08 02:01:28 +00001367 if (RetValExp) {
1368 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001369 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001370 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001371 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00001372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373
1374 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001375 // return statement in our scope for later processing.
1376 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1377 !CurContext->isDependentContext())
1378 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001380 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001381}
1382
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001383/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1384/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1385/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1386/// provide a strong guidance to not use it.
1387///
1388/// This method checks to see if the argument is an acceptable l-value and
1389/// returns false if it is a case we can handle.
1390static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00001391 // Type dependent expressions will be checked during instantiation.
1392 if (E->isTypeDependent())
1393 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001394
John McCall086a4642010-11-24 05:12:34 +00001395 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001396 return false; // Cool, this is an lvalue.
1397
1398 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1399 // are supposed to allow.
1400 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00001401 if (E != E2 && E2->isLValue()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001402 if (!S.getLangOptions().HeinousExtensions)
1403 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1404 << E->getSourceRange();
1405 else
1406 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1407 << E->getSourceRange();
1408 // Accept, even if we emitted an error diagnostic.
1409 return false;
1410 }
1411
1412 // None of the above, just randomly invalid non-lvalue.
1413 return true;
1414}
1415
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001416/// isOperandMentioned - Return true if the specified operand # is mentioned
1417/// anywhere in the decomposed asm string.
1418static bool isOperandMentioned(unsigned OpNo,
1419 llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
1420 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1421 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1422 if (!Piece.isOperand()) continue;
1423
1424 // If this is a reference to the input and if the input was the smaller
1425 // one, then we have to reject this asm.
1426 if (Piece.getOperandNo() == OpNo)
1427 return true;
1428 }
1429
1430 return false;
1431}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001432
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001433StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1434 bool IsVolatile, unsigned NumOutputs,
1435 unsigned NumInputs, IdentifierInfo **Names,
1436 MultiExprArg constraints, MultiExprArg exprs,
1437 Expr *asmString, MultiExprArg clobbers,
1438 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001439 unsigned NumClobbers = clobbers.size();
1440 StringLiteral **Constraints =
1441 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00001442 Expr **Exprs = exprs.get();
1443 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00001444 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1445
Anders Carlsson570c3572009-01-27 20:38:24 +00001446 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Chris Lattner496acc12008-08-18 19:55:17 +00001448 // The parser verifies that there is a string literal here.
Chris Lattner07096892008-07-23 06:46:56 +00001449 if (AsmString->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001450 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1451 << AsmString->getSourceRange());
1452
Chris Lattner496acc12008-08-18 19:55:17 +00001453 for (unsigned i = 0; i != NumOutputs; i++) {
1454 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001455 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001456 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1457 << Literal->getSourceRange());
1458
Anders Carlsson9a020f92010-01-30 22:25:16 +00001459 llvm::StringRef OutputName;
1460 if (Names[i])
1461 OutputName = Names[i]->getName();
1462
1463 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001464 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001465 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001466 diag::err_asm_invalid_output_constraint)
1467 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001468
Anders Carlssonf511f642007-11-27 04:11:28 +00001469 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00001470 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001471 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00001472 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001473 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00001474 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Chris Lattnerd9725f72009-04-26 07:16:29 +00001477 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001478 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001479
Chris Lattner34b51e82009-05-03 05:55:43 +00001480 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1481
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001482 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00001483 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001484 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001485 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1486 << Literal->getSourceRange());
1487
Anders Carlsson9a020f92010-01-30 22:25:16 +00001488 llvm::StringRef InputName;
1489 if (Names[i])
1490 InputName = Names[i]->getName();
1491
1492 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foad7d0479f2009-05-21 09:52:38 +00001493 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001494 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001495 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001496 diag::err_asm_invalid_input_constraint)
1497 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00001498 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001499
Eli Friedman47e78572009-05-03 07:49:42 +00001500 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00001501
Anders Carlsson224fca82009-01-20 20:49:22 +00001502 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00001503 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001504 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00001505 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001506 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001507 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001508 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001509 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001510
Chris Lattnerd9725f72009-04-26 07:16:29 +00001511 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00001512 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00001513 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001514 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00001515 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001516 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00001517 }
Anders Carlsson224fca82009-01-20 20:49:22 +00001518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
John Wiegley01296292011-04-08 18:41:53 +00001520 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
1521 if (Result.isInvalid())
1522 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001523
John Wiegley01296292011-04-08 18:41:53 +00001524 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00001525 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001526 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001527
Anders Carlsson290aa852007-11-25 00:25:21 +00001528 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00001529 for (unsigned i = 0; i != NumClobbers; i++) {
1530 StringLiteral *Literal = Clobbers[i];
Chris Lattner07096892008-07-23 06:46:56 +00001531 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001532 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1533 << Literal->getSourceRange());
1534
Anders Carlsson96fe0b52010-01-30 19:34:25 +00001535 llvm::StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00001536
Anders Carlsson96fe0b52010-01-30 19:34:25 +00001537 if (!Context.Target.isValidGCCRegisterName(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001538 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001539 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00001540 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001541
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001542 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1544 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00001545 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001546 // Validate the asm string, ensuring it makes sense given the operands we
1547 // have.
1548 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1549 unsigned DiagOffs;
1550 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00001551 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1552 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001553 return StmtError();
1554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
Chris Lattner34b51e82009-05-03 05:55:43 +00001556 // Validate tied input operands for type mismatches.
1557 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1558 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattner34b51e82009-05-03 05:55:43 +00001560 // If this is a tied constraint, verify that the output and input have
1561 // either exactly the same type, or that they are int/ptr operands with the
1562 // same size (int/long, int*/long, are ok etc).
1563 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001564
Chris Lattner34b51e82009-05-03 05:55:43 +00001565 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00001566 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00001567 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00001568 Expr *InputExpr = Exprs[InputOpNo];
Chris Lattner2c295cf2009-05-03 05:59:17 +00001569 QualType InTy = InputExpr->getType();
1570 QualType OutTy = OutputExpr->getType();
1571 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00001572 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001574 // Decide if the input and output are in the same domain (integer/ptr or
1575 // floating point.
1576 enum AsmDomain {
1577 AD_Int, AD_FP, AD_Other
1578 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001579
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001580 if (InTy->isIntegerType() || InTy->isPointerType())
1581 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00001582 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001583 InputDomain = AD_FP;
1584 else
1585 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001587 if (OutTy->isIntegerType() || OutTy->isPointerType())
1588 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00001589 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001590 OutputDomain = AD_FP;
1591 else
1592 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001593
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001594 // They are ok if they are the same size and in the same domain. This
1595 // allows tying things like:
1596 // void* to int*
1597 // void* to int if they are the same size.
1598 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001600 uint64_t OutSize = Context.getTypeSize(OutTy);
1601 uint64_t InSize = Context.getTypeSize(InTy);
1602 if (OutSize == InSize && InputDomain == OutputDomain &&
1603 InputDomain != AD_Other)
1604 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001605
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001606 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00001607 // then we can promote the smaller one to a larger input and the asm string
1608 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001609 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001610
1611 // If this is a reference to the input and if the input was the smaller
1612 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00001613 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001614 // This is a use in the asm string of the smaller operand. Since we
1615 // codegen this by promoting to a wider value, the asm will get printed
1616 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00001617 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001618 }
Chris Lattnere3694b12011-02-21 21:50:25 +00001619 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001620 // If this is a reference to the output, and if the output is the larger
1621 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00001622 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00001623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001625 // If the smaller value wasn't mentioned in the asm string, and if the
1626 // output was a register, just extend the shorter one to the size of the
1627 // larger one.
1628 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1629 OutputConstraintInfos[TiedTo].allowsRegister())
1630 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00001631
Chris Lattner93ede022011-02-21 22:09:29 +00001632 // Either both of the operands were mentioned or the smaller one was
1633 // mentioned. One more special case that we'll allow: if the tied input is
1634 // integer, unmentioned, and is a constant, then we'll allow truncating it
1635 // down to the size of the destination.
1636 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
1637 !isOperandMentioned(InputOpNo, Pieces) &&
1638 InputExpr->isEvaluatable(Context)) {
John Wiegley01296292011-04-08 18:41:53 +00001639 InputExpr = ImpCastExprToType(InputExpr, OutTy, CK_IntegralCast).take();
Chris Lattner93ede022011-02-21 22:09:29 +00001640 Exprs[InputOpNo] = InputExpr;
1641 NS->setInputExpr(i, InputExpr);
1642 continue;
1643 }
1644
Chris Lattner28b05c82009-05-03 06:50:40 +00001645 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00001646 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00001647 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00001648 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00001649 return StmtError();
1650 }
Mike Stump11289f42009-09-09 15:08:12 +00001651
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001652 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00001653}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001654
John McCalldadc5752010-08-24 06:29:42 +00001655StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001656Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00001657 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00001658 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00001659 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00001660 if (Var && Var->isInvalidDecl())
1661 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001662
John McCallb268a282010-08-23 23:25:46 +00001663 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001664}
1665
John McCalldadc5752010-08-24 06:29:42 +00001666StmtResult
John McCallb268a282010-08-23 23:25:46 +00001667Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1668 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00001669}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001670
John McCalldadc5752010-08-24 06:29:42 +00001671StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00001673 MultiStmtArg CatchStmts, Stmt *Finally) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00001674 if (!getLangOptions().ObjCExceptions)
1675 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
1676
John McCallaab3e412010-08-25 08:40:02 +00001677 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00001678 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00001679 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1680 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00001681 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00001682 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001683}
1684
John McCalldadc5752010-08-24 06:29:42 +00001685StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCallb268a282010-08-23 23:25:46 +00001686 Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00001687 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00001688 ExprResult Result = DefaultLvalueConversion(Throw);
1689 if (Result.isInvalid())
1690 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00001691
John Wiegley01296292011-04-08 18:41:53 +00001692 Throw = Result.take();
Douglas Gregor2900c162010-04-22 21:44:01 +00001693 QualType ThrowType = Throw->getType();
1694 // Make sure the expression type is an ObjC pointer or "void *".
1695 if (!ThrowType->isDependentType() &&
1696 !ThrowType->isObjCObjectPointerType()) {
1697 const PointerType *PT = ThrowType->getAs<PointerType>();
1698 if (!PT || !PT->getPointeeType()->isVoidType())
1699 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1700 << Throw->getType() << Throw->getSourceRange());
1701 }
1702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
John McCallb268a282010-08-23 23:25:46 +00001704 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00001705}
1706
John McCalldadc5752010-08-24 06:29:42 +00001707StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001708Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00001709 Scope *CurScope) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00001710 if (!getLangOptions().ObjCExceptions)
1711 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
1712
John McCallb268a282010-08-23 23:25:46 +00001713 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00001714 // @throw without an expression designates a rethrow (which much occur
1715 // in the context of an @catch clause).
1716 Scope *AtCatchParent = CurScope;
1717 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1718 AtCatchParent = AtCatchParent->getParent();
1719 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00001720 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 }
1722
John McCallb268a282010-08-23 23:25:46 +00001723 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00001724}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001725
John McCalldadc5752010-08-24 06:29:42 +00001726StmtResult
John McCallb268a282010-08-23 23:25:46 +00001727Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1728 Stmt *SyncBody) {
John McCallaab3e412010-08-25 08:40:02 +00001729 getCurFunction()->setHasBranchProtectedScope();
Chris Lattnerc70dd562009-04-21 06:01:00 +00001730
John Wiegley01296292011-04-08 18:41:53 +00001731 ExprResult Result = DefaultLvalueConversion(SyncExpr);
1732 if (Result.isInvalid())
1733 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00001734
John Wiegley01296292011-04-08 18:41:53 +00001735 SyncExpr = Result.take();
Chris Lattner3501d432009-04-21 06:11:25 +00001736 // Make sure the expression type is an ObjC pointer or "void *".
Douglas Gregor6148de72010-04-22 22:01:21 +00001737 if (!SyncExpr->getType()->isDependentType() &&
1738 !SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001739 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattner3501d432009-04-21 06:11:25 +00001740 if (!PT || !PT->getPointeeType()->isVoidType())
1741 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1742 << SyncExpr->getType() << SyncExpr->getSourceRange());
1743 }
Mike Stump11289f42009-09-09 15:08:12 +00001744
John McCallb268a282010-08-23 23:25:46 +00001745 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00001746}
Sebastian Redl54c04d42008-12-22 19:15:10 +00001747
1748/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1749/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00001750StmtResult
John McCall48871652010-08-21 09:40:31 +00001751Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00001752 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00001753 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00001754 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00001755 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00001756 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00001757}
Sebastian Redl9b244a82008-12-22 21:35:02 +00001758
Dan Gohman28ade552010-07-26 21:25:24 +00001759namespace {
1760
Sebastian Redl63c4da02009-07-29 17:15:45 +00001761class TypeWithHandler {
1762 QualType t;
1763 CXXCatchStmt *stmt;
1764public:
1765 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1766 : t(type), stmt(statement) {}
1767
John McCall8ccfcb52009-09-24 19:53:00 +00001768 // An arbitrary order is fine as long as it places identical
1769 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00001770 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001771 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001772 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00001773 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001774 return false;
1775 else
1776 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
Sebastian Redl63c4da02009-07-29 17:15:45 +00001779 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001780 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00001781 }
Mike Stump11289f42009-09-09 15:08:12 +00001782
Sebastian Redl63c4da02009-07-29 17:15:45 +00001783 CXXCatchStmt *getCatchStmt() const { return stmt; }
1784 SourceLocation getTypeSpecStartLoc() const {
1785 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1786 }
1787};
1788
Dan Gohman28ade552010-07-26 21:25:24 +00001789}
1790
Sebastian Redl9b244a82008-12-22 21:35:02 +00001791/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1792/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00001793StmtResult
John McCallb268a282010-08-23 23:25:46 +00001794Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00001795 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00001796 // Don't report an error if 'try' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +00001797 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00001798 !getSourceManager().isInSystemHeader(TryLoc))
1799 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00001800
Sebastian Redl9b244a82008-12-22 21:35:02 +00001801 unsigned NumHandlers = RawHandlers.size();
1802 assert(NumHandlers > 0 &&
1803 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00001804 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00001805
Sebastian Redl63c4da02009-07-29 17:15:45 +00001806 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00001807
1808 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl9b244a82008-12-22 21:35:02 +00001809 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00001810 if (!Handler->getExceptionDecl()) {
1811 if (i < NumHandlers - 1)
1812 return StmtError(Diag(Handler->getLocStart(),
1813 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00001814
Sebastian Redl63c4da02009-07-29 17:15:45 +00001815 continue;
1816 }
Mike Stump11289f42009-09-09 15:08:12 +00001817
Sebastian Redl63c4da02009-07-29 17:15:45 +00001818 const QualType CaughtType = Handler->getCaughtType();
1819 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1820 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001821 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00001822
1823 // Detect handlers for the same type as an earlier one.
1824 if (NumHandlers > 1) {
1825 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00001826
Sebastian Redl63c4da02009-07-29 17:15:45 +00001827 TypeWithHandler prev = TypesWithHandlers[0];
1828 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1829 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00001830
Sebastian Redl63c4da02009-07-29 17:15:45 +00001831 if (curr == prev) {
1832 Diag(curr.getTypeSpecStartLoc(),
1833 diag::warn_exception_caught_by_earlier_handler)
1834 << curr.getCatchStmt()->getCaughtType().getAsString();
1835 Diag(prev.getTypeSpecStartLoc(),
1836 diag::note_previous_exception_handler)
1837 << prev.getCatchStmt()->getCaughtType().getAsString();
1838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
Sebastian Redl63c4da02009-07-29 17:15:45 +00001840 prev = curr;
1841 }
1842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
John McCallaab3e412010-08-25 08:40:02 +00001844 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00001845
Sebastian Redl9b244a82008-12-22 21:35:02 +00001846 // FIXME: We should detect handlers that cannot catch anything because an
1847 // earlier handler catches a superclass. Need to find a method that is not
1848 // quadratic for this.
1849 // Neither of these are explicitly forbidden, but every compiler detects them
1850 // and warns.
1851
John McCallb268a282010-08-23 23:25:46 +00001852 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00001853 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001854}