blob: be9a09bc1dcdbe7be74b19a121b68a590b1be843 [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
14#include "Sema.h"
Anders Carlsson59689ed2008-11-22 21:04:56 +000015#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000019#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
21#include "clang/AST/StmtCXX.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000023#include "clang/Basic/TargetInfo.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000024#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000026using namespace clang;
27
Anders Carlsson24824e52009-05-17 21:11:30 +000028Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
29 Expr *E = expr->takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +000030 assert(E && "ActOnExprStmt(): missing expression");
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +000031 if (E->getType()->isObjCInterfaceType()) {
32 if (LangOpts.ObjCNonFragileABI)
33 Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object)
34 << E->getType();
35 else
36 Diag(E->getLocEnd(), diag::err_direct_interface_unsupported)
37 << E->getType();
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
Sebastian Redl52f03ba2008-12-21 12:04:03 +000049Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
Ted Kremenek5a201952009-02-07 01:47:29 +000050 return Owned(new (Context) NullStmt(SemiLoc));
Chris Lattner0f203a72007-05-28 01:45:28 +000051}
52
Chris Lattner5bbb3c82009-03-29 16:50:03 +000053Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
Sebastian Redl52f03ba2008-12-21 12:04:03 +000054 SourceLocation StartLoc,
55 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000056 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000057
Chris Lattnercbafe8d2009-04-12 20:13:14 +000058 // If we have an invalid decl, just return an error.
59 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattner34a22092009-03-04 04:23:07 +000061 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000062}
Chris Lattneraf8d5812006-11-10 05:07:45 +000063
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000064void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
66
67 // If we have an invalid decl, just return.
68 if (DG.isNull() || !DG.isSingleDecl()) return;
69 // suppress any potential 'unused variable' warning.
70 DG.getSingleDecl()->setUsed();
71}
72
Anders Carlsson59a2ab92009-07-30 22:17:18 +000073void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Anders Carlsson5c5f1602009-07-30 22:39:03 +000074 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +000075 if (!E)
76 return;
77
78 // Ignore expressions that have void type.
79 if (E->getType()->isVoidType())
80 return;
Mike Stump11289f42009-09-09 15:08:12 +000081
Anders Carlsson59a2ab92009-07-30 22:17:18 +000082 SourceLocation Loc;
83 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +000084 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +000085 return;
Mike Stump11289f42009-09-09 15:08:12 +000086
Chris Lattner2ba5ca92009-08-16 16:57:27 +000087 // Okay, we have an unused result. Depending on what the base expression is,
88 // we might want to make a more specific diagnostic. Check for one of these
89 // cases now.
90 unsigned DiagID = diag::warn_unused_expr;
91 E = E->IgnoreParens();
Fariborz Jahanian9a846652009-08-20 17:02:02 +000092 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
Chris Lattner2ba5ca92009-08-16 16:57:27 +000093 DiagID = diag::warn_unused_property_expr;
Chris Lattner1a6babf2009-10-13 04:53:48 +000094
95 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
96 // If the callee has attribute pure, const, or warn_unused_result, warn with
97 // a more specific message to make it clear what is happening.
98 if (const FunctionDecl *FD = CE->getDirectCallee()) {
99 if (FD->getAttr<WarnUnusedResultAttr>()) {
100 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
101 return;
102 }
103 if (FD->getAttr<PureAttr>()) {
104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
105 return;
106 }
107 if (FD->getAttr<ConstAttr>()) {
108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
109 return;
110 }
111 }
112 }
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000114 Diag(Loc, DiagID) << R1 << R2;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000115}
116
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000117Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000118Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000119 MultiStmtArg elts, bool isStmtExpr) {
120 unsigned NumElts = elts.size();
121 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000122 // If we're in C89 mode, check that we don't have any decls after stmts. If
123 // so, emit an extension diagnostic.
124 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
125 // Note that __extension__ can be around a decl.
126 unsigned i = 0;
127 // Skip over all declarations.
128 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
129 /*empty*/;
130
131 // We found the end of the list or a statement. Scan for another declstmt.
132 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
133 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattnerd864daf2007-08-27 04:29:41 +0000135 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000136 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000137 Diag(D->getLocation(), diag::ext_mixed_decls_code);
138 }
139 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000140 // Warn about unused expressions in statements.
141 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000142 // Ignore statements that are last in a statement expression.
143 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000144 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000145
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000146 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000147 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000148
Ted Kremenek5a201952009-02-07 01:47:29 +0000149 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000150}
151
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000152Action::OwningStmtResult
153Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
154 SourceLocation DotDotDotLoc, ExprArg rhsval,
Chris Lattner34a22092009-03-04 04:23:07 +0000155 SourceLocation ColonLoc) {
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000156 assert((lhsval.get() != 0) && "missing expression in case statement");
157
Steve Naroff8eeeb132007-05-08 21:09:37 +0000158 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000159 // However, GCC allows any evaluatable integer expression.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000160 Expr *LHSVal = static_cast<Expr*>(lhsval.get());
Mike Stump11289f42009-09-09 15:08:12 +0000161 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000162 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000163 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000164
Chris Lattner46eeb222007-07-18 02:28:47 +0000165 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000166
167 Expr *RHSVal = static_cast<Expr*>(rhsval.get());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000168 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
169 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000170 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000171 rhsval = 0;
172 }
173
Chris Lattner96b31392009-04-18 20:10:59 +0000174 if (getSwitchStack().empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000175 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000176 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000177 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000178
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000179 // Only now release the smart pointers.
180 lhsval.release();
181 rhsval.release();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000182 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
183 ColonLoc);
Chris Lattner96b31392009-04-18 20:10:59 +0000184 getSwitchStack().back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000185 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000186}
187
Chris Lattner34a22092009-03-04 04:23:07 +0000188/// ActOnCaseStmtBody - This installs a statement as the body of a case.
189void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
190 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000191 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Chris Lattner34a22092009-03-04 04:23:07 +0000192 CS->setSubStmt(SubStmt);
193}
194
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000195Action::OwningStmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000196Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000197 StmtArg subStmt, Scope *CurScope) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000198 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000199
Chris Lattner96b31392009-04-18 20:10:59 +0000200 if (getSwitchStack().empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000201 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000202 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000203 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000204
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000205 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Chris Lattner96b31392009-04-18 20:10:59 +0000206 getSwitchStack().back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000207 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000208}
209
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000210Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000211Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000212 SourceLocation ColonLoc, StmtArg subStmt) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000213 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Steve Naroffd123bd02009-02-28 16:48:43 +0000214 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +0000215 LabelStmt *&LabelDecl = getLabelMap()[II];
Steve Naroffd123bd02009-02-28 16:48:43 +0000216
Chris Lattnere2473062007-05-28 06:28:18 +0000217 // If not forward referenced or defined already, just create a new LabelStmt.
Steve Naroff846b1ec2009-03-13 15:38:40 +0000218 if (LabelDecl == 0)
219 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000220
Chris Lattnereefa10e2007-05-28 06:56:27 +0000221 assert(LabelDecl->getID() == II && "Label mismatch!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000222
Chris Lattnere2473062007-05-28 06:28:18 +0000223 // Otherwise, this label was either forward reference or multiply defined. If
224 // multiply defined, reject it now.
225 if (LabelDecl->getSubStmt()) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000226 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
Chris Lattner0369c572008-11-23 23:12:31 +0000227 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000228 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000229 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000230
Chris Lattnere2473062007-05-28 06:28:18 +0000231 // Otherwise, this label was forward declared, and we just found its real
232 // definition. Fill in the forward definition and return it.
233 LabelDecl->setIdentLoc(IdentLoc);
Chris Lattner39407372007-07-21 03:00:26 +0000234 LabelDecl->setSubStmt(SubStmt);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000235 return Owned(LabelDecl);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000236}
237
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000238Action::OwningStmtResult
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000239Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, DeclPtrTy CondVar,
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000240 StmtArg ThenVal, SourceLocation ElseLoc,
241 StmtArg ElseVal) {
Anders Carlsson52627462009-05-17 18:26:53 +0000242 OwningExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000243
Douglas Gregor633caca2009-11-23 23:44:04 +0000244 VarDecl *ConditionVar = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000245 if (CondVar.get()) {
246 ConditionVar = CondVar.getAs<VarDecl>();
247 CondResult = CheckConditionVariable(ConditionVar);
248 if (CondResult.isInvalid())
249 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000250 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000251 Expr *ConditionExpr = CondResult.takeAs<Expr>();
252 if (!ConditionExpr)
253 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000254
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000255 if (CheckBooleanCondition(ConditionExpr, IfLoc)) {
256 CondResult = ConditionExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000257 return StmtError();
Douglas Gregor9d73cab2009-05-15 18:53:42 +0000258 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000259
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000260 Stmt *thenStmt = ThenVal.takeAs<Stmt>();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000261 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000262
Anders Carlssondb83d772007-10-10 20:50:11 +0000263 // Warn if the if block has a null body without an else value.
264 // this helps prevent bugs due to typos, such as
265 // if (condition);
266 // do_stuff();
Mike Stump11289f42009-09-09 15:08:12 +0000267 if (!ElseVal.get()) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000268 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
269 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
270 }
271
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000272 Stmt *elseStmt = ElseVal.takeAs<Stmt>();
273 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlsson52627462009-05-17 18:26:53 +0000275 CondResult.release();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000276 return Owned(new (Context) IfStmt(IfLoc, ConditionVar, ConditionExpr,
277 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000278}
Steve Naroff86272ea2007-05-29 02:14:17 +0000279
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000280Action::OwningStmtResult
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000281Sema::ActOnStartOfSwitchStmt(FullExprArg cond, DeclPtrTy CondVar) {
282 OwningExprResult CondResult(cond.release());
283
Douglas Gregordcf19622009-11-24 17:07:59 +0000284 VarDecl *ConditionVar = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000285 if (CondVar.get()) {
286 ConditionVar = CondVar.getAs<VarDecl>();
287 CondResult = CheckConditionVariable(ConditionVar);
288 if (CondResult.isInvalid())
289 return StmtError();
Douglas Gregordcf19622009-11-24 17:07:59 +0000290 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000291 Expr *ConditionExpr = CondResult.takeAs<Expr>();
292 if (!ConditionExpr)
293 return StmtError();
Douglas Gregordcf19622009-11-24 17:07:59 +0000294
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000295 CondResult.release();
296 SwitchStmt *SS = new (Context) SwitchStmt(ConditionVar, ConditionExpr);
Chris Lattner96b31392009-04-18 20:10:59 +0000297 getSwitchStack().push_back(SS);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000298 return Owned(SS);
Anders Carlsson51873c22007-07-22 07:07:56 +0000299}
Chris Lattner46eeb222007-07-18 02:28:47 +0000300
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000301/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
302/// the specified width and sign. If an overflow occurs, detect it and emit
303/// the specified diagnostic.
304void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
305 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000306 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000307 unsigned DiagID) {
308 // Perform a conversion to the promoted condition type if needed.
309 if (NewWidth > Val.getBitWidth()) {
310 // If this is an extension, just do it.
311 llvm::APSInt OldVal(Val);
312 Val.extend(NewWidth);
Mike Stump11289f42009-09-09 15:08:12 +0000313
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000314 // If the input was signed and negative and the output is unsigned,
315 // warn.
316 if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
Chris Lattner29e812b2008-11-20 06:06:08 +0000317 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000319 Val.setIsSigned(NewSign);
320 } else if (NewWidth < Val.getBitWidth()) {
321 // If this is a truncation, check for overflow.
322 llvm::APSInt ConvVal(Val);
323 ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000324 ConvVal.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000325 ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000326 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000327 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000328 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000330 // Regardless of whether a diagnostic was emitted, really do the
331 // truncation.
332 Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000333 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000334 } else if (NewSign != Val.isSigned()) {
335 // Convert the sign to match the sign of the condition. This can cause
336 // overflow as well: unsigned(INTMIN)
337 llvm::APSInt OldVal(Val);
338 Val.setIsSigned(NewSign);
Mike Stump11289f42009-09-09 15:08:12 +0000339
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000340 if (Val.isNegative()) // Sign bit changes meaning.
Chris Lattner29e812b2008-11-20 06:06:08 +0000341 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000342 }
343}
344
Chris Lattner67998452007-08-23 18:29:20 +0000345namespace {
346 struct CaseCompareFunctor {
347 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
348 const llvm::APSInt &RHS) {
349 return LHS.first < RHS;
350 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000351 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
352 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
353 return LHS.first < RHS.first;
354 }
Chris Lattner67998452007-08-23 18:29:20 +0000355 bool operator()(const llvm::APSInt &LHS,
356 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
357 return LHS < RHS.first;
358 }
359 };
360}
361
Chris Lattner4b2ff022007-09-21 18:15:22 +0000362/// CmpCaseVals - Comparison predicate for sorting case values.
363///
364static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
365 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
366 if (lhs.first < rhs.first)
367 return true;
368
369 if (lhs.first == rhs.first &&
370 lhs.second->getCaseLoc().getRawEncoding()
371 < rhs.second->getCaseLoc().getRawEncoding())
372 return true;
373 return false;
374}
375
Chris Lattnera96d4272009-10-16 16:45:22 +0000376/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
377/// potentially integral-promoted expression @p expr.
378static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
379 const ImplicitCastExpr *ImplicitCast =
380 dyn_cast_or_null<ImplicitCastExpr>(expr);
381 if (ImplicitCast != NULL) {
382 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
383 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
384 if (TypeBeforePromotion->isIntegralType()) {
385 return TypeBeforePromotion;
386 }
387 }
388 return expr->getType();
389}
390
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000391Action::OwningStmtResult
392Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
393 StmtArg Body) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000394 Stmt *BodyStmt = Body.takeAs<Stmt>();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000395
Chris Lattner96b31392009-04-18 20:10:59 +0000396 SwitchStmt *SS = getSwitchStack().back();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000397 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
398
Steve Naroff42a350a2007-09-01 21:08:38 +0000399 SS->setBody(BodyStmt, SwitchLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000400 getSwitchStack().pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000401
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000402 Expr *CondExpr = SS->getCond();
Douglas Gregord0c22e02009-11-23 13:46:08 +0000403 QualType CondTypeBeforePromotion =
404 GetTypeBeforeIntegralPromotion(CondExpr);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000405 QualType CondType = CondExpr->getType();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000406
Douglas Gregord0c22e02009-11-23 13:46:08 +0000407 if (getLangOptions().CPlusPlus) {
408 // C++ 6.4.2.p2:
409 // The condition shall be of integral type, enumeration type, or of a class
410 // type for which a single conversion function to integral or enumeration
411 // type exists (12.3). If the condition is of class type, the condition is
412 // converted by calling that conversion function, and the result of the
413 // conversion is used in place of the original condition for the remainder
414 // of this section. Integral promotions are performed.
415 if (!CondExpr->isTypeDependent()) {
Douglas Gregor378e1922009-11-23 13:53:21 +0000416 // Make sure that the condition expression has a complete type,
417 // otherwise we'll never find any conversions.
418 if (RequireCompleteType(SwitchLoc, CondType,
419 PDiag(diag::err_switch_incomplete_class_type)
420 << CondExpr->getSourceRange()))
421 return StmtError();
422
Douglas Gregord0c22e02009-11-23 13:46:08 +0000423 llvm::SmallVector<CXXConversionDecl *, 4> ViableConversions;
424 llvm::SmallVector<CXXConversionDecl *, 4> ExplicitConversions;
425 if (const RecordType *RecordTy = CondType->getAs<RecordType>()) {
426 const UnresolvedSet *Conversions
427 = cast<CXXRecordDecl>(RecordTy->getDecl())
428 ->getVisibleConversionFunctions();
429 for (UnresolvedSet::iterator I = Conversions->begin(),
430 E = Conversions->end(); I != E; ++I) {
431 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(*I))
432 if (Conversion->getConversionType().getNonReferenceType()
433 ->isIntegralType()) {
434 if (Conversion->isExplicit())
435 ExplicitConversions.push_back(Conversion);
436 else
437 ViableConversions.push_back(Conversion);
438 }
439 }
440
441 switch (ViableConversions.size()) {
442 case 0:
443 if (ExplicitConversions.size() == 1) {
444 // The user probably meant to invoke the given explicit
445 // conversion; use it.
446 QualType ConvTy
447 = ExplicitConversions[0]->getConversionType()
448 .getNonReferenceType();
449 std::string TypeStr;
450 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
451
452
453 Diag(SwitchLoc, diag::err_switch_explicit_conversion)
454 << CondType << ConvTy << CondExpr->getSourceRange()
455 << CodeModificationHint::CreateInsertion(CondExpr->getLocStart(),
456 "static_cast<" + TypeStr + ">(")
457 << CodeModificationHint::CreateInsertion(
458 PP.getLocForEndOfToken(CondExpr->getLocEnd()),
459 ")");
460 Diag(ExplicitConversions[0]->getLocation(),
461 diag::note_switch_conversion)
462 << ConvTy->isEnumeralType() << ConvTy;
463
464 // If we aren't in a SFINAE context, build a call to the
465 // explicit conversion function.
466 if (!isSFINAEContext())
467 CondExpr = BuildCXXMemberCallExpr(CondExpr,
468 ExplicitConversions[0]);
469 }
470
471 // We'll complain below about a non-integral condition type.
472 break;
473
474 case 1:
475 // Apply this conversion.
476 CondExpr = BuildCXXMemberCallExpr(CondExpr, ViableConversions[0]);
477 break;
478
479 default:
480 Diag(SwitchLoc, diag::err_switch_multiple_conversions)
481 << CondType << CondExpr->getSourceRange();
482 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
483 QualType ConvTy
484 = ViableConversions[I]->getConversionType()
485 .getNonReferenceType();
486 Diag(ViableConversions[I]->getLocation(),
487 diag::note_switch_conversion)
488 << ConvTy->isEnumeralType() << ConvTy;
489 }
490 return StmtError();
491 }
492 }
493 CondType = CondExpr->getType();
494
495 if (CondType->isIntegralType() || CondType->isEnumeralType()) {
496 // Integral promotions are performed.
497 UsualUnaryConversions(CondExpr);
498 }
499 }
500 } else {
501 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
502 UsualUnaryConversions(CondExpr);
503 }
504 CondType = CondExpr->getType();
505 SS->setCond(CondExpr);
506
Chris Lattnera96d4272009-10-16 16:45:22 +0000507 // C++ 6.4.2.p2:
508 // Integral promotions are performed (on the switch condition).
509 //
510 // A case value unrepresentable by the original switch condition
511 // type (before the promotion) doesn't make sense, even when it can
512 // be represented by the promoted type. Therefore we need to find
513 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000514 if (!CondExpr->isTypeDependent()) {
515 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
516 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
517 << CondType << CondExpr->getSourceRange();
518 return StmtError();
519 }
520
521 if (CondTypeBeforePromotion->isBooleanType()) {
522 // switch(bool_expr) {...} is often a programmer error, e.g.
523 // switch(n && mask) { ... } // Doh - should be "n & mask".
524 // One can always use an if statement instead of switch(bool_expr).
525 Diag(SwitchLoc, diag::warn_bool_switch_condition)
526 << CondExpr->getSourceRange();
527 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000528 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000529
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000530 // Get the bitwidth of the switched-on value before promotions. We must
531 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000532 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000533 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000534 unsigned CondWidth
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000535 = HasDependentValue? 0
Chris Lattnera96d4272009-10-16 16:45:22 +0000536 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
537 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000538
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000539 // Accumulate all of the case values in a vector so that we can sort them
540 // and detect duplicates. This vector contains the APInt for the case after
541 // it has been converted to the condition type.
Chris Lattner67998452007-08-23 18:29:20 +0000542 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
543 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000545 // Keep track of any GNU case ranges we see. The APSInt is the low value.
546 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000548 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattner10cb5e52007-08-23 06:23:56 +0000550 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000551
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000552 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000553 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000554
Anders Carlsson51873c22007-07-22 07:07:56 +0000555 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000556 if (TheDefaultStmt) {
557 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000558 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000559
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000560 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000561 // we'll return a valid AST. This requires recursing down the AST and
562 // finding it, not something we are set up to do right now. For now,
563 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000564 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000565 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000566 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000568 } else {
569 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000570
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000571 // We already verified that the expression has a i-c-e value (C99
572 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000573 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000574
575 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
576 HasDependentValue = true;
577 break;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Anders Carlsson59689ed2008-11-22 21:04:56 +0000580 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000582 // Convert the value to the same width/sign as the condition.
583 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
584 CS->getLHS()->getLocStart(),
585 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000586
Chris Lattnera65e1f32008-01-16 19:17:22 +0000587 // If the LHS is not the same type as the condition, insert an implicit
588 // cast.
Eli Friedman06ed2a52009-10-20 08:27:19 +0000589 ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast);
Chris Lattnera65e1f32008-01-16 19:17:22 +0000590 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattner10cb5e52007-08-23 06:23:56 +0000592 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000593 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000594 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000595 CS->getRHS()->isValueDependent()) {
596 HasDependentValue = true;
597 break;
598 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000599 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000600 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000601 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000602 }
603 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000604
605 if (!HasDependentValue) {
606 // Sort all the scalar case values so we can easily detect duplicates.
607 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
608
609 if (!CaseVals.empty()) {
610 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
611 if (CaseVals[i].first == CaseVals[i+1].first) {
612 // If we have a duplicate, report it.
613 Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
614 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000615 Diag(CaseVals[i].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000616 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000617 // FIXME: We really want to remove the bogus case stmt from the
618 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000619 CaseListIsErroneous = true;
620 }
621 }
622 }
Mike Stump11289f42009-09-09 15:08:12 +0000623
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000624 // Detect duplicate case ranges, which usually don't exist at all in
625 // the first place.
626 if (!CaseRanges.empty()) {
627 // Sort all the case ranges by their low value so we can easily detect
628 // overlaps between ranges.
629 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000630
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000631 // Scan the ranges, computing the high values and removing empty ranges.
632 std::vector<llvm::APSInt> HiVals;
633 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
634 CaseStmt *CR = CaseRanges[i].second;
635 Expr *Hi = CR->getRHS();
636 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000637
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000638 // Convert the value to the same width/sign as the condition.
639 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
640 CR->getRHS()->getLocStart(),
641 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000642
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000643 // If the LHS is not the same type as the condition, insert an implicit
644 // cast.
Eli Friedman06ed2a52009-10-20 08:27:19 +0000645 ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast);
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000646 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000648 // If the low value is bigger than the high value, the case is empty.
649 if (CaseRanges[i].first > HiVal) {
650 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
651 << SourceRange(CR->getLHS()->getLocStart(),
652 CR->getRHS()->getLocEnd());
653 CaseRanges.erase(CaseRanges.begin()+i);
654 --i, --e;
655 continue;
656 }
657 HiVals.push_back(HiVal);
658 }
Mike Stump11289f42009-09-09 15:08:12 +0000659
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000660 // Rescan the ranges, looking for overlap with singleton values and other
661 // ranges. Since the range list is sorted, we only need to compare case
662 // ranges with their neighbors.
663 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
664 llvm::APSInt &CRLo = CaseRanges[i].first;
665 llvm::APSInt &CRHi = HiVals[i];
666 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000667
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000668 // Check to see whether the case range overlaps with any
669 // singleton cases.
670 CaseStmt *OverlapStmt = 0;
671 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000672
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000673 // Find the smallest value >= the lower bound. If I is in the
674 // case range, then we have overlap.
675 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
676 CaseVals.end(), CRLo,
677 CaseCompareFunctor());
678 if (I != CaseVals.end() && I->first < CRHi) {
679 OverlapVal = I->first; // Found overlap with scalar.
680 OverlapStmt = I->second;
681 }
Mike Stump11289f42009-09-09 15:08:12 +0000682
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000683 // Find the smallest value bigger than the upper bound.
684 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
685 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
686 OverlapVal = (I-1)->first; // Found overlap with scalar.
687 OverlapStmt = (I-1)->second;
688 }
Mike Stump11289f42009-09-09 15:08:12 +0000689
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000690 // Check to see if this case stmt overlaps with the subsequent
691 // case range.
692 if (i && CRLo <= HiVals[i-1]) {
693 OverlapVal = HiVals[i-1]; // Found overlap with range.
694 OverlapStmt = CaseRanges[i-1].second;
695 }
Mike Stump11289f42009-09-09 15:08:12 +0000696
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000697 if (OverlapStmt) {
698 // If we have a duplicate, report it.
699 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
700 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000701 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000702 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000703 // FIXME: We really want to remove the bogus case stmt from the
704 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000705 CaseListIsErroneous = true;
706 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000707 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000708 }
709 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000710
Mike Stump87c57ac2009-05-16 07:39:55 +0000711 // FIXME: If the case list was broken is some way, we don't have a good system
712 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000713 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000714 return StmtError();
715
716 Switch.release();
717 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000718}
719
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000720Action::OwningStmtResult
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000721Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
722 DeclPtrTy CondVar, StmtArg Body) {
723 OwningExprResult CondResult(Cond.release());
724
Douglas Gregor680f8612009-11-24 21:15:44 +0000725 VarDecl *ConditionVar = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000726 if (CondVar.get()) {
727 ConditionVar = CondVar.getAs<VarDecl>();
728 CondResult = CheckConditionVariable(ConditionVar);
729 if (CondResult.isInvalid())
730 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +0000731 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000732 Expr *ConditionExpr = CondResult.takeAs<Expr>();
733 if (!ConditionExpr)
734 return StmtError();
735
736 if (CheckBooleanCondition(ConditionExpr, WhileLoc)) {
737 CondResult = ConditionExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000738 return StmtError();
Douglas Gregor8a930c32009-05-15 21:45:53 +0000739 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000740
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000741 Stmt *bodyStmt = Body.takeAs<Stmt>();
742 DiagnoseUnusedExprResult(bodyStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000743
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000744 CondResult.release();
745 return Owned(new (Context) WhileStmt(ConditionVar, ConditionExpr, bodyStmt,
Douglas Gregor680f8612009-11-24 21:15:44 +0000746 WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000747}
748
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000749Action::OwningStmtResult
750Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000751 SourceLocation WhileLoc, SourceLocation CondLParen,
752 ExprArg Cond, SourceLocation CondRParen) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000753 Expr *condExpr = Cond.takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +0000754 assert(condExpr && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000755
John McCalld5707ab2009-10-12 21:59:07 +0000756 if (CheckBooleanCondition(condExpr, DoLoc)) {
Douglas Gregor3daa82d2009-05-15 21:56:04 +0000757 Cond = condExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000758 return StmtError();
Douglas Gregor3daa82d2009-05-15 21:56:04 +0000759 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000760
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000761 Stmt *bodyStmt = Body.takeAs<Stmt>();
762 DiagnoseUnusedExprResult(bodyStmt);
763
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000764 Cond.release();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000765 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
Chris Lattner815b70e2009-06-12 23:04:47 +0000766 WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000767}
768
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000769Action::OwningStmtResult
770Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000771 StmtArg first, FullExprArg second, DeclPtrTy secondVar,
772 FullExprArg third,
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000773 SourceLocation RParenLoc, StmtArg body) {
774 Stmt *First = static_cast<Stmt*>(first.get());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000775
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000776 if (!getLangOptions().CPlusPlus) {
777 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000778 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
779 // declare identifiers for objects having storage class 'auto' or
780 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000781 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
782 DI!=DE; ++DI) {
783 VarDecl *VD = dyn_cast<VarDecl>(*DI);
784 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
785 VD = 0;
786 if (VD == 0)
787 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
788 // FIXME: mark decl erroneous!
789 }
Chris Lattner39f920f2007-08-28 05:03:08 +0000790 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000791 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000792
793 OwningExprResult SecondResult(second.release());
794 VarDecl *ConditionVar = 0;
795 if (secondVar.get()) {
796 ConditionVar = secondVar.getAs<VarDecl>();
797 SecondResult = CheckConditionVariable(ConditionVar);
798 if (SecondResult.isInvalid())
799 return StmtError();
800 }
801
802 Expr *Second = SecondResult.takeAs<Expr>();
John McCalld5707ab2009-10-12 21:59:07 +0000803 if (Second && CheckBooleanCondition(Second, ForLoc)) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000804 SecondResult = Second;
John McCalld5707ab2009-10-12 21:59:07 +0000805 return StmtError();
Steve Naroff86272ea2007-05-29 02:14:17 +0000806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000808 Expr *Third = third.release().takeAs<Expr>();
809 Stmt *Body = static_cast<Stmt*>(body.get());
810
Anders Carlsson1682af52009-08-01 01:39:59 +0000811 DiagnoseUnusedExprResult(First);
812 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000813 DiagnoseUnusedExprResult(Body);
814
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000815 first.release();
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000816 body.release();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000817 return Owned(new (Context) ForStmt(First, Second, ConditionVar, Third, Body,
818 ForLoc, LParenLoc, RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000819}
820
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000821Action::OwningStmtResult
822Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
823 SourceLocation LParenLoc,
824 StmtArg first, ExprArg second,
825 SourceLocation RParenLoc, StmtArg body) {
826 Stmt *First = static_cast<Stmt*>(first.get());
827 Expr *Second = static_cast<Expr*>(second.get());
828 Stmt *Body = static_cast<Stmt*>(body.get());
Fariborz Jahanian93977672008-01-10 20:33:58 +0000829 if (First) {
830 QualType FirstType;
831 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +0000832 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000833 return StmtError(Diag((*DS->decl_begin())->getLocation(),
834 diag::err_toomany_element_decls));
835
Chris Lattner529efc72009-03-28 06:33:19 +0000836 Decl *D = DS->getSingleDecl();
Ted Kremenek11b00422008-10-06 20:58:11 +0000837 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +0000838 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
839 // declare identifiers for objects having storage class 'auto' or
840 // 'register'.
Steve Naroff08899ff2008-04-15 22:42:06 +0000841 VarDecl *VD = cast<VarDecl>(D);
842 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000843 return StmtError(Diag(VD->getLocation(),
844 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000845 } else {
Chris Lattnercda4d7e2009-03-13 17:38:01 +0000846 if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000847 return StmtError(Diag(First->getLocStart(),
848 diag::err_selector_element_not_lvalue)
849 << First->getSourceRange());
850
Mike Stump11289f42009-09-09 15:08:12 +0000851 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853 if (!FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +0000854 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000855 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000856 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000857 }
858 if (Second) {
859 DefaultFunctionArrayConversion(Second);
860 QualType SecondType = Second->getType();
Steve Naroff79d12152009-07-16 15:41:00 +0000861 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000862 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000863 << SecondType << Second->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000864 }
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000865 first.release();
866 second.release();
867 body.release();
Ted Kremenek5a201952009-02-07 01:47:29 +0000868 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
869 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000870}
Chris Lattneraf8d5812006-11-10 05:07:45 +0000871
Sebastian Redl573feed2009-01-18 13:19:59 +0000872Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000873Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
Chris Lattneraf8d5812006-11-10 05:07:45 +0000874 IdentifierInfo *LabelII) {
Steve Naroffc540d662008-09-03 18:15:37 +0000875 // If we are in a block, reject all gotos for now.
876 if (CurBlock)
Sebastian Redl573feed2009-01-18 13:19:59 +0000877 return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
Steve Naroffc540d662008-09-03 18:15:37 +0000878
Chris Lattnere2473062007-05-28 06:28:18 +0000879 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +0000880 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Chris Lattnere2473062007-05-28 06:28:18 +0000881
Steve Naroff846b1ec2009-03-13 15:38:40 +0000882 // If we haven't seen this label yet, create a forward reference.
883 if (LabelDecl == 0)
Ted Kremenek5a201952009-02-07 01:47:29 +0000884 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
Sebastian Redl573feed2009-01-18 13:19:59 +0000885
Ted Kremenek5a201952009-02-07 01:47:29 +0000886 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000887}
Chris Lattner1c310502007-05-31 06:00:00 +0000888
Sebastian Redl573feed2009-01-18 13:19:59 +0000889Action::OwningStmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +0000890Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
Sebastian Redl573feed2009-01-18 13:19:59 +0000891 ExprArg DestExp) {
Eli Friedman8d7ff402009-03-26 00:18:06 +0000892 // Convert operand to void*
Eli Friedman6568eef2009-03-26 07:32:37 +0000893 Expr* E = DestExp.takeAs<Expr>();
Douglas Gregor30776d42009-05-16 00:20:29 +0000894 if (!E->isTypeDependent()) {
895 QualType ETy = E->getType();
896 AssignConvertType ConvTy =
897 CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
898 if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
899 E, "passing"))
900 return StmtError();
901 }
902 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000903}
904
Sebastian Redl573feed2009-01-18 13:19:59 +0000905Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000906Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +0000907 Scope *S = CurScope->getContinueParent();
908 if (!S) {
909 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +0000910 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +0000911 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000912
Ted Kremenek5a201952009-02-07 01:47:29 +0000913 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000914}
915
Sebastian Redl573feed2009-01-18 13:19:59 +0000916Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000917Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +0000918 Scope *S = CurScope->getBreakParent();
919 if (!S) {
920 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +0000921 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +0000922 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000923
Ted Kremenek5a201952009-02-07 01:47:29 +0000924 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000925}
926
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000927/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +0000928///
Sebastian Redl573feed2009-01-18 13:19:59 +0000929Action::OwningStmtResult
Steve Naroffc540d662008-09-03 18:15:37 +0000930Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +0000931 // If this is the first return we've seen in the block, infer the type of
932 // the block from it.
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000933 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +0000934 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +0000935 // Don't call UsualUnaryConversions(), since we don't want to do
936 // integer promotions here.
937 DefaultFunctionArrayConversion(RetValExp);
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000938 CurBlock->ReturnType = RetValExp->getType();
939 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
940 // We have to remove a 'const' added to copied-in variable which was
941 // part of the implementation spec. and not the actual qualifier for
942 // the variable.
943 if (CDRE->isConstQualAdded())
944 CurBlock->ReturnType.removeConst();
945 }
Steve Naroff3b1e1722008-09-16 22:25:10 +0000946 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000947 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +0000948 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000949 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +0000950
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000951 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +0000952 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
953 << getCurFunctionOrMethodDecl()->getDeclName();
954 return StmtError();
955 }
956
Steve Naroffc540d662008-09-03 18:15:37 +0000957 // Otherwise, verify that this result type matches the previous one. We are
958 // pickier with blocks than for normal functions because we don't have GCC
959 // compatibility to worry about here.
960 if (CurBlock->ReturnType->isVoidType()) {
961 if (RetValExp) {
962 Diag(ReturnLoc, diag::err_return_block_has_expr);
Ted Kremenek5a201952009-02-07 01:47:29 +0000963 RetValExp->Destroy(Context);
Steve Naroffc540d662008-09-03 18:15:37 +0000964 RetValExp = 0;
965 }
Ted Kremenek5a201952009-02-07 01:47:29 +0000966 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroffc540d662008-09-03 18:15:37 +0000967 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000968
969 if (!RetValExp)
970 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
971
Mike Stump82f071f2009-02-04 22:31:32 +0000972 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
973 // we have a non-void block with an expression, continue checking
974 QualType RetValType = RetValExp->getType();
Sebastian Redl573feed2009-01-18 13:19:59 +0000975
Mike Stump11289f42009-09-09 15:08:12 +0000976 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
977 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
Mike Stump82f071f2009-02-04 22:31:32 +0000978 // function return.
979
980 // In C++ the return statement is handled via a copy initialization.
981 // the C version of which boils down to CheckSingleAssignmentConstraints.
982 // FIXME: Leaks RetValExp.
983 if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
984 return StmtError();
985
986 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +0000987 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000988
Ted Kremenek5a201952009-02-07 01:47:29 +0000989 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroffc540d662008-09-03 18:15:37 +0000990}
Chris Lattneraf8d5812006-11-10 05:07:45 +0000991
Sebastian Redl42e92c42009-04-12 17:16:29 +0000992/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
993/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
994static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
995 Expr *RetExpr) {
996 QualType ExprType = RetExpr->getType();
997 // - in a return statement in a function with ...
998 // ... a class return type ...
999 if (!RetType->isRecordType())
1000 return false;
1001 // ... the same cv-unqualified type as the function return type ...
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001002 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
Sebastian Redl42e92c42009-04-12 17:16:29 +00001003 return false;
1004 // ... the expression is the name of a non-volatile automatic object ...
1005 // We ignore parentheses here.
1006 // FIXME: Is this compliant?
1007 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1008 if (!DR)
1009 return false;
1010 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1011 if (!VD)
1012 return false;
1013 return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
1014 && !VD->getType().isVolatileQualified();
1015}
1016
Sebastian Redl573feed2009-01-18 13:19:59 +00001017Action::OwningStmtResult
Anders Carlssona1929472009-08-18 16:11:00 +00001018Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
1019 Expr *RetValExp = rex.takeAs<Expr>();
Steve Naroffc540d662008-09-03 18:15:37 +00001020 if (CurBlock)
1021 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00001022
Chris Lattner79413952008-12-04 23:50:19 +00001023 QualType FnRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001024 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00001025 FnRetType = FD->getResultType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001026 if (FD->hasAttr<NoReturnAttr>())
Chris Lattner6e127a62009-05-31 19:32:13 +00001027 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001028 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001029 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Narofff3833d72009-03-03 00:45:38 +00001030 FnRetType = MD->getResultType();
1031 else // If we don't have a function/method context, bail.
1032 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattner9bad62c2008-01-04 18:04:52 +00001034 if (FnRetType->isVoidType()) {
Douglas Gregor78b691a2009-10-01 23:25:31 +00001035 if (RetValExp && !RetValExp->isTypeDependent()) {
1036 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner27e5bef2008-12-18 02:01:17 +00001037 unsigned D = diag::ext_return_has_expr;
1038 if (RetValExp->getType()->isVoidType())
1039 D = diag::ext_return_has_void_expr;
Sebastian Redl573feed2009-01-18 13:19:59 +00001040
Chris Lattner0cb00d62008-12-18 02:03:48 +00001041 // return (some void expression); is legal in C++.
1042 if (D != diag::ext_return_has_void_expr ||
1043 !getLangOptions().CPlusPlus) {
1044 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1045 Diag(ReturnLoc, D)
1046 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1047 << RetValExp->getSourceRange();
1048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Anders Carlssona1929472009-08-18 16:11:00 +00001050 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001051 }
Ted Kremenek5a201952009-02-07 01:47:29 +00001052 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroff9358c712007-05-27 23:58:33 +00001053 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001054
Anders Carlsson19b8c4c2009-05-15 00:48:27 +00001055 if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001056 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1057 // C99 6.8.6.4p1 (ext_ since GCC warns)
1058 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1059
1060 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001061 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001062 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001063 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Ted Kremenek5a201952009-02-07 01:47:29 +00001064 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001065 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001066
Douglas Gregor4619e432008-12-05 23:32:09 +00001067 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1068 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001069
Mike Stump11289f42009-09-09 15:08:12 +00001070 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1071 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
Sebastian Redl573feed2009-01-18 13:19:59 +00001072 // function return.
1073
Sebastian Redl42e92c42009-04-12 17:16:29 +00001074 // C++0x 12.8p15: When certain criteria are met, an implementation is
1075 // allowed to omit the copy construction of a class object, [...]
1076 // - in a return statement in a function with a class return type, when
1077 // the expression is the name of a non-volatile automatic object with
1078 // the same cv-unqualified type as the function return type, the copy
1079 // operation can be omitted [...]
1080 // C++0x 12.8p16: When the criteria for elision of a copy operation are met
1081 // and the object to be copied is designated by an lvalue, overload
1082 // resolution to select the constructor for the copy is first performed
1083 // as if the object were designated by an rvalue.
1084 // Note that we only compute Elidable if we're in C++0x, since we don't
1085 // care otherwise.
1086 bool Elidable = getLangOptions().CPlusPlus0x ?
1087 IsReturnCopyElidable(Context, FnRetType, RetValExp) :
1088 false;
1089
Douglas Gregor4619e432008-12-05 23:32:09 +00001090 // In C++ the return statement is handled via a copy initialization.
Sebastian Redl573feed2009-01-18 13:19:59 +00001091 // the C version of which boils down to CheckSingleAssignmentConstraints.
Sebastian Redl42e92c42009-04-12 17:16:29 +00001092 // FIXME: Leaks RetValExp on error.
Douglas Gregorffe14e32009-11-14 01:20:54 +00001093 if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable)){
1094 // We should still clean up our temporaries, even when we're failing!
1095 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Sebastian Redl573feed2009-01-18 13:19:59 +00001096 return StmtError();
Douglas Gregorffe14e32009-11-14 01:20:54 +00001097 }
1098
Douglas Gregor4619e432008-12-05 23:32:09 +00001099 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1100 }
1101
Anders Carlssona1929472009-08-18 16:11:00 +00001102 if (RetValExp)
1103 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Ted Kremenek5a201952009-02-07 01:47:29 +00001104 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001105}
1106
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001107/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1108/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1109/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1110/// provide a strong guidance to not use it.
1111///
1112/// This method checks to see if the argument is an acceptable l-value and
1113/// returns false if it is a case we can handle.
1114static bool CheckAsmLValue(const Expr *E, Sema &S) {
1115 if (E->isLvalue(S.Context) == Expr::LV_Valid)
1116 return false; // Cool, this is an lvalue.
1117
1118 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1119 // are supposed to allow.
1120 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1121 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1122 if (!S.getLangOptions().HeinousExtensions)
1123 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1124 << E->getSourceRange();
1125 else
1126 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1127 << E->getSourceRange();
1128 // Accept, even if we emitted an error diagnostic.
1129 return false;
1130 }
1131
1132 // None of the above, just randomly invalid non-lvalue.
1133 return true;
1134}
1135
1136
Sebastian Redl24b8e152009-01-18 16:53:17 +00001137Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1138 bool IsSimple,
1139 bool IsVolatile,
1140 unsigned NumOutputs,
1141 unsigned NumInputs,
1142 std::string *Names,
1143 MultiExprArg constraints,
1144 MultiExprArg exprs,
1145 ExprArg asmString,
1146 MultiExprArg clobbers,
1147 SourceLocation RParenLoc) {
1148 unsigned NumClobbers = clobbers.size();
1149 StringLiteral **Constraints =
1150 reinterpret_cast<StringLiteral**>(constraints.get());
1151 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1152 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1153 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1154
Anders Carlsson570c3572009-01-27 20:38:24 +00001155 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Chris Lattner496acc12008-08-18 19:55:17 +00001157 // The parser verifies that there is a string literal here.
Chris Lattner07096892008-07-23 06:46:56 +00001158 if (AsmString->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001159 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1160 << AsmString->getSourceRange());
1161
Chris Lattner496acc12008-08-18 19:55:17 +00001162 for (unsigned i = 0; i != NumOutputs; i++) {
1163 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001164 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001165 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1166 << Literal->getSourceRange());
1167
Mike Stump11289f42009-09-09 15:08:12 +00001168 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001169 Literal->getByteLength(),
1170 Names[i]);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001171 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001172 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001173 diag::err_asm_invalid_output_constraint)
1174 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001175
Anders Carlssonf511f642007-11-27 04:11:28 +00001176 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00001177 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001178 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00001179 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001180 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00001181 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001182 }
Mike Stump11289f42009-09-09 15:08:12 +00001183
Chris Lattnerd9725f72009-04-26 07:16:29 +00001184 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001185 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001186
Chris Lattner34b51e82009-05-03 05:55:43 +00001187 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1188
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001189 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00001190 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001191 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001192 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1193 << Literal->getSourceRange());
1194
Mike Stump11289f42009-09-09 15:08:12 +00001195 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001196 Literal->getByteLength(),
1197 Names[i]);
Jay Foad7d0479f2009-05-21 09:52:38 +00001198 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001199 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001200 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001201 diag::err_asm_invalid_input_constraint)
1202 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00001203 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001204
Eli Friedman47e78572009-05-03 07:49:42 +00001205 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00001206
Anders Carlsson224fca82009-01-20 20:49:22 +00001207 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00001208 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001209 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00001210 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001211 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001212 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001213 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001214 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001215
Chris Lattnerd9725f72009-04-26 07:16:29 +00001216 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00001217 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00001218 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001219 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00001220 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001221 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00001222 }
Anders Carlsson224fca82009-01-20 20:49:22 +00001223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
Anders Carlssonb8482c52009-02-22 02:11:23 +00001225 DefaultFunctionArrayConversion(Exprs[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001226
Chris Lattner34b51e82009-05-03 05:55:43 +00001227 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001228 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001229
Anders Carlsson290aa852007-11-25 00:25:21 +00001230 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00001231 for (unsigned i = 0; i != NumClobbers; i++) {
1232 StringLiteral *Literal = Clobbers[i];
Chris Lattner07096892008-07-23 06:46:56 +00001233 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001234 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1235 << Literal->getSourceRange());
1236
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001237 std::string Clobber(Literal->getStrData(),
1238 Literal->getStrData() +
1239 Literal->getByteLength());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001240
Chris Lattner07096892008-07-23 06:46:56 +00001241 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001242 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001243 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00001244 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001245
1246 constraints.release();
1247 exprs.release();
1248 asmString.release();
1249 clobbers.release();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001250 AsmStmt *NS =
1251 new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1252 Names, Constraints, Exprs, AsmString, NumClobbers,
1253 Clobbers, RParenLoc);
1254 // Validate the asm string, ensuring it makes sense given the operands we
1255 // have.
1256 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1257 unsigned DiagOffs;
1258 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00001259 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1260 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001261 DeleteStmt(NS);
1262 return StmtError();
1263 }
Mike Stump11289f42009-09-09 15:08:12 +00001264
Chris Lattner34b51e82009-05-03 05:55:43 +00001265 // Validate tied input operands for type mismatches.
1266 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1267 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00001268
Chris Lattner34b51e82009-05-03 05:55:43 +00001269 // If this is a tied constraint, verify that the output and input have
1270 // either exactly the same type, or that they are int/ptr operands with the
1271 // same size (int/long, int*/long, are ok etc).
1272 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001273
Chris Lattner34b51e82009-05-03 05:55:43 +00001274 unsigned TiedTo = Info.getTiedOperand();
Chris Lattnercb66c732009-05-03 07:04:21 +00001275 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner28b05c82009-05-03 06:50:40 +00001276 Expr *InputExpr = Exprs[i+NumOutputs];
Chris Lattner2c295cf2009-05-03 05:59:17 +00001277 QualType InTy = InputExpr->getType();
1278 QualType OutTy = OutputExpr->getType();
1279 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00001280 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner2c295cf2009-05-03 05:59:17 +00001282 // Int/ptr operands have some special cases that we allow.
1283 if ((OutTy->isIntegerType() || OutTy->isPointerType()) &&
1284 (InTy->isIntegerType() || InTy->isPointerType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattner2c295cf2009-05-03 05:59:17 +00001286 // They are ok if they are the same size. Tying void* to int is ok if
1287 // they are the same size, for example. This also allows tying void* to
1288 // int*.
Chris Lattnercc1cde92009-05-03 08:32:32 +00001289 uint64_t OutSize = Context.getTypeSize(OutTy);
1290 uint64_t InSize = Context.getTypeSize(InTy);
1291 if (OutSize == InSize)
Chris Lattner34b51e82009-05-03 05:55:43 +00001292 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001293
Chris Lattnercc1cde92009-05-03 08:32:32 +00001294 // If the smaller input/output operand is not mentioned in the asm string,
1295 // then we can promote it and the asm string won't notice. Check this
Chris Lattnercb66c732009-05-03 07:04:21 +00001296 // case now.
Chris Lattnercc1cde92009-05-03 08:32:32 +00001297 bool SmallerValueMentioned = false;
Chris Lattner97de21f2009-05-03 08:24:16 +00001298 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1299 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1300 if (!Piece.isOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattnercc1cde92009-05-03 08:32:32 +00001302 // If this is a reference to the input and if the input was the smaller
1303 // one, then we have to reject this asm.
1304 if (Piece.getOperandNo() == i+NumOutputs) {
1305 if (InSize < OutSize) {
1306 SmallerValueMentioned = true;
1307 break;
1308 }
1309 }
1310
1311 // If this is a reference to the input and if the input was the smaller
1312 // one, then we have to reject this asm.
1313 if (Piece.getOperandNo() == TiedTo) {
1314 if (InSize > OutSize) {
1315 SmallerValueMentioned = true;
1316 break;
1317 }
1318 }
Chris Lattnercb66c732009-05-03 07:04:21 +00001319 }
Mike Stump11289f42009-09-09 15:08:12 +00001320
Chris Lattnercc1cde92009-05-03 08:32:32 +00001321 // If the smaller value wasn't mentioned in the asm string, and if the
1322 // output was a register, just extend the shorter one to the size of the
1323 // larger one.
1324 if (!SmallerValueMentioned &&
Chris Lattnercb66c732009-05-03 07:04:21 +00001325 OutputConstraintInfos[TiedTo].allowsRegister())
1326 continue;
Chris Lattner34b51e82009-05-03 05:55:43 +00001327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattner28b05c82009-05-03 06:50:40 +00001329 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00001330 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00001331 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00001332 << InputExpr->getSourceRange();
1333 DeleteStmt(NS);
1334 return StmtError();
1335 }
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001337 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00001338}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001339
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001340Action::OwningStmtResult
1341Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001342 SourceLocation RParen, DeclPtrTy Parm,
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001343 StmtArg Body, StmtArg catchList) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001344 Stmt *CatchList = catchList.takeAs<Stmt>();
Chris Lattner83f095c2009-03-28 19:18:32 +00001345 ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001346
Steve Naroff39d6fba2009-03-03 20:59:06 +00001347 // PVD == 0 implies @catch(...).
Steve Naroff27ed6f62009-03-03 21:16:54 +00001348 if (PVD) {
Chris Lattnera2ca03a2009-04-12 23:26:56 +00001349 // If we already know the decl is invalid, reject it.
1350 if (PVD->isInvalidDecl())
1351 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001352
Steve Naroff79d12152009-07-16 15:41:00 +00001353 if (!PVD->getType()->isObjCObjectPointerType())
Mike Stump11289f42009-09-09 15:08:12 +00001354 return StmtError(Diag(PVD->getLocation(),
Steve Naroff27ed6f62009-03-03 21:16:54 +00001355 diag::err_catch_param_not_objc_type));
1356 if (PVD->getType()->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00001357 return StmtError(Diag(PVD->getLocation(),
Steve Naroff013813d2009-03-03 23:13:51 +00001358 diag::err_illegal_qualifiers_on_catch_parm));
Steve Naroff27ed6f62009-03-03 21:16:54 +00001359 }
Chris Lattnera2ca03a2009-04-12 23:26:56 +00001360
Ted Kremenek5a201952009-02-07 01:47:29 +00001361 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001362 PVD, Body.takeAs<Stmt>(), CatchList);
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001363 return Owned(CatchList ? CatchList : CS);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001364}
1365
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001366Action::OwningStmtResult
1367Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001368 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1369 static_cast<Stmt*>(Body.release())));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00001370}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001371
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001372Action::OwningStmtResult
1373Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1374 StmtArg Try, StmtArg Catch, StmtArg Finally) {
Chris Lattner9fecd742009-04-19 05:21:20 +00001375 CurFunctionNeedsScopeChecking = true;
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001376 return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(),
1377 Catch.takeAs<Stmt>(),
1378 Finally.takeAs<Stmt>()));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001379}
1380
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001381Action::OwningStmtResult
Steve Naroff0fa412c2009-02-12 15:54:59 +00001382Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001383 Expr *ThrowExpr = expr.takeAs<Expr>();
Steve Naroffd5581d22009-02-11 17:45:08 +00001384 if (!ThrowExpr) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00001385 // @throw without an expression designates a rethrow (which much occur
1386 // in the context of an @catch clause).
1387 Scope *AtCatchParent = CurScope;
1388 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1389 AtCatchParent = AtCatchParent->getParent();
1390 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00001391 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
Steve Naroffd5581d22009-02-11 17:45:08 +00001392 } else {
1393 QualType ThrowType = ThrowExpr->getType();
1394 // Make sure the expression type is an ObjC pointer or "void *".
Steve Naroff79d12152009-07-16 15:41:00 +00001395 if (!ThrowType->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001396 const PointerType *PT = ThrowType->getAs<PointerType>();
Steve Naroffd5581d22009-02-11 17:45:08 +00001397 if (!PT || !PT->getPointeeType()->isVoidType())
Steve Naroffc49b22a2009-02-12 18:09:32 +00001398 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1399 << ThrowExpr->getType() << ThrowExpr->getSourceRange());
Steve Naroffd5581d22009-02-11 17:45:08 +00001400 }
1401 }
1402 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00001403}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001404
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001405Action::OwningStmtResult
1406Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1407 StmtArg SynchBody) {
Chris Lattnerc70dd562009-04-21 06:01:00 +00001408 CurFunctionNeedsScopeChecking = true;
1409
Chris Lattner3501d432009-04-21 06:11:25 +00001410 // Make sure the expression type is an ObjC pointer or "void *".
1411 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
Steve Naroff79d12152009-07-16 15:41:00 +00001412 if (!SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001413 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattner3501d432009-04-21 06:11:25 +00001414 if (!PT || !PT->getPointeeType()->isVoidType())
1415 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1416 << SyncExpr->getType() << SyncExpr->getSourceRange());
1417 }
Mike Stump11289f42009-09-09 15:08:12 +00001418
1419 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001420 SynchExpr.takeAs<Stmt>(),
1421 SynchBody.takeAs<Stmt>()));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00001422}
Sebastian Redl54c04d42008-12-22 19:15:10 +00001423
1424/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1425/// and creates a proper catch handler from them.
1426Action::OwningStmtResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001427Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
Sebastian Redl54c04d42008-12-22 19:15:10 +00001428 StmtArg HandlerBlock) {
1429 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00001430 return Owned(new (Context) CXXCatchStmt(CatchLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001431 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001432 HandlerBlock.takeAs<Stmt>()));
Sebastian Redl54c04d42008-12-22 19:15:10 +00001433}
Sebastian Redl9b244a82008-12-22 21:35:02 +00001434
Sebastian Redl63c4da02009-07-29 17:15:45 +00001435class TypeWithHandler {
1436 QualType t;
1437 CXXCatchStmt *stmt;
1438public:
1439 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1440 : t(type), stmt(statement) {}
1441
John McCall8ccfcb52009-09-24 19:53:00 +00001442 // An arbitrary order is fine as long as it places identical
1443 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00001444 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001445 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001446 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00001447 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001448 return false;
1449 else
1450 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Sebastian Redl63c4da02009-07-29 17:15:45 +00001453 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001454 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
Sebastian Redl63c4da02009-07-29 17:15:45 +00001457 QualType getQualType() const { return t; }
1458 CXXCatchStmt *getCatchStmt() const { return stmt; }
1459 SourceLocation getTypeSpecStartLoc() const {
1460 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1461 }
1462};
1463
Sebastian Redl9b244a82008-12-22 21:35:02 +00001464/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1465/// handlers and creates a try statement from them.
1466Action::OwningStmtResult
1467Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1468 MultiStmtArg RawHandlers) {
1469 unsigned NumHandlers = RawHandlers.size();
1470 assert(NumHandlers > 0 &&
1471 "The parser shouldn't call this if there are no handlers.");
1472 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1473
Sebastian Redl63c4da02009-07-29 17:15:45 +00001474 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00001475
1476 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl9b244a82008-12-22 21:35:02 +00001477 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00001478 if (!Handler->getExceptionDecl()) {
1479 if (i < NumHandlers - 1)
1480 return StmtError(Diag(Handler->getLocStart(),
1481 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00001482
Sebastian Redl63c4da02009-07-29 17:15:45 +00001483 continue;
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Sebastian Redl63c4da02009-07-29 17:15:45 +00001486 const QualType CaughtType = Handler->getCaughtType();
1487 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1488 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001489 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00001490
1491 // Detect handlers for the same type as an earlier one.
1492 if (NumHandlers > 1) {
1493 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00001494
Sebastian Redl63c4da02009-07-29 17:15:45 +00001495 TypeWithHandler prev = TypesWithHandlers[0];
1496 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1497 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00001498
Sebastian Redl63c4da02009-07-29 17:15:45 +00001499 if (curr == prev) {
1500 Diag(curr.getTypeSpecStartLoc(),
1501 diag::warn_exception_caught_by_earlier_handler)
1502 << curr.getCatchStmt()->getCaughtType().getAsString();
1503 Diag(prev.getTypeSpecStartLoc(),
1504 diag::note_previous_exception_handler)
1505 << prev.getCatchStmt()->getCaughtType().getAsString();
1506 }
Mike Stump11289f42009-09-09 15:08:12 +00001507
Sebastian Redl63c4da02009-07-29 17:15:45 +00001508 prev = curr;
1509 }
1510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Sebastian Redl9b244a82008-12-22 21:35:02 +00001512 // FIXME: We should detect handlers that cannot catch anything because an
1513 // earlier handler catches a superclass. Need to find a method that is not
1514 // quadratic for this.
1515 // Neither of these are explicitly forbidden, but every compiler detects them
1516 // and warns.
1517
Sebastian Redl4de47b42009-04-27 20:27:31 +00001518 CurFunctionNeedsScopeChecking = true;
Sebastian Redl9b244a82008-12-22 21:35:02 +00001519 RawHandlers.release();
Ted Kremenek5a201952009-02-07 01:47:29 +00001520 return Owned(new (Context) CXXTryStmt(TryLoc,
1521 static_cast<Stmt*>(TryBlock.release()),
1522 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001523}