blob: 407618219fbf322aaf15e799345ed40cdf7084bb [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Richard Smith02e85f32011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Anders Carlsson59689ed2008-11-22 21:04:56 +000019#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000027#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000028#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000029#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000032using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000033using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000034
John McCalldadc5752010-08-24 06:29:42 +000035StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000036 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000037 if (!E) // FIXME: FullExprArg has no error state?
38 return StmtError();
39
Chris Lattner903eb512008-07-25 23:18:17 +000040 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41 // void expression for its side effects. Conversion to void allows any
42 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000043
Chris Lattner903eb512008-07-25 23:18:17 +000044 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000045 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000046}
47
48
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +000049StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool LeadingEmptyMacro) {
50 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000051}
52
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000053StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
54 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000055 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000056
Chris Lattnercbafe8d2009-04-12 20:13:14 +000057 // If we have an invalid decl, just return an error.
58 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000059
Chris Lattner34a22092009-03-04 04:23:07 +000060 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000061}
Chris Lattneraf8d5812006-11-10 05:07:45 +000062
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000063void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
64 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000065
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000066 // If we have an invalid decl, just return.
67 if (DG.isNull() || !DG.isSingleDecl()) return;
68 // suppress any potential 'unused variable' warning.
69 DG.getSingleDecl()->setUsed();
70}
71
Anders Carlsson59a2ab92009-07-30 22:17:18 +000072void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +000073 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
74 return DiagnoseUnusedExprResult(Label->getSubStmt());
75
Anders Carlsson5c5f1602009-07-30 22:39:03 +000076 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +000077 if (!E)
78 return;
79
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000080 if (E->isBoundMemberFunction(Context)) {
81 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
82 << E->getSourceRange();
83 return;
84 }
85
Anders Carlsson59a2ab92009-07-30 22:17:18 +000086 SourceLocation Loc;
87 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +000088 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +000089 return;
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattner2ba5ca92009-08-16 16:57:27 +000091 // Okay, we have an unused result. Depending on what the base expression is,
92 // we might want to make a more specific diagnostic. Check for one of these
93 // cases now.
94 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +000095 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +000096 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +000097 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
98 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +000099
John McCall34376a62010-12-04 03:47:34 +0000100 E = E->IgnoreParenImpCasts();
Chris Lattner1a6babf2009-10-13 04:53:48 +0000101 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000102 if (E->getType()->isVoidType())
103 return;
104
Chris Lattner1a6babf2009-10-13 04:53:48 +0000105 // If the callee has attribute pure, const, or warn_unused_result, warn with
106 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000107 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000108 if (FD->getAttr<WarnUnusedResultAttr>()) {
109 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
110 return;
111 }
112 if (FD->getAttr<PureAttr>()) {
113 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
114 return;
115 }
116 if (FD->getAttr<ConstAttr>()) {
117 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
118 return;
119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000120 }
John McCallb7bd14f2010-12-02 01:19:52 +0000121 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000122 const ObjCMethodDecl *MD = ME->getMethodDecl();
123 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
124 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
125 return;
126 }
John McCallb7bd14f2010-12-02 01:19:52 +0000127 } else if (isa<ObjCPropertyRefExpr>(E)) {
128 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000129 } else if (const CXXFunctionalCastExpr *FC
130 = dyn_cast<CXXFunctionalCastExpr>(E)) {
131 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
132 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
133 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000134 }
John McCall2351cb92010-04-06 22:24:14 +0000135 // Diagnose "(void*) blah" as a typo for "(void) blah".
136 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
137 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
138 QualType T = TI->getType();
139
140 // We really do want to use the non-canonical type here.
141 if (T == Context.VoidPtrTy) {
142 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
143
144 Diag(Loc, diag::warn_unused_voidptr)
145 << FixItHint::CreateRemoval(TL.getStarLoc());
146 return;
147 }
148 }
149
Ted Kremenek3427fac2011-02-23 01:52:04 +0000150 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000151}
152
John McCalldadc5752010-08-24 06:29:42 +0000153StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000154Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000155 MultiStmtArg elts, bool isStmtExpr) {
156 unsigned NumElts = elts.size();
157 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000158 // If we're in C89 mode, check that we don't have any decls after stmts. If
159 // so, emit an extension diagnostic.
160 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
161 // Note that __extension__ can be around a decl.
162 unsigned i = 0;
163 // Skip over all declarations.
164 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
165 /*empty*/;
166
167 // We found the end of the list or a statement. Scan for another declstmt.
168 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
169 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000170
Chris Lattnerd864daf2007-08-27 04:29:41 +0000171 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000172 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000173 Diag(D->getLocation(), diag::ext_mixed_decls_code);
174 }
175 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000176 // Warn about unused expressions in statements.
177 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000178 // Ignore statements that are last in a statement expression.
179 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000180 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000181
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000182 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000183 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000184
Ted Kremenek5a201952009-02-07 01:47:29 +0000185 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000186}
187
John McCalldadc5752010-08-24 06:29:42 +0000188StmtResult
John McCallb268a282010-08-23 23:25:46 +0000189Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
190 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000191 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000192 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000193
Steve Naroff8eeeb132007-05-08 21:09:37 +0000194 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000195 // However, GCC allows any evaluatable integer expression.
Mike Stump11289f42009-09-09 15:08:12 +0000196 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000197 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000198 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000199
Chris Lattner46eeb222007-07-18 02:28:47 +0000200 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000201
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000202 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
203 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000204 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000205 }
206
John McCallaab3e412010-08-25 08:40:02 +0000207 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000208 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000209 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000210 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000211
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000212 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
213 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000214 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000215 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000216}
217
Chris Lattner34a22092009-03-04 04:23:07 +0000218/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000219void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chris Lattner34a22092009-03-04 04:23:07 +0000220 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000221 CS->setSubStmt(SubStmt);
222}
223
John McCalldadc5752010-08-24 06:29:42 +0000224StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000225Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000226 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000227 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000228 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000229 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000230 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000231
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000232 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000233 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000234 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000235}
236
John McCalldadc5752010-08-24 06:29:42 +0000237StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000238Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
239 SourceLocation ColonLoc, Stmt *SubStmt) {
240
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000241 // If the label was multiply defined, reject it now.
242 if (TheDecl->getStmt()) {
243 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
244 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000245 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000246 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000247
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000248 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000249 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
250 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000251 if (!TheDecl->isGnuLocal())
252 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000253 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000254}
255
John McCalldadc5752010-08-24 06:29:42 +0000256StmtResult
John McCall48871652010-08-21 09:40:31 +0000257Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000258 Stmt *thenStmt, SourceLocation ElseLoc,
259 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000260 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor633caca2009-11-23 23:44:04 +0000262 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000263 if (CondVar) {
264 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000265 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000266 if (CondResult.isInvalid())
267 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000268 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000269 Expr *ConditionExpr = CondResult.takeAs<Expr>();
270 if (!ConditionExpr)
271 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000273 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000274
Anders Carlssondb83d772007-10-10 20:50:11 +0000275 // Warn if the if block has a null body without an else value.
276 // this helps prevent bugs due to typos, such as
277 // if (condition);
278 // do_stuff();
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000279 //
John McCallb268a282010-08-23 23:25:46 +0000280 if (!elseStmt) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000281 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Argyrios Kyrtzidis90ee2a42010-11-19 20:54:25 +0000282 // But do not warn if the body is a macro that expands to nothing, e.g:
283 //
284 // #define CALL(x)
285 // if (condition)
286 // CALL(0);
287 //
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000288 if (!stmt->hasLeadingEmptyMacro())
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000289 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000290 }
291
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000292 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000293
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000295 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000296}
Steve Naroff86272ea2007-05-29 02:14:17 +0000297
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000298/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
299/// the specified width and sign. If an overflow occurs, detect it and emit
300/// the specified diagnostic.
301void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
302 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000303 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000304 unsigned DiagID) {
305 // Perform a conversion to the promoted condition type if needed.
306 if (NewWidth > Val.getBitWidth()) {
307 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000308 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000309 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000310
311 // If the input was signed and negative and the output is
312 // unsigned, don't bother to warn: this is implementation-defined
313 // behavior.
314 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000315 } else if (NewWidth < Val.getBitWidth()) {
316 // If this is a truncation, check for overflow.
317 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000318 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000319 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000320 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000321 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000322 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000323 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000324
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000325 // Regardless of whether a diagnostic was emitted, really do the
326 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000327 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000328 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000329 } else if (NewSign != Val.isSigned()) {
330 // Convert the sign to match the sign of the condition. This can cause
331 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000333 // behavior.
334 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000335 llvm::APSInt OldVal(Val);
336 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000337 }
338}
339
Chris Lattner67998452007-08-23 18:29:20 +0000340namespace {
341 struct CaseCompareFunctor {
342 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
343 const llvm::APSInt &RHS) {
344 return LHS.first < RHS;
345 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000346 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
347 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
348 return LHS.first < RHS.first;
349 }
Chris Lattner67998452007-08-23 18:29:20 +0000350 bool operator()(const llvm::APSInt &LHS,
351 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
352 return LHS < RHS.first;
353 }
354 };
355}
356
Chris Lattner4b2ff022007-09-21 18:15:22 +0000357/// CmpCaseVals - Comparison predicate for sorting case values.
358///
359static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
360 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
361 if (lhs.first < rhs.first)
362 return true;
363
364 if (lhs.first == rhs.first &&
365 lhs.second->getCaseLoc().getRawEncoding()
366 < rhs.second->getCaseLoc().getRawEncoding())
367 return true;
368 return false;
369}
370
Douglas Gregorbd6839732010-02-08 22:24:16 +0000371/// CmpEnumVals - Comparison predicate for sorting enumeration values.
372///
373static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
374 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
375{
376 return lhs.first < rhs.first;
377}
378
379/// EqEnumVals - Comparison preficate for uniqing enumeration values.
380///
381static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
382 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
383{
384 return lhs.first == rhs.first;
385}
386
Chris Lattnera96d4272009-10-16 16:45:22 +0000387/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
388/// potentially integral-promoted expression @p expr.
389static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
John McCall45d30c32010-06-12 01:56:02 +0000390 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
Chris Lattnera96d4272009-10-16 16:45:22 +0000391 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
392 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000393 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
Chris Lattnera96d4272009-10-16 16:45:22 +0000394 return TypeBeforePromotion;
395 }
396 }
397 return expr->getType();
398}
399
John McCalldadc5752010-08-24 06:29:42 +0000400StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000402 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000403 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000404
Douglas Gregore60e41a2010-05-06 17:25:47 +0000405 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000406 if (CondVar) {
407 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000408 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
409 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000410 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000411
John McCallb268a282010-08-23 23:25:46 +0000412 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000414
John McCallb268a282010-08-23 23:25:46 +0000415 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000416 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
John McCallb268a282010-08-23 23:25:46 +0000418 CondResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000420 PDiag(diag::err_typecheck_statement_requires_integer),
421 PDiag(diag::err_switch_incomplete_class_type)
John McCallb268a282010-08-23 23:25:46 +0000422 << Cond->getSourceRange(),
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000423 PDiag(diag::err_switch_explicit_conversion),
424 PDiag(diag::note_switch_conversion),
425 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000426 PDiag(diag::note_switch_conversion),
427 PDiag(0));
John McCallb268a282010-08-23 23:25:46 +0000428 if (CondResult.isInvalid()) return StmtError();
429 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000430
John McCall48871652010-08-21 09:40:31 +0000431 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000432 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000433 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000434 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000435 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000436 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000437 }
John McCalla95172b2010-08-01 00:26:45 +0000438
John McCallaab3e412010-08-25 08:40:02 +0000439 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
John McCallb268a282010-08-23 23:25:46 +0000441 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000442 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000443 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000444}
445
Gabor Greif16e02862010-10-01 22:05:14 +0000446static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
447 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000448 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000449 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000450 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000451 Val.setIsSigned(IsSigned);
452}
453
John McCalldadc5752010-08-24 06:29:42 +0000454StmtResult
John McCallb268a282010-08-23 23:25:46 +0000455Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
456 Stmt *BodyStmt) {
457 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000458 assert(SS == getCurFunction()->SwitchStack.back() &&
459 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000460
Steve Naroff42a350a2007-09-01 21:08:38 +0000461 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000462 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000463
Douglas Gregorb412e172010-07-25 18:17:45 +0000464 if (SS->getCond() == 0)
Douglas Gregor3ff3af42009-11-25 06:20:02 +0000465 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000466
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000467 Expr *CondExpr = SS->getCond();
John McCalld3dfbd62010-05-18 03:19:21 +0000468 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000469 QualType CondTypeBeforePromotion =
470 GetTypeBeforeIntegralPromotion(CondExpr);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000471
Douglas Gregor7fdcbaf22009-11-25 15:17:36 +0000472 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
John Wiegley01296292011-04-08 18:41:53 +0000473 ExprResult CondResult = UsualUnaryConversions(CondExpr);
474 if (CondResult.isInvalid())
475 return StmtError();
476 CondExpr = CondResult.take();
Douglas Gregor11075552009-11-25 05:02:21 +0000477 QualType CondType = CondExpr->getType();
Douglas Gregord0c22e02009-11-23 13:46:08 +0000478 SS->setCond(CondExpr);
479
Chris Lattnera96d4272009-10-16 16:45:22 +0000480 // C++ 6.4.2.p2:
481 // Integral promotions are performed (on the switch condition).
482 //
483 // A case value unrepresentable by the original switch condition
484 // type (before the promotion) doesn't make sense, even when it can
485 // be represented by the promoted type. Therefore we need to find
486 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000487 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000488 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000489 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000490 // appropriate type now, just return an error.
491 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000492 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000493
Chris Lattner4ebae652010-04-16 23:34:13 +0000494 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000495 // switch(bool_expr) {...} is often a programmer error, e.g.
496 // switch(n && mask) { ... } // Doh - should be "n & mask".
497 // One can always use an if statement instead of switch(bool_expr).
498 Diag(SwitchLoc, diag::warn_bool_switch_condition)
499 << CondExpr->getSourceRange();
500 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000501 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000502
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000503 // Get the bitwidth of the switched-on value before promotions. We must
504 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000505 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000506 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000507 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000508 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chris Lattnera96d4272009-10-16 16:45:22 +0000509 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000511 // Accumulate all of the case values in a vector so that we can sort them
512 // and detect duplicates. This vector contains the APInt for the case after
513 // it has been converted to the condition type.
Chris Lattner67998452007-08-23 18:29:20 +0000514 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
515 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000517 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000518 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
519 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000521 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000522
Chris Lattner10cb5e52007-08-23 06:23:56 +0000523 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000525 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000526 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000527
Anders Carlsson51873c22007-07-22 07:07:56 +0000528 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000529 if (TheDefaultStmt) {
530 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000531 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000532
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000533 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000534 // we'll return a valid AST. This requires recursing down the AST and
535 // finding it, not something we are set up to do right now. For now,
536 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000537 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000538 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000539 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000541 } else {
542 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000543
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000544 // We already verified that the expression has a i-c-e value (C99
545 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000546 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000547
548 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
549 HasDependentValue = true;
550 break;
551 }
Mike Stump11289f42009-09-09 15:08:12 +0000552
Anders Carlsson59689ed2008-11-22 21:04:56 +0000553 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000555 // Convert the value to the same width/sign as the condition.
556 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000557 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000558 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000559
Chris Lattnera65e1f32008-01-16 19:17:22 +0000560 // If the LHS is not the same type as the condition, insert an implicit
561 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000562 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
Chris Lattnera65e1f32008-01-16 19:17:22 +0000563 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000564
Chris Lattner10cb5e52007-08-23 06:23:56 +0000565 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000566 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000567 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000568 CS->getRHS()->isValueDependent()) {
569 HasDependentValue = true;
570 break;
571 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000572 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000573 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000574 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000575 }
576 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000577
578 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000579 // If we don't have a default statement, check whether the
580 // condition is constant.
581 llvm::APSInt ConstantCondValue;
582 bool HasConstantCond = false;
583 bool ShouldCheckConstantCond = false;
584 if (!HasDependentValue && !TheDefaultStmt) {
585 Expr::EvalResult Result;
586 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
587 if (HasConstantCond) {
588 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
589 ConstantCondValue = Result.Val.getInt();
590 ShouldCheckConstantCond = true;
591
592 assert(ConstantCondValue.getBitWidth() == CondWidth &&
593 ConstantCondValue.isSigned() == CondIsSigned);
594 }
595 }
596
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000597 // Sort all the scalar case values so we can easily detect duplicates.
598 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
599
600 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000601 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
602 if (ShouldCheckConstantCond &&
603 CaseVals[i].first == ConstantCondValue)
604 ShouldCheckConstantCond = false;
605
606 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000607 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000608 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000609 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
610 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000611 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000612 // FIXME: We really want to remove the bogus case stmt from the
613 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000614 CaseListIsErroneous = true;
615 }
616 }
617 }
Mike Stump11289f42009-09-09 15:08:12 +0000618
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000619 // Detect duplicate case ranges, which usually don't exist at all in
620 // the first place.
621 if (!CaseRanges.empty()) {
622 // Sort all the case ranges by their low value so we can easily detect
623 // overlaps between ranges.
624 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000625
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000626 // Scan the ranges, computing the high values and removing empty ranges.
627 std::vector<llvm::APSInt> HiVals;
628 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000629 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000630 CaseStmt *CR = CaseRanges[i].second;
631 Expr *Hi = CR->getRHS();
632 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000633
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000634 // Convert the value to the same width/sign as the condition.
635 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000636 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000637 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000638
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000639 // If the LHS is not the same type as the condition, insert an implicit
640 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000641 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000642 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000644 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000645 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000646 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
647 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000648 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000649 CaseRanges.erase(CaseRanges.begin()+i);
650 --i, --e;
651 continue;
652 }
John McCalld3dfbd62010-05-18 03:19:21 +0000653
654 if (ShouldCheckConstantCond &&
655 LoVal <= ConstantCondValue &&
656 ConstantCondValue <= HiVal)
657 ShouldCheckConstantCond = false;
658
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000659 HiVals.push_back(HiVal);
660 }
Mike Stump11289f42009-09-09 15:08:12 +0000661
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000662 // Rescan the ranges, looking for overlap with singleton values and other
663 // ranges. Since the range list is sorted, we only need to compare case
664 // ranges with their neighbors.
665 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
666 llvm::APSInt &CRLo = CaseRanges[i].first;
667 llvm::APSInt &CRHi = HiVals[i];
668 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000669
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000670 // Check to see whether the case range overlaps with any
671 // singleton cases.
672 CaseStmt *OverlapStmt = 0;
673 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000674
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000675 // Find the smallest value >= the lower bound. If I is in the
676 // case range, then we have overlap.
677 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
678 CaseVals.end(), CRLo,
679 CaseCompareFunctor());
680 if (I != CaseVals.end() && I->first < CRHi) {
681 OverlapVal = I->first; // Found overlap with scalar.
682 OverlapStmt = I->second;
683 }
Mike Stump11289f42009-09-09 15:08:12 +0000684
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000685 // Find the smallest value bigger than the upper bound.
686 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
687 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
688 OverlapVal = (I-1)->first; // Found overlap with scalar.
689 OverlapStmt = (I-1)->second;
690 }
Mike Stump11289f42009-09-09 15:08:12 +0000691
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000692 // Check to see if this case stmt overlaps with the subsequent
693 // case range.
694 if (i && CRLo <= HiVals[i-1]) {
695 OverlapVal = HiVals[i-1]; // Found overlap with range.
696 OverlapStmt = CaseRanges[i-1].second;
697 }
Mike Stump11289f42009-09-09 15:08:12 +0000698
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000699 if (OverlapStmt) {
700 // If we have a duplicate, report it.
701 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
702 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000703 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000704 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000705 // FIXME: We really want to remove the bogus case stmt from the
706 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000707 CaseListIsErroneous = true;
708 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000709 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000710 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000711
John McCalld3dfbd62010-05-18 03:19:21 +0000712 // Complain if we have a constant condition and we didn't find a match.
713 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
714 // TODO: it would be nice if we printed enums as enums, chars as
715 // chars, etc.
716 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
717 << ConstantCondValue.toString(10)
718 << CondExpr->getSourceRange();
719 }
720
721 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000722 // values. We only issue a warning if there is not 'default:', but
723 // we still do the analysis to preserve this information in the AST
724 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000725 //
Chris Lattner51679082010-09-16 17:09:42 +0000726 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000727
Douglas Gregorbd6839732010-02-08 22:24:16 +0000728 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000729 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000730 const EnumDecl *ED = ET->getDecl();
731 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
732 EnumValsTy EnumVals;
733
John McCalld3dfbd62010-05-18 03:19:21 +0000734 // Gather all enum values, set their type and sort them,
735 // allowing easier comparison with CaseVals.
736 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000737 EDI != ED->enumerator_end(); ++EDI) {
738 llvm::APSInt Val = EDI->getInitVal();
739 AdjustAPSInt(Val, CondWidth, CondIsSigned);
740 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000741 }
742 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000743 EnumValsTy::iterator EIend =
744 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000745
746 // See which case values aren't in enum.
747 // TODO: we might want to check whether case values are out of the
748 // enum even if we don't want to check whether all cases are handled.
749 if (!TheDefaultStmt) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000750 EnumValsTy::const_iterator EI = EnumVals.begin();
751 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000752 CI != CaseVals.end(); CI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000753 while (EI != EIend && EI->first < CI->first)
754 EI++;
755 if (EI == EIend || EI->first > CI->first)
John McCalld3dfbd62010-05-18 03:19:21 +0000756 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
757 << ED->getDeclName();
Ted Kremenek02627a22010-09-09 06:53:59 +0000758 }
759 // See which of case ranges aren't in enum
760 EI = EnumVals.begin();
761 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000762 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000763 while (EI != EIend && EI->first < RI->first)
764 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Ted Kremenek02627a22010-09-09 06:53:59 +0000766 if (EI == EIend || EI->first != RI->first) {
767 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
768 << ED->getDeclName();
769 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000770
Ted Kremenek02627a22010-09-09 06:53:59 +0000771 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000772 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Ted Kremenek02627a22010-09-09 06:53:59 +0000773 while (EI != EIend && EI->first < Hi)
774 EI++;
775 if (EI == EIend || EI->first != Hi)
776 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
777 << ED->getDeclName();
778 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000779 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
Ted Kremenekc42f3452010-09-09 00:05:53 +0000781 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000782 CaseValsTy::const_iterator CI = CaseVals.begin();
783 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000784 bool hasCasesNotInSwitch = false;
785
Chris Lattner51679082010-09-16 17:09:42 +0000786 llvm::SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Ted Kremenekc42f3452010-09-09 00:05:53 +0000788 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000789 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000790 llvm::APSInt CIVal;
791 while (CI != CaseVals.end() && CI->first < EI->first)
792 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793
Douglas Gregorbd6839732010-02-08 22:24:16 +0000794 if (CI != CaseVals.end() && CI->first == EI->first)
795 continue;
796
Ted Kremenekc42f3452010-09-09 00:05:53 +0000797 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +0000798 for (; RI != CaseRanges.end(); RI++) {
799 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000800 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000801 if (EI->first <= Hi)
802 break;
803 }
804
Ted Kremenekc42f3452010-09-09 00:05:53 +0000805 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000806 hasCasesNotInSwitch = true;
807 if (!TheDefaultStmt)
Chris Lattner51679082010-09-16 17:09:42 +0000808 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +0000809 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Chris Lattner51679082010-09-16 17:09:42 +0000812 // Produce a nice diagnostic if multiple values aren't handled.
813 switch (UnhandledNames.size()) {
814 case 0: break;
815 case 1:
816 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
817 << UnhandledNames[0];
818 break;
819 case 2:
820 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
821 << UnhandledNames[0] << UnhandledNames[1];
822 break;
823 case 3:
824 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
825 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
826 break;
827 default:
828 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
829 << (unsigned)UnhandledNames.size()
830 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
831 break;
832 }
Ted Kremenekc42f3452010-09-09 00:05:53 +0000833
834 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +0000835 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000836 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000837 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000838
Mike Stump87c57ac2009-05-16 07:39:55 +0000839 // FIXME: If the case list was broken is some way, we don't have a good system
840 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000841 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000842 return StmtError();
843
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000844 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000845}
846
John McCalldadc5752010-08-24 06:29:42 +0000847StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +0000849 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +0000850 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851
Douglas Gregor680f8612009-11-24 21:15:44 +0000852 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000853 if (CondVar) {
854 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000855 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000856 if (CondResult.isInvalid())
857 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +0000858 }
John McCallb268a282010-08-23 23:25:46 +0000859 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000860 if (!ConditionExpr)
861 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862
John McCallb268a282010-08-23 23:25:46 +0000863 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +0000864
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000865 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +0000866 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000867}
868
John McCalldadc5752010-08-24 06:29:42 +0000869StmtResult
John McCallb268a282010-08-23 23:25:46 +0000870Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000871 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +0000872 Expr *Cond, SourceLocation CondRParen) {
873 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000874
John Wiegley01296292011-04-08 18:41:53 +0000875 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
876 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +0000877 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +0000878 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +0000879
John McCallacf0ee52010-10-08 02:01:28 +0000880 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +0000881 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000882 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000883 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000884 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
John McCallb268a282010-08-23 23:25:46 +0000886 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000887
John McCallb268a282010-08-23 23:25:46 +0000888 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000889}
890
John McCalldadc5752010-08-24 06:29:42 +0000891StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000892Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +0000893 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000894 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +0000895 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000896 if (!getLangOptions().CPlusPlus) {
897 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000898 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
899 // declare identifiers for objects having storage class 'auto' or
900 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000901 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
902 DI!=DE; ++DI) {
903 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +0000904 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000905 VD = 0;
906 if (VD == 0)
907 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
908 // FIXME: mark decl erroneous!
909 }
Chris Lattner39f920f2007-08-28 05:03:08 +0000910 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000911 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000912
John McCalldadc5752010-08-24 06:29:42 +0000913 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000914 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000915 if (secondVar) {
916 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000917 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000918 if (SecondResult.isInvalid())
919 return StmtError();
920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000922 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000923
Anders Carlsson1682af52009-08-01 01:39:59 +0000924 DiagnoseUnusedExprResult(First);
925 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000926 DiagnoseUnusedExprResult(Body);
927
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000928 return Owned(new (Context) ForStmt(Context, First,
929 SecondResult.take(), ConditionVar,
930 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000931 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000932}
933
John McCall34376a62010-12-04 03:47:34 +0000934/// In an Objective C collection iteration statement:
935/// for (x in y)
936/// x can be an arbitrary l-value expression. Bind it up as a
937/// full-expression.
938StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
939 CheckImplicitConversions(E);
John McCall5d413782010-12-06 08:20:24 +0000940 ExprResult Result = MaybeCreateExprWithCleanups(E);
John McCall34376a62010-12-04 03:47:34 +0000941 if (Result.isInvalid()) return StmtError();
942 return Owned(static_cast<Stmt*>(Result.get()));
943}
944
John McCalldadc5752010-08-24 06:29:42 +0000945StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000946Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
947 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +0000948 Stmt *First, Expr *Second,
949 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +0000950 if (First) {
951 QualType FirstType;
952 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +0000953 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000954 return StmtError(Diag((*DS->decl_begin())->getLocation(),
955 diag::err_toomany_element_decls));
956
Chris Lattner529efc72009-03-28 06:33:19 +0000957 Decl *D = DS->getSingleDecl();
Ted Kremenek11b00422008-10-06 20:58:11 +0000958 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +0000959 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
960 // declare identifiers for objects having storage class 'auto' or
961 // 'register'.
Steve Naroff08899ff2008-04-15 22:42:06 +0000962 VarDecl *VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000963 if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000964 return StmtError(Diag(VD->getLocation(),
965 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000966 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +0000967 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +0000968 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000969 return StmtError(Diag(First->getLocStart(),
970 diag::err_selector_element_not_lvalue)
971 << First->getSourceRange());
972
Mike Stump11289f42009-09-09 15:08:12 +0000973 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000974 }
Douglas Gregorf68a5082010-04-22 23:10:45 +0000975 if (!FirstType->isDependentType() &&
976 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +0000977 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000978 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000979 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000980 }
Douglas Gregorf68a5082010-04-22 23:10:45 +0000981 if (Second && !Second->isTypeDependent()) {
John Wiegley01296292011-04-08 18:41:53 +0000982 ExprResult Result = DefaultFunctionArrayLvalueConversion(Second);
983 if (Result.isInvalid())
984 return StmtError();
985 Second = Result.take();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000986 QualType SecondType = Second->getType();
Steve Naroff79d12152009-07-16 15:41:00 +0000987 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000988 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000989 << SecondType << Second->getSourceRange();
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +0000990 else if (const ObjCObjectPointerType *OPT =
991 SecondType->getAsObjCInterfacePointerType()) {
992 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993 IdentifierInfo* selIdent =
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +0000994 &Context.Idents.get("countByEnumeratingWithState");
995 KeyIdents.push_back(selIdent);
996 selIdent = &Context.Idents.get("objects");
997 KeyIdents.push_back(selIdent);
998 selIdent = &Context.Idents.get("count");
999 KeyIdents.push_back(selIdent);
1000 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
1001 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002 if (!IDecl->isForwardDecl() &&
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001003 !IDecl->lookupInstanceMethod(CSelector) &&
1004 !LookupMethodInQualifiedType(CSelector, OPT, true)) {
Fariborz Jahanianb5a62462010-08-12 22:33:42 +00001005 // Must further look into private implementation methods.
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +00001006 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
1007 Diag(ForLoc, diag::warn_collection_expr_type)
1008 << SecondType << CSelector << Second->getSourceRange();
1009 }
1010 }
1011 }
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001012 }
Ted Kremenek5a201952009-02-07 01:47:29 +00001013 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1014 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001015}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001016
Richard Smith02e85f32011-04-14 22:09:26 +00001017namespace {
1018
1019enum BeginEndFunction {
1020 BEF_begin,
1021 BEF_end
1022};
1023
1024/// Build a variable declaration for a for-range statement.
1025static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1026 QualType Type, const char *Name) {
1027 DeclContext *DC = SemaRef.CurContext;
1028 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1029 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1030 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1031 TInfo, SC_Auto, SC_None);
1032 return Decl;
1033}
1034
1035/// Finish building a variable declaration for a for-range statement.
1036/// \return true if an error occurs.
1037static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1038 SourceLocation Loc, int diag) {
1039 // Deduce the type for the iterator variable now rather than leaving it to
1040 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1041 TypeSourceInfo *InitTSI = 0;
1042 if (Init->getType()->isVoidType() ||
1043 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
1044 SemaRef.Diag(Loc, diag) << Init->getType();
1045 if (!InitTSI) {
1046 Decl->setInvalidDecl();
1047 return true;
1048 }
1049 Decl->setTypeSourceInfo(InitTSI);
1050 Decl->setType(InitTSI->getType());
1051
1052 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1053 /*TypeMayContainAuto=*/false);
1054 SemaRef.FinalizeDeclaration(Decl);
1055 return false;
1056}
1057
1058/// Produce a note indicating which begin/end function was implicitly called
1059/// by a C++0x for-range statement. This is often not obvious from the code,
1060/// nor from the diagnostics produced when analysing the implicit expressions
1061/// required in a for-range statement.
1062void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1063 BeginEndFunction BEF) {
1064 CallExpr *CE = dyn_cast<CallExpr>(E);
1065 if (!CE)
1066 return;
1067 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1068 if (!D)
1069 return;
1070 SourceLocation Loc = D->getLocation();
1071
1072 std::string Description;
1073 bool IsTemplate = false;
1074 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1075 Description = SemaRef.getTemplateArgumentBindingsText(
1076 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1077 IsTemplate = true;
1078 }
1079
1080 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1081 << BEF << IsTemplate << Description << E->getType();
1082}
1083
1084/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1085/// given LookupResult is non-empty, it is assumed to describe a member which
1086/// will be invoked. Otherwise, the function will be found via argument
1087/// dependent lookup.
1088static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1089 SourceLocation Loc,
1090 VarDecl *Decl,
1091 BeginEndFunction BEF,
1092 const DeclarationNameInfo &NameInfo,
1093 LookupResult &MemberLookup,
1094 Expr *Range) {
1095 ExprResult CallExpr;
1096 if (!MemberLookup.empty()) {
1097 ExprResult MemberRef =
1098 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1099 /*IsPtr=*/false, CXXScopeSpec(),
1100 /*Qualifier=*/0, MemberLookup,
1101 /*TemplateArgs=*/0);
1102 if (MemberRef.isInvalid())
1103 return ExprError();
1104 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1105 Loc, 0);
1106 if (CallExpr.isInvalid())
1107 return ExprError();
1108 } else {
1109 UnresolvedSet<0> FoundNames;
1110 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1111 // std is an associated namespace.
1112 UnresolvedLookupExpr *Fn =
1113 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1114 NestedNameSpecifierLoc(), NameInfo,
1115 /*NeedsADL=*/true, /*Overloaded=*/false,
1116 FoundNames.begin(), FoundNames.end(),
1117 /*LookInStdNamespace=*/true);
1118 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1119 0);
1120 if (CallExpr.isInvalid()) {
1121 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1122 << Range->getType();
1123 return ExprError();
1124 }
1125 }
1126 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1127 diag::err_for_range_iter_deduction_failure)) {
1128 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1129 return ExprError();
1130 }
1131 return CallExpr;
1132}
1133
1134}
1135
1136/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1137///
1138/// C++0x [stmt.ranged]:
1139/// A range-based for statement is equivalent to
1140///
1141/// {
1142/// auto && __range = range-init;
1143/// for ( auto __begin = begin-expr,
1144/// __end = end-expr;
1145/// __begin != __end;
1146/// ++__begin ) {
1147/// for-range-declaration = *__begin;
1148/// statement
1149/// }
1150/// }
1151///
1152/// The body of the loop is not available yet, since it cannot be analysed until
1153/// we have determined the type of the for-range-declaration.
1154StmtResult
1155Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1156 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1157 SourceLocation RParenLoc) {
1158 if (!First || !Range)
1159 return StmtError();
1160
1161 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1162 assert(DS && "first part of for range not a decl stmt");
1163
1164 if (!DS->isSingleDecl()) {
1165 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1166 return StmtError();
1167 }
1168 if (DS->getSingleDecl()->isInvalidDecl())
1169 return StmtError();
1170
1171 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1172 return StmtError();
1173
1174 // Build auto && __range = range-init
1175 SourceLocation RangeLoc = Range->getLocStart();
1176 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1177 Context.getAutoRRefDeductType(),
1178 "__range");
1179 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1180 diag::err_for_range_deduction_failure))
1181 return StmtError();
1182
1183 // Claim the type doesn't contain auto: we've already done the checking.
1184 DeclGroupPtrTy RangeGroup =
1185 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1186 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1187 if (RangeDecl.isInvalid())
1188 return StmtError();
1189
1190 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1191 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1192 RParenLoc);
1193}
1194
1195/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1196StmtResult
1197Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1198 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1199 Expr *Inc, Stmt *LoopVarDecl,
1200 SourceLocation RParenLoc) {
1201 Scope *S = getCurScope();
1202
1203 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1204 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1205 QualType RangeVarType = RangeVar->getType();
1206
1207 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1208 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1209
1210 StmtResult BeginEndDecl = BeginEnd;
1211 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1212
1213 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1214 SourceLocation RangeLoc = RangeVar->getLocation();
1215
1216 ExprResult RangeRef = BuildDeclRefExpr(RangeVar,
1217 RangeVarType.getNonReferenceType(),
1218 VK_LValue, ColonLoc);
1219 if (RangeRef.isInvalid())
1220 return StmtError();
1221
1222 QualType AutoType = Context.getAutoDeductType();
1223 Expr *Range = RangeVar->getInit();
1224 if (!Range)
1225 return StmtError();
1226 QualType RangeType = Range->getType();
1227
1228 if (RequireCompleteType(RangeLoc, RangeType,
1229 PDiag(diag::err_for_range_incomplete_type)))
1230 return StmtError();
1231
1232 // Build auto __begin = begin-expr, __end = end-expr.
1233 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1234 "__begin");
1235 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1236 "__end");
1237
1238 // Build begin-expr and end-expr and attach to __begin and __end variables.
1239 ExprResult BeginExpr, EndExpr;
1240 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1241 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1242 // __range + __bound, respectively, where __bound is the array bound. If
1243 // _RangeT is an array of unknown size or an array of incomplete type,
1244 // the program is ill-formed;
1245
1246 // begin-expr is __range.
1247 BeginExpr = RangeRef;
1248 if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc,
1249 diag::err_for_range_iter_deduction_failure)) {
1250 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1251 return StmtError();
1252 }
1253
1254 // Find the array bound.
1255 ExprResult BoundExpr;
1256 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1257 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1258 Context.IntTy, RangeLoc));
1259 else if (const VariableArrayType *VAT =
1260 dyn_cast<VariableArrayType>(UnqAT))
1261 BoundExpr = VAT->getSizeExpr();
1262 else {
1263 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1264 // UnqAT is not incomplete and Range is not type-dependent.
1265 assert(0 && "Unexpected array type in for-range");
1266 return StmtError();
1267 }
1268
1269 // end-expr is __range + __bound.
1270 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(),
1271 BoundExpr.get());
1272 if (EndExpr.isInvalid())
1273 return StmtError();
1274 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1275 diag::err_for_range_iter_deduction_failure)) {
1276 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1277 return StmtError();
1278 }
1279 } else {
1280 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1281 ColonLoc);
1282 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1283 ColonLoc);
1284
1285 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1286 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1287
1288 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1289 // - if _RangeT is a class type, the unqualified-ids begin and end are
1290 // looked up in the scope of class _RangeT as if by class member access
1291 // lookup (3.4.5), and if either (or both) finds at least one
1292 // declaration, begin-expr and end-expr are __range.begin() and
1293 // __range.end(), respectively;
1294 LookupQualifiedName(BeginMemberLookup, D);
1295 LookupQualifiedName(EndMemberLookup, D);
1296
1297 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1298 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1299 << RangeType << BeginMemberLookup.empty();
1300 return StmtError();
1301 }
1302 } else {
1303 // - otherwise, begin-expr and end-expr are begin(__range) and
1304 // end(__range), respectively, where begin and end are looked up with
1305 // argument-dependent lookup (3.4.2). For the purposes of this name
1306 // lookup, namespace std is an associated namespace.
1307 }
1308
1309 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1310 BEF_begin, BeginNameInfo,
1311 BeginMemberLookup, RangeRef.get());
1312 if (BeginExpr.isInvalid())
1313 return StmtError();
1314
1315 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1316 BEF_end, EndNameInfo,
1317 EndMemberLookup, RangeRef.get());
1318 if (EndExpr.isInvalid())
1319 return StmtError();
1320 }
1321
1322 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1323 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1324 if (!Context.hasSameType(BeginType, EndType)) {
1325 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1326 << BeginType << EndType;
1327 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1328 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1329 }
1330
1331 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1332 // Claim the type doesn't contain auto: we've already done the checking.
1333 DeclGroupPtrTy BeginEndGroup =
1334 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1335 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1336
1337 ExprResult BeginRef = BuildDeclRefExpr(BeginVar,
1338 BeginType.getNonReferenceType(),
1339 VK_LValue, ColonLoc);
1340 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1341 VK_LValue, ColonLoc);
1342
1343 // Build and check __begin != __end expression.
1344 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1345 BeginRef.get(), EndRef.get());
1346 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1347 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1348 if (NotEqExpr.isInvalid()) {
1349 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1350 if (!Context.hasSameType(BeginType, EndType))
1351 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1352 return StmtError();
1353 }
1354
1355 // Build and check ++__begin expression.
1356 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1357 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1358 if (IncrExpr.isInvalid()) {
1359 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1360 return StmtError();
1361 }
1362
1363 // Build and check *__begin expression.
1364 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1365 if (DerefExpr.isInvalid()) {
1366 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1367 return StmtError();
1368 }
1369
1370 // Attach *__begin as initializer for VD.
1371 if (!LoopVar->isInvalidDecl()) {
1372 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1373 /*TypeMayContainAuto=*/true);
1374 if (LoopVar->isInvalidDecl())
1375 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1376 }
1377 }
1378
1379 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1380 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1381 NotEqExpr.take(), IncrExpr.take(),
1382 LoopVarDS, /*Body=*/0, ForLoc,
1383 ColonLoc, RParenLoc));
1384}
1385
1386/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1387/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1388/// body cannot be performed until after the type of the range variable is
1389/// determined.
1390StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1391 if (!S || !B)
1392 return StmtError();
1393
1394 cast<CXXForRangeStmt>(S)->setBody(B);
1395 return S;
1396}
1397
Chris Lattnercab02a62011-02-17 20:34:02 +00001398StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1399 SourceLocation LabelLoc,
1400 LabelDecl *TheDecl) {
1401 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001402 TheDecl->setUsed();
1403 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001404}
Chris Lattner1c310502007-05-31 06:00:00 +00001405
John McCalldadc5752010-08-24 06:29:42 +00001406StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001407Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001408 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001409 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001410 if (!E->isTypeDependent()) {
1411 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001412 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001413 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001414 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001415 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1416 if (ExprRes.isInvalid())
1417 return StmtError();
1418 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001419 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001420 return StmtError();
1421 }
John McCalla95172b2010-08-01 00:26:45 +00001422
John McCallaab3e412010-08-25 08:40:02 +00001423 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001424
Douglas Gregor30776d42009-05-16 00:20:29 +00001425 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001426}
1427
John McCalldadc5752010-08-24 06:29:42 +00001428StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001429Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001430 Scope *S = CurScope->getContinueParent();
1431 if (!S) {
1432 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001433 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001434 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001435
Ted Kremenek5a201952009-02-07 01:47:29 +00001436 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001437}
1438
John McCalldadc5752010-08-24 06:29:42 +00001439StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001440Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001441 Scope *S = CurScope->getBreakParent();
1442 if (!S) {
1443 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001444 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001445 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001446
Ted Kremenek5a201952009-02-07 01:47:29 +00001447 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001448}
1449
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001451/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001452///
Douglas Gregor5d369002011-01-21 18:05:27 +00001453/// \param ReturnType If we're determining the copy elision candidate for
1454/// a return statement, this is the return type of the function. If we're
1455/// determining the copy elision candidate for a throw expression, this will
1456/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001457///
Douglas Gregor5d369002011-01-21 18:05:27 +00001458/// \param E The expression being returned from the function or block, or
1459/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001460///
Douglas Gregor5d369002011-01-21 18:05:27 +00001461/// \param AllowFunctionParameter
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001462///
1463/// \returns The NRVO candidate variable, if the return statement may use the
1464/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001465const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1466 Expr *E,
1467 bool AllowFunctionParameter) {
1468 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001469 // - in a return statement in a function with ...
1470 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001471 if (!ReturnType.isNull()) {
1472 if (!ReturnType->isRecordType())
1473 return 0;
1474 // ... the same cv-unqualified type as the function return type ...
1475 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1476 return 0;
1477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478
1479 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00001480 // (other than a function or catch-clause parameter)) ...
1481 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001482 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001483 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001484 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1485 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001486 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregor5d369002011-01-21 18:05:27 +00001488 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
Douglas Gregor290c93e2010-05-15 06:46:45 +00001489 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
Douglas Gregor5d369002011-01-21 18:05:27 +00001490 !VD->getType().isVolatileQualified() &&
Douglas Gregor732abf12011-01-21 18:20:49 +00001491 ((VD->getKind() == Decl::Var) ||
1492 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001493 return VD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001495 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001496}
1497
Douglas Gregor626fbed2011-01-21 21:08:57 +00001498/// \brief Perform the initialization of a potentially-movable value, which
1499/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00001500///
1501/// This routine implements C++0x [class.copy]p33, which attempts to treat
1502/// returned lvalues as rvalues in certain cases (to prefer move construction),
1503/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001504ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00001505Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1506 const VarDecl *NRVOCandidate,
1507 QualType ResultType,
1508 Expr *Value) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001509 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001510 // When the criteria for elision of a copy operation are met or would
1511 // be met save for the fact that the source object is a function
1512 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00001513 // overload resolution to select the constructor for the copy is first
1514 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00001515 ExprResult Res = ExprError();
Douglas Gregor626fbed2011-01-21 21:08:57 +00001516 if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001517 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001518 Value->getType(), CK_LValueToRValue,
1519 Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Douglas Gregorf282a762011-01-21 19:38:21 +00001521 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001522 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00001523 = InitializationKind::CreateCopy(Value->getLocStart(),
1524 Value->getLocStart());
1525 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001526
1527 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00001528 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001529 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00001530 // is performed again, considering the object as an lvalue.
1531 if (Seq.getKind() != InitializationSequence::FailedSequence) {
1532 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1533 StepEnd = Seq.step_end();
1534 Step != StepEnd; ++Step) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535 if (Step->Kind
Douglas Gregorf282a762011-01-21 19:38:21 +00001536 != InitializationSequence::SK_ConstructorInitialization)
1537 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538
1539 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00001540 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Douglas Gregorf282a762011-01-21 19:38:21 +00001542 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00001543 = Constructor->getParamDecl(0)->getType()
1544 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001545
Douglas Gregorf282a762011-01-21 19:38:21 +00001546 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00001548 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1549 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00001550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551
Douglas Gregorf282a762011-01-21 19:38:21 +00001552 // Promote "AsRvalue" to the heap, since we now need this
1553 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001554 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555 CK_LValueToRValue, Value, 0,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001556 VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557
Douglas Gregorf282a762011-01-21 19:38:21 +00001558 // Complete type-checking the initialization of the return type
1559 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001560 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00001561 }
1562 }
1563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Douglas Gregorf282a762011-01-21 19:38:21 +00001565 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00001567 // (again) now with the return value expression as written.
1568 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00001569 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001570
Douglas Gregorf282a762011-01-21 19:38:21 +00001571 return Res;
1572}
1573
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001574/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +00001575///
John McCalldadc5752010-08-24 06:29:42 +00001576StmtResult
Steve Naroffc540d662008-09-03 18:15:37 +00001577Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +00001578 // If this is the first return we've seen in the block, infer the type of
1579 // the block from it.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001580 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001581 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +00001582 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +00001583 // Don't call UsualUnaryConversions(), since we don't want to do
1584 // integer promotions here.
John Wiegley01296292011-04-08 18:41:53 +00001585 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1586 if (Result.isInvalid())
1587 return StmtError();
1588 RetValExp = Result.take();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001589 CurBlock->ReturnType = RetValExp->getType();
1590 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1591 // We have to remove a 'const' added to copied-in variable which was
1592 // part of the implementation spec. and not the actual qualifier for
1593 // the variable.
1594 if (CDRE->isConstQualAdded())
John McCall717d9b02010-12-10 11:01:00 +00001595 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001596 }
Steve Naroff3b1e1722008-09-16 22:25:10 +00001597 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001598 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +00001599 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001600 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +00001601
John McCall3882ace2011-01-05 12:14:39 +00001602 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +00001603 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1604 << getCurFunctionOrMethodDecl()->getDeclName();
1605 return StmtError();
1606 }
1607
Steve Naroffc540d662008-09-03 18:15:37 +00001608 // Otherwise, verify that this result type matches the previous one. We are
1609 // pickier with blocks than for normal functions because we don't have GCC
1610 // compatibility to worry about here.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001611 ReturnStmt *Result = 0;
Steve Naroffc540d662008-09-03 18:15:37 +00001612 if (CurBlock->ReturnType->isVoidType()) {
1613 if (RetValExp) {
1614 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroffc540d662008-09-03 18:15:37 +00001615 RetValExp = 0;
1616 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001617 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1618 } else if (!RetValExp) {
Sebastian Redl573feed2009-01-18 13:19:59 +00001619 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001620 } else {
1621 const VarDecl *NRVOCandidate = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001623 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1624 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001625
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001626 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1627 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1628 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001629
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001630 // In C++ the return statement is handled via a copy initialization.
1631 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001632 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001634 FnRetType,
1635 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001636 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001637 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001638 if (Res.isInvalid()) {
1639 // FIXME: Cleanup temporaries here, anyway?
1640 return StmtError();
1641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642
John McCallacf0ee52010-10-08 02:01:28 +00001643 if (RetValExp) {
1644 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001645 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001646 }
Mike Stump82f071f2009-02-04 22:31:32 +00001647
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001648 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001650 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlsson6f923f82010-01-29 18:30:20 +00001651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001653 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Steve Naroffc540d662008-09-03 18:15:37 +00001654 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001655
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001657 // return statement in our scope for later processing.
1658 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1659 !CurContext->isDependentContext())
1660 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001662 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00001663}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001664
John McCalldadc5752010-08-24 06:29:42 +00001665StmtResult
John McCallb268a282010-08-23 23:25:46 +00001666Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00001667 if (getCurBlock())
Steve Naroffc540d662008-09-03 18:15:37 +00001668 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00001669
Chris Lattner79413952008-12-04 23:50:19 +00001670 QualType FnRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001671 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00001672 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00001673 if (FD->hasAttr<NoReturnAttr>() ||
1674 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00001675 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001676 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001677 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Narofff3833d72009-03-03 00:45:38 +00001678 FnRetType = MD->getResultType();
1679 else // If we don't have a function/method context, bail.
1680 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001681
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001682 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00001683 if (FnRetType->isVoidType()) {
Douglas Gregor78b691a2009-10-01 23:25:31 +00001684 if (RetValExp && !RetValExp->isTypeDependent()) {
1685 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner27e5bef2008-12-18 02:01:17 +00001686 unsigned D = diag::ext_return_has_expr;
1687 if (RetValExp->getType()->isVoidType())
1688 D = diag::ext_return_has_void_expr;
John McCall34376a62010-12-04 03:47:34 +00001689 else {
John Wiegley01296292011-04-08 18:41:53 +00001690 ExprResult Result = Owned(RetValExp);
1691 Result = IgnoredValueConversions(Result.take());
1692 if (Result.isInvalid())
1693 return StmtError();
1694 RetValExp = Result.take();
1695 RetValExp = ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid).take();
John McCall34376a62010-12-04 03:47:34 +00001696 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001697
Chris Lattner0cb00d62008-12-18 02:03:48 +00001698 // return (some void expression); is legal in C++.
1699 if (D != diag::ext_return_has_void_expr ||
1700 !getLangOptions().CPlusPlus) {
1701 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1702 Diag(ReturnLoc, D)
1703 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1704 << RetValExp->getSourceRange();
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCallacf0ee52010-10-08 02:01:28 +00001707 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001708 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001711 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1712 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001713 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1714 // C99 6.8.6.4p1 (ext_ since GCC warns)
1715 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1716
1717 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001718 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001719 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001720 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001721 Result = new (Context) ReturnStmt(ReturnLoc);
1722 } else {
1723 const VarDecl *NRVOCandidate = 0;
1724 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1725 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001726
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001727 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1728 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1729 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001730
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001731 // In C++ the return statement is handled via a copy initialization.
1732 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001733 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001735 FnRetType,
1736 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001738 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001739 if (Res.isInvalid()) {
1740 // FIXME: Cleanup temporaries here, anyway?
1741 return StmtError();
1742 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001743
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001744 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001745 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001746 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001748
John McCallacf0ee52010-10-08 02:01:28 +00001749 if (RetValExp) {
1750 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001751 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001752 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001753 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00001754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755
1756 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001757 // return statement in our scope for later processing.
1758 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1759 !CurContext->isDependentContext())
1760 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001762 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001763}
1764
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001765/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1766/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1767/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1768/// provide a strong guidance to not use it.
1769///
1770/// This method checks to see if the argument is an acceptable l-value and
1771/// returns false if it is a case we can handle.
1772static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00001773 // Type dependent expressions will be checked during instantiation.
1774 if (E->isTypeDependent())
1775 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776
John McCall086a4642010-11-24 05:12:34 +00001777 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001778 return false; // Cool, this is an lvalue.
1779
1780 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1781 // are supposed to allow.
1782 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00001783 if (E != E2 && E2->isLValue()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001784 if (!S.getLangOptions().HeinousExtensions)
1785 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1786 << E->getSourceRange();
1787 else
1788 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1789 << E->getSourceRange();
1790 // Accept, even if we emitted an error diagnostic.
1791 return false;
1792 }
1793
1794 // None of the above, just randomly invalid non-lvalue.
1795 return true;
1796}
1797
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001798/// isOperandMentioned - Return true if the specified operand # is mentioned
1799/// anywhere in the decomposed asm string.
1800static bool isOperandMentioned(unsigned OpNo,
1801 llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
1802 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1803 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1804 if (!Piece.isOperand()) continue;
1805
1806 // If this is a reference to the input and if the input was the smaller
1807 // one, then we have to reject this asm.
1808 if (Piece.getOperandNo() == OpNo)
1809 return true;
1810 }
1811
1812 return false;
1813}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001814
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001815StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1816 bool IsVolatile, unsigned NumOutputs,
1817 unsigned NumInputs, IdentifierInfo **Names,
1818 MultiExprArg constraints, MultiExprArg exprs,
1819 Expr *asmString, MultiExprArg clobbers,
1820 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001821 unsigned NumClobbers = clobbers.size();
1822 StringLiteral **Constraints =
1823 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00001824 Expr **Exprs = exprs.get();
1825 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00001826 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1827
Anders Carlsson570c3572009-01-27 20:38:24 +00001828 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattner496acc12008-08-18 19:55:17 +00001830 // The parser verifies that there is a string literal here.
Chris Lattner07096892008-07-23 06:46:56 +00001831 if (AsmString->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001832 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1833 << AsmString->getSourceRange());
1834
Chris Lattner496acc12008-08-18 19:55:17 +00001835 for (unsigned i = 0; i != NumOutputs; i++) {
1836 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001837 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001838 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1839 << Literal->getSourceRange());
1840
Anders Carlsson9a020f92010-01-30 22:25:16 +00001841 llvm::StringRef OutputName;
1842 if (Names[i])
1843 OutputName = Names[i]->getName();
1844
1845 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001846 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001847 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001848 diag::err_asm_invalid_output_constraint)
1849 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001850
Anders Carlssonf511f642007-11-27 04:11:28 +00001851 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00001852 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001853 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00001854 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001855 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00001856 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001857 }
Mike Stump11289f42009-09-09 15:08:12 +00001858
Chris Lattnerd9725f72009-04-26 07:16:29 +00001859 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001860 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001861
Chris Lattner34b51e82009-05-03 05:55:43 +00001862 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1863
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001864 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00001865 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001866 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001867 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1868 << Literal->getSourceRange());
1869
Anders Carlsson9a020f92010-01-30 22:25:16 +00001870 llvm::StringRef InputName;
1871 if (Names[i])
1872 InputName = Names[i]->getName();
1873
1874 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foad7d0479f2009-05-21 09:52:38 +00001875 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001876 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001877 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001878 diag::err_asm_invalid_input_constraint)
1879 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00001880 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001881
Eli Friedman47e78572009-05-03 07:49:42 +00001882 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00001883
Anders Carlsson224fca82009-01-20 20:49:22 +00001884 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00001885 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001886 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00001887 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001888 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001889 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001890 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001891 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001892
Chris Lattnerd9725f72009-04-26 07:16:29 +00001893 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00001894 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00001895 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001896 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00001897 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001898 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00001899 }
Anders Carlsson224fca82009-01-20 20:49:22 +00001900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
John Wiegley01296292011-04-08 18:41:53 +00001902 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
1903 if (Result.isInvalid())
1904 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001905
John Wiegley01296292011-04-08 18:41:53 +00001906 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00001907 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001908 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001909
Anders Carlsson290aa852007-11-25 00:25:21 +00001910 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00001911 for (unsigned i = 0; i != NumClobbers; i++) {
1912 StringLiteral *Literal = Clobbers[i];
Chris Lattner07096892008-07-23 06:46:56 +00001913 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001914 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1915 << Literal->getSourceRange());
1916
Anders Carlsson96fe0b52010-01-30 19:34:25 +00001917 llvm::StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00001918
Anders Carlsson96fe0b52010-01-30 19:34:25 +00001919 if (!Context.Target.isValidGCCRegisterName(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001920 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001921 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00001922 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001923
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001924 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1926 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00001927 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001928 // Validate the asm string, ensuring it makes sense given the operands we
1929 // have.
1930 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1931 unsigned DiagOffs;
1932 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00001933 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1934 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001935 return StmtError();
1936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Chris Lattner34b51e82009-05-03 05:55:43 +00001938 // Validate tied input operands for type mismatches.
1939 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1940 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattner34b51e82009-05-03 05:55:43 +00001942 // If this is a tied constraint, verify that the output and input have
1943 // either exactly the same type, or that they are int/ptr operands with the
1944 // same size (int/long, int*/long, are ok etc).
1945 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001946
Chris Lattner34b51e82009-05-03 05:55:43 +00001947 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00001948 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00001949 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00001950 Expr *InputExpr = Exprs[InputOpNo];
Chris Lattner2c295cf2009-05-03 05:59:17 +00001951 QualType InTy = InputExpr->getType();
1952 QualType OutTy = OutputExpr->getType();
1953 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00001954 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001956 // Decide if the input and output are in the same domain (integer/ptr or
1957 // floating point.
1958 enum AsmDomain {
1959 AD_Int, AD_FP, AD_Other
1960 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001962 if (InTy->isIntegerType() || InTy->isPointerType())
1963 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00001964 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001965 InputDomain = AD_FP;
1966 else
1967 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00001968
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001969 if (OutTy->isIntegerType() || OutTy->isPointerType())
1970 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00001971 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001972 OutputDomain = AD_FP;
1973 else
1974 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001976 // They are ok if they are the same size and in the same domain. This
1977 // allows tying things like:
1978 // void* to int*
1979 // void* to int if they are the same size.
1980 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001982 uint64_t OutSize = Context.getTypeSize(OutTy);
1983 uint64_t InSize = Context.getTypeSize(InTy);
1984 if (OutSize == InSize && InputDomain == OutputDomain &&
1985 InputDomain != AD_Other)
1986 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001988 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00001989 // then we can promote the smaller one to a larger input and the asm string
1990 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001991 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001992
1993 // If this is a reference to the input and if the input was the smaller
1994 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00001995 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00001996 // This is a use in the asm string of the smaller operand. Since we
1997 // codegen this by promoting to a wider value, the asm will get printed
1998 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00001999 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002000 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002001 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002002 // If this is a reference to the output, and if the output is the larger
2003 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002004 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002007 // If the smaller value wasn't mentioned in the asm string, and if the
2008 // output was a register, just extend the shorter one to the size of the
2009 // larger one.
2010 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2011 OutputConstraintInfos[TiedTo].allowsRegister())
2012 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00002013
Chris Lattner93ede022011-02-21 22:09:29 +00002014 // Either both of the operands were mentioned or the smaller one was
2015 // mentioned. One more special case that we'll allow: if the tied input is
2016 // integer, unmentioned, and is a constant, then we'll allow truncating it
2017 // down to the size of the destination.
2018 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2019 !isOperandMentioned(InputOpNo, Pieces) &&
2020 InputExpr->isEvaluatable(Context)) {
John Wiegley01296292011-04-08 18:41:53 +00002021 InputExpr = ImpCastExprToType(InputExpr, OutTy, CK_IntegralCast).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002022 Exprs[InputOpNo] = InputExpr;
2023 NS->setInputExpr(i, InputExpr);
2024 continue;
2025 }
2026
Chris Lattner28b05c82009-05-03 06:50:40 +00002027 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002028 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002029 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002030 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002031 return StmtError();
2032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002034 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002035}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002036
John McCalldadc5752010-08-24 06:29:42 +00002037StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002038Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002039 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002040 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002041 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002042 if (Var && Var->isInvalidDecl())
2043 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002044
John McCallb268a282010-08-23 23:25:46 +00002045 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002046}
2047
John McCalldadc5752010-08-24 06:29:42 +00002048StmtResult
John McCallb268a282010-08-23 23:25:46 +00002049Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2050 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002051}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002052
John McCalldadc5752010-08-24 06:29:42 +00002053StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002055 MultiStmtArg CatchStmts, Stmt *Finally) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002056 if (!getLangOptions().ObjCExceptions)
2057 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2058
John McCallaab3e412010-08-25 08:40:02 +00002059 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002060 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002061 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2062 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002063 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002064 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002065}
2066
John McCalldadc5752010-08-24 06:29:42 +00002067StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCallb268a282010-08-23 23:25:46 +00002068 Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002069 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00002070 ExprResult Result = DefaultLvalueConversion(Throw);
2071 if (Result.isInvalid())
2072 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002073
John Wiegley01296292011-04-08 18:41:53 +00002074 Throw = Result.take();
Douglas Gregor2900c162010-04-22 21:44:01 +00002075 QualType ThrowType = Throw->getType();
2076 // Make sure the expression type is an ObjC pointer or "void *".
2077 if (!ThrowType->isDependentType() &&
2078 !ThrowType->isObjCObjectPointerType()) {
2079 const PointerType *PT = ThrowType->getAs<PointerType>();
2080 if (!PT || !PT->getPointeeType()->isVoidType())
2081 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2082 << Throw->getType() << Throw->getSourceRange());
2083 }
2084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
John McCallb268a282010-08-23 23:25:46 +00002086 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002087}
2088
John McCalldadc5752010-08-24 06:29:42 +00002089StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002091 Scope *CurScope) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002092 if (!getLangOptions().ObjCExceptions)
2093 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2094
John McCallb268a282010-08-23 23:25:46 +00002095 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002096 // @throw without an expression designates a rethrow (which much occur
2097 // in the context of an @catch clause).
2098 Scope *AtCatchParent = CurScope;
2099 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2100 AtCatchParent = AtCatchParent->getParent();
2101 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002102 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103 }
2104
John McCallb268a282010-08-23 23:25:46 +00002105 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002106}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002107
John McCalldadc5752010-08-24 06:29:42 +00002108StmtResult
John McCallb268a282010-08-23 23:25:46 +00002109Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2110 Stmt *SyncBody) {
John McCallaab3e412010-08-25 08:40:02 +00002111 getCurFunction()->setHasBranchProtectedScope();
Chris Lattnerc70dd562009-04-21 06:01:00 +00002112
John Wiegley01296292011-04-08 18:41:53 +00002113 ExprResult Result = DefaultLvalueConversion(SyncExpr);
2114 if (Result.isInvalid())
2115 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002116
John Wiegley01296292011-04-08 18:41:53 +00002117 SyncExpr = Result.take();
Chris Lattner3501d432009-04-21 06:11:25 +00002118 // Make sure the expression type is an ObjC pointer or "void *".
Douglas Gregor6148de72010-04-22 22:01:21 +00002119 if (!SyncExpr->getType()->isDependentType() &&
2120 !SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002121 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattner3501d432009-04-21 06:11:25 +00002122 if (!PT || !PT->getPointeeType()->isVoidType())
2123 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
2124 << SyncExpr->getType() << SyncExpr->getSourceRange());
2125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
John McCallb268a282010-08-23 23:25:46 +00002127 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002128}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002129
2130/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2131/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002132StmtResult
John McCall48871652010-08-21 09:40:31 +00002133Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002134 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002135 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002136 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002137 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002138 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002139}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002140
Dan Gohman28ade552010-07-26 21:25:24 +00002141namespace {
2142
Sebastian Redl63c4da02009-07-29 17:15:45 +00002143class TypeWithHandler {
2144 QualType t;
2145 CXXCatchStmt *stmt;
2146public:
2147 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2148 : t(type), stmt(statement) {}
2149
John McCall8ccfcb52009-09-24 19:53:00 +00002150 // An arbitrary order is fine as long as it places identical
2151 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002152 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002153 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002154 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002155 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002156 return false;
2157 else
2158 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Sebastian Redl63c4da02009-07-29 17:15:45 +00002161 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002162 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002163 }
Mike Stump11289f42009-09-09 15:08:12 +00002164
Sebastian Redl63c4da02009-07-29 17:15:45 +00002165 CXXCatchStmt *getCatchStmt() const { return stmt; }
2166 SourceLocation getTypeSpecStartLoc() const {
2167 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2168 }
2169};
2170
Dan Gohman28ade552010-07-26 21:25:24 +00002171}
2172
Sebastian Redl9b244a82008-12-22 21:35:02 +00002173/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2174/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002175StmtResult
John McCallb268a282010-08-23 23:25:46 +00002176Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002177 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002178 // Don't report an error if 'try' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +00002179 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002180 !getSourceManager().isInSystemHeader(TryLoc))
2181 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002182
Sebastian Redl9b244a82008-12-22 21:35:02 +00002183 unsigned NumHandlers = RawHandlers.size();
2184 assert(NumHandlers > 0 &&
2185 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00002186 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002187
Sebastian Redl63c4da02009-07-29 17:15:45 +00002188 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002189
2190 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl9b244a82008-12-22 21:35:02 +00002191 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002192 if (!Handler->getExceptionDecl()) {
2193 if (i < NumHandlers - 1)
2194 return StmtError(Diag(Handler->getLocStart(),
2195 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002196
Sebastian Redl63c4da02009-07-29 17:15:45 +00002197 continue;
2198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
Sebastian Redl63c4da02009-07-29 17:15:45 +00002200 const QualType CaughtType = Handler->getCaughtType();
2201 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2202 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002203 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002204
2205 // Detect handlers for the same type as an earlier one.
2206 if (NumHandlers > 1) {
2207 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002208
Sebastian Redl63c4da02009-07-29 17:15:45 +00002209 TypeWithHandler prev = TypesWithHandlers[0];
2210 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2211 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002212
Sebastian Redl63c4da02009-07-29 17:15:45 +00002213 if (curr == prev) {
2214 Diag(curr.getTypeSpecStartLoc(),
2215 diag::warn_exception_caught_by_earlier_handler)
2216 << curr.getCatchStmt()->getCaughtType().getAsString();
2217 Diag(prev.getTypeSpecStartLoc(),
2218 diag::note_previous_exception_handler)
2219 << prev.getCatchStmt()->getCaughtType().getAsString();
2220 }
Mike Stump11289f42009-09-09 15:08:12 +00002221
Sebastian Redl63c4da02009-07-29 17:15:45 +00002222 prev = curr;
2223 }
2224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
John McCallaab3e412010-08-25 08:40:02 +00002226 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002227
Sebastian Redl9b244a82008-12-22 21:35:02 +00002228 // FIXME: We should detect handlers that cannot catch anything because an
2229 // earlier handler catches a superclass. Need to find a method that is not
2230 // quadratic for this.
2231 // Neither of these are explicitly forbidden, but every compiler detects them
2232 // and warns.
2233
John McCallb268a282010-08-23 23:25:46 +00002234 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002235 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002236}