blob: 464206eafe31b8192b6c6e1c9bea8ced15ab2e2c [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"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000022#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000023#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000025#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000036using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000037using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000038
Richard Smith945f8d32013-01-14 22:39:08 +000039StmtResult Sema::ActOnExprStmt(ExprResult FE) {
40 if (FE.isInvalid())
41 return StmtError();
42
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
45 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000046 return StmtError();
47
Chris Lattner903eb512008-07-25 23:18:17 +000048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000051
Chris Lattner903eb512008-07-25 23:18:17 +000052 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000053 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000054}
55
56
John McCalleaef89b2013-03-22 02:10:40 +000057StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
59 return StmtError();
60}
61
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000062StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000063 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000065}
66
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000067StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000069 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000070
Chris Lattnercbafe8d2009-04-12 20:13:14 +000071 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000073
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000074 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000075}
Chris Lattneraf8d5812006-11-10 05:07:45 +000076
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000077void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000078 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000079
Douglas Gregor2eb1c572013-04-08 20:52:24 +000080 // If we don't have a declaration, or we have an invalid declaration,
81 // just return.
82 if (DG.isNull() || !DG.isSingleDecl())
83 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
87 return;
88
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
91 if (!var) {
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
94 return;
95 }
John McCall31168b02011-06-15 23:02:42 +000096
John McCalld4631322011-06-17 06:42:21 +000097 // foreach variables are never actually initialized in the way that
98 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +000099 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // In ARC, we don't need to retain the iteration variable of a fast
102 // enumeration loop. Rather than actually trying to catch that
103 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000104 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000105 QualType type = var->getType();
106
107 // Only do this if we inferred the lifetime. Inferred lifetime
108 // will show up as a local qualifier because explicit lifetime
109 // should have shown up as an AttributedType instead.
110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
111 // Add 'const' and mark the variable as pseudo-strong.
112 var->setType(type.withConst());
113 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000114 }
115 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000116}
117
Richard Trieu99e1c952014-03-11 03:11:08 +0000118/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
119/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120///
121/// Adding a cast to void (or other expression wrappers) will prevent the
122/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000123static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000125 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126
127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000128 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000129 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
Richard Trieu99e1c952014-03-11 03:11:08 +0000131 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 switch (Op->getOperator()) {
137 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000138 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000139 case OO_EqualEqual:
140 case OO_ExclaimEqual:
141 IsRelational = false;
142 break;
143 case OO_Less:
144 case OO_Greater:
145 case OO_GreaterEqual:
146 case OO_LessEqual:
147 IsRelational = true;
148 break;
149 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000151 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154 } else {
155 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000156 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000157 }
158
159 // Suppress warnings when the operator, suspicious as it may be, comes from
160 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000161 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000162 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000163
Chandler Carruthe2669392011-08-17 09:34:37 +0000164 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000166
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000167 // If the LHS is a plausible entity to assign to, provide a fixit hint to
168 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000170 if (IsNotEqual)
171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
172 << FixItHint::CreateReplacement(Loc, "|=");
173 else
174 S.Diag(Loc, diag::note_equality_comparison_to_assign)
175 << FixItHint::CreateReplacement(Loc, "=");
176 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000177
178 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000179}
180
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000181void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
183 return DiagnoseUnusedExprResult(Label->getSubStmt());
184
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000185 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186 if (!E)
187 return;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000188 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000189 // In most cases, we don't want to warn if the expression is written in a
190 // macro body, or if the macro comes from a system header. If the offending
191 // expression is a call to a function with the warn_unused_result attribute,
192 // we warn no matter the location. Because of the order in which the various
193 // checks need to happen, we factor out the macro-related test here.
194 bool ShouldSuppress =
195 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
196 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000197
Eli Friedmanc11535c2012-05-24 00:47:05 +0000198 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000199 SourceLocation Loc;
200 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000201 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000202 return;
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner6dc7e572012-08-31 22:39:21 +0000204 // If this is a GNU statement expression expanded from a macro, it is probably
205 // unused because it is a function-like macro that can be used as either an
206 // expression or statement. Don't warn, because it is almost certainly a
207 // false positive.
208 if (isa<StmtExpr>(E) && Loc.isMacroID())
209 return;
210
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000211 // Okay, we have an unused result. Depending on what the base expression is,
212 // we might want to make a more specific diagnostic. Check for one of these
213 // cases now.
214 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000215 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000216 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000217 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
218 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000219
Chandler Carruthe2669392011-08-17 09:34:37 +0000220 if (DiagnoseUnusedComparison(*this, E))
221 return;
222
Eli Friedmanc11535c2012-05-24 00:47:05 +0000223 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000224 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000225 if (E->getType()->isVoidType())
226 return;
227
Chris Lattner1a6babf2009-10-13 04:53:48 +0000228 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000229 // a more specific message to make it clear what is happening. If the call
230 // is written in a macro body, only warn if it has the warn_unused_result
231 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000232 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000233 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000234 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000235 return;
236 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000237 if (ShouldSuppress)
238 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000239 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000240 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
241 return;
242 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000243 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
245 return;
246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000247 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000248 } else if (ShouldSuppress)
249 return;
250
251 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000252 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000253 Diag(Loc, diag::err_arc_unused_init_message) << R1;
254 return;
255 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000256 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000257 if (MD) {
258 if (MD->hasAttr<WarnUnusedResultAttr>()) {
259 Diag(Loc, diag::warn_unused_result) << R1 << R2;
260 return;
261 }
262 if (MD->isPropertyAccessor()) {
263 Diag(Loc, diag::warn_unused_property_expr);
264 return;
265 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000266 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000267 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
268 const Expr *Source = POE->getSyntacticForm();
269 if (isa<ObjCSubscriptRefExpr>(Source))
270 DiagID = diag::warn_unused_container_subscript_expr;
271 else
272 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000273 } else if (const CXXFunctionalCastExpr *FC
274 = dyn_cast<CXXFunctionalCastExpr>(E)) {
275 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
276 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
277 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 }
John McCall2351cb92010-04-06 22:24:14 +0000279 // Diagnose "(void*) blah" as a typo for "(void) blah".
280 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
281 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
282 QualType T = TI->getType();
283
284 // We really do want to use the non-canonical type here.
285 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000286 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000287
288 Diag(Loc, diag::warn_unused_voidptr)
289 << FixItHint::CreateRemoval(TL.getStarLoc());
290 return;
291 }
292 }
293
Eli Friedmanc11535c2012-05-24 00:47:05 +0000294 if (E->isGLValue() && E->getType().isVolatileQualified()) {
295 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
296 return;
297 }
298
Craig Topperc3ec1492014-05-26 06:22:03 +0000299 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000300}
301
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000302void Sema::ActOnStartOfCompoundStmt() {
303 PushCompoundScope();
304}
305
306void Sema::ActOnFinishOfCompoundStmt() {
307 PopCompoundScope();
308}
309
310sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
311 return getCurFunction()->CompoundScopes.back();
312}
313
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000314StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
315 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
316 const unsigned NumElts = Elts.size();
317
Chris Lattnerd864daf2007-08-27 04:29:41 +0000318 // If we're in C89 mode, check that we don't have any decls after stmts. If
319 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000320 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000321 // Note that __extension__ can be around a decl.
322 unsigned i = 0;
323 // Skip over all declarations.
324 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
325 /*empty*/;
326
327 // We found the end of the list or a statement. Scan for another declstmt.
328 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
329 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattnerd864daf2007-08-27 04:29:41 +0000331 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000332 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000333 Diag(D->getLocation(), diag::ext_mixed_decls_code);
334 }
335 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000336 // Warn about unused expressions in statements.
337 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000338 // Ignore statements that are last in a statement expression.
339 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000340 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000341
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000342 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000343 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000344
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000345 // Check for suspicious empty body (null statement) in `for' and `while'
346 // statements. Don't do anything for template instantiations, this just adds
347 // noise.
348 if (NumElts != 0 && !CurrentInstantiationScope &&
349 getCurCompoundScope().HasEmptyLoopBodies) {
350 for (unsigned i = 0; i != NumElts - 1; ++i)
351 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
352 }
353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000354 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000355}
356
John McCalldadc5752010-08-24 06:29:42 +0000357StmtResult
John McCallb268a282010-08-23 23:25:46 +0000358Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
359 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000360 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000361 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000362
John McCallaab3e412010-08-25 08:40:02 +0000363 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000364 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000365 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000366 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000367
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000368 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000369 // C99 6.8.4.2p3: The expression shall be an integer constant.
370 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000371 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000372 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000373 if (!LHSVal)
374 return StmtError();
375 }
Richard Smithf8379a02012-01-18 23:55:52 +0000376
377 // GCC extension: The expression shall be an integer constant.
378
Richard Smithf4c51d92012-02-04 09:53:13 +0000379 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000380 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000381 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000382 }
383 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000384
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000385 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000386 getLangOpts().CPlusPlus11).get();
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000387 if (RHSVal)
388 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000389 getLangOpts().CPlusPlus11).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000390
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000391 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
392 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000393 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000394 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000395}
396
Chris Lattner34a22092009-03-04 04:23:07 +0000397/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000398void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000399 DiagnoseUnusedExprResult(SubStmt);
400
Chris Lattner34a22092009-03-04 04:23:07 +0000401 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000402 CS->setSubStmt(SubStmt);
403}
404
John McCalldadc5752010-08-24 06:29:42 +0000405StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000406Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000407 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000408 DiagnoseUnusedExprResult(SubStmt);
409
John McCallaab3e412010-08-25 08:40:02 +0000410 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000411 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000412 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000413 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000414
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000415 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000416 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000417 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000418}
419
John McCalldadc5752010-08-24 06:29:42 +0000420StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000421Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
422 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000423 // If the label was multiply defined, reject it now.
424 if (TheDecl->getStmt()) {
425 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
426 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000427 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000428 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000429
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000430 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000431 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
432 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000433 if (!TheDecl->isGnuLocal()) {
434 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000435 if (!TheDecl->isMSAsmLabel()) {
436 // Don't update the location of MS ASM labels. These will result in
437 // a diagnostic, and changing the location here will mess that up.
438 TheDecl->setLocation(IdentLoc);
439 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000440 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000441 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000442}
443
Richard Smithc202b282012-04-14 00:33:13 +0000444StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000445 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000446 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000447 // Fill in the declaration and return it.
448 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000449 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000450}
451
John McCalldadc5752010-08-24 06:29:42 +0000452StmtResult
John McCall48871652010-08-21 09:40:31 +0000453Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000454 Stmt *thenStmt, SourceLocation ElseLoc,
455 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000456 // If the condition was invalid, discard the if statement. We could recover
457 // better by replacing it with a valid expr, but don't do that yet.
458 if (!CondVal.get() && !CondVar) {
459 getCurFunction()->setHasDroppedStmt();
460 return StmtError();
461 }
462
John McCalldadc5752010-08-24 06:29:42 +0000463 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000464
Craig Topperc3ec1492014-05-26 06:22:03 +0000465 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000466 if (CondVar) {
467 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000468 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000469 if (CondResult.isInvalid())
470 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000471 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000472 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000473 if (!ConditionExpr)
474 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000476 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000477
John McCallb268a282010-08-23 23:25:46 +0000478 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000479 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
480 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000481 }
482
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000483 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000484
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000485 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
486 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000487}
Steve Naroff86272ea2007-05-29 02:14:17 +0000488
Chris Lattner67998452007-08-23 18:29:20 +0000489namespace {
490 struct CaseCompareFunctor {
491 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
492 const llvm::APSInt &RHS) {
493 return LHS.first < RHS;
494 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000495 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
496 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
497 return LHS.first < RHS.first;
498 }
Chris Lattner67998452007-08-23 18:29:20 +0000499 bool operator()(const llvm::APSInt &LHS,
500 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
501 return LHS < RHS.first;
502 }
503 };
504}
505
Chris Lattner4b2ff022007-09-21 18:15:22 +0000506/// CmpCaseVals - Comparison predicate for sorting case values.
507///
508static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
509 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
510 if (lhs.first < rhs.first)
511 return true;
512
513 if (lhs.first == rhs.first &&
514 lhs.second->getCaseLoc().getRawEncoding()
515 < rhs.second->getCaseLoc().getRawEncoding())
516 return true;
517 return false;
518}
519
Douglas Gregorbd6839732010-02-08 22:24:16 +0000520/// CmpEnumVals - Comparison predicate for sorting enumeration values.
521///
522static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
523 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
524{
525 return lhs.first < rhs.first;
526}
527
528/// EqEnumVals - Comparison preficate for uniqing enumeration values.
529///
530static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
531 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
532{
533 return lhs.first == rhs.first;
534}
535
Chris Lattnera96d4272009-10-16 16:45:22 +0000536/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
537/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000538static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
539 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
540 expr = cleanups->getSubExpr();
541 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
542 if (impcast->getCastKind() != CK_IntegralCast) break;
543 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000544 }
545 return expr->getType();
546}
547
John McCalldadc5752010-08-24 06:29:42 +0000548StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000549Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000550 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000551 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000552
Craig Topperc3ec1492014-05-26 06:22:03 +0000553 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000554 if (CondVar) {
555 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000556 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
557 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000558 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000560 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
John McCallb268a282010-08-23 23:25:46 +0000563 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000564 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregore2b37442012-05-04 22:38:52 +0000566 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
567 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000568
Douglas Gregore2b37442012-05-04 22:38:52 +0000569 public:
570 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000571 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
572 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000573
Craig Toppere14c0f82014-03-12 04:55:44 +0000574 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
575 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000576 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
577 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000578
Craig Toppere14c0f82014-03-12 04:55:44 +0000579 SemaDiagnosticBuilder diagnoseIncomplete(
580 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000581 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
582 << T << Cond->getSourceRange();
583 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000584
Craig Toppere14c0f82014-03-12 04:55:44 +0000585 SemaDiagnosticBuilder diagnoseExplicitConv(
586 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000587 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
588 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000589
Craig Toppere14c0f82014-03-12 04:55:44 +0000590 SemaDiagnosticBuilder noteExplicitConv(
591 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000592 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
593 << ConvTy->isEnumeralType() << ConvTy;
594 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000595
Craig Toppere14c0f82014-03-12 04:55:44 +0000596 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
597 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000598 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
599 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000600
Craig Toppere14c0f82014-03-12 04:55:44 +0000601 SemaDiagnosticBuilder noteAmbiguous(
602 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000603 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
604 << ConvTy->isEnumeralType() << ConvTy;
605 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000606
Craig Toppere14c0f82014-03-12 04:55:44 +0000607 SemaDiagnosticBuilder diagnoseConversion(
608 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000609 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000610 }
611 } SwitchDiagnoser(Cond);
612
Richard Smithccc11812013-05-21 19:05:48 +0000613 CondResult =
614 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000615 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000616 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
John McCall5939b162011-08-06 07:30:58 +0000618 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
619 CondResult = UsualUnaryConversions(Cond);
620 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000621 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000622
John McCall48871652010-08-21 09:40:31 +0000623 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000624 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000625 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000626 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000627 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000628 }
John McCalla95172b2010-08-01 00:26:45 +0000629
John McCallaab3e412010-08-25 08:40:02 +0000630 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
John McCallb268a282010-08-23 23:25:46 +0000632 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000633 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000634 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000635}
636
Gabor Greif16e02862010-10-01 22:05:14 +0000637static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000638 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000639 Val.setIsSigned(IsSigned);
640}
641
Richard Smith077d0832014-08-04 00:40:48 +0000642/// Check the specified case value is in range for the given unpromoted switch
643/// type.
644static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
645 unsigned UnpromotedWidth, bool UnpromotedSign) {
646 // If the case value was signed and negative and the switch expression is
647 // unsigned, don't bother to warn: this is implementation-defined behavior.
648 // FIXME: Introduce a second, default-ignored warning for this case?
649 if (UnpromotedWidth < Val.getBitWidth()) {
650 llvm::APSInt ConvVal(Val);
651 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
652 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
653 // FIXME: Use different diagnostics for overflow in conversion to promoted
654 // type versus "switch expression cannot have this value". Use proper
655 // IntRange checking rather than just looking at the unpromoted type here.
656 if (ConvVal != Val)
657 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
658 << ConvVal.toString(10);
659 }
660}
661
Dmitri Gribenko58683752013-12-05 22:52:07 +0000662/// Returns true if we should emit a diagnostic about this case expression not
663/// being a part of the enum used in the switch controlling expression.
664static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
665 const EnumDecl *ED,
666 const Expr *CaseExpr) {
667 // Don't warn if the 'case' expression refers to a static const variable of
668 // the enum type.
669 CaseExpr = CaseExpr->IgnoreParenImpCasts();
670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
671 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
672 if (!VD->hasGlobalStorage())
673 return true;
674 QualType VarType = VD->getType();
675 if (!VarType.isConstQualified())
676 return true;
677 QualType EnumType = Ctx.getTypeDeclType(ED);
678 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
679 return false;
680 }
681 }
682 return true;
683}
684
John McCalldadc5752010-08-24 06:29:42 +0000685StmtResult
John McCallb268a282010-08-23 23:25:46 +0000686Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
687 Stmt *BodyStmt) {
688 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000689 assert(SS == getCurFunction()->SwitchStack.back() &&
690 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000691
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000692 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000693 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000694 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000695
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000696 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000697 if (!CondExpr) return StmtError();
698
699 QualType CondType = CondExpr->getType();
700
John McCalld3dfbd62010-05-18 03:19:21 +0000701 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000702 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000703 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000704
Chris Lattnera96d4272009-10-16 16:45:22 +0000705 // C++ 6.4.2.p2:
706 // Integral promotions are performed (on the switch condition).
707 //
708 // A case value unrepresentable by the original switch condition
709 // type (before the promotion) doesn't make sense, even when it can
710 // be represented by the promoted type. Therefore we need to find
711 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000712 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000713 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000715 // appropriate type now, just return an error.
716 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000717 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000718
Chris Lattner4ebae652010-04-16 23:34:13 +0000719 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000720 // switch(bool_expr) {...} is often a programmer error, e.g.
721 // switch(n && mask) { ... } // Doh - should be "n & mask".
722 // One can always use an if statement instead of switch(bool_expr).
723 Diag(SwitchLoc, diag::warn_bool_switch_condition)
724 << CondExpr->getSourceRange();
725 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000726 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000727
Richard Smith077d0832014-08-04 00:40:48 +0000728 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000729 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000730 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000731 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000732 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
733 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
734
735 // Get the width and signedness that the condition might actually have, for
736 // warning purposes.
737 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
738 // type.
739 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000740 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000741 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000742 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000744 // Accumulate all of the case values in a vector so that we can sort them
745 // and detect duplicates. This vector contains the APInt for the case after
746 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000747 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000748 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000750 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000751 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
752 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Craig Topperc3ec1492014-05-26 06:22:03 +0000754 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner10cb5e52007-08-23 06:23:56 +0000756 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000757
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000758 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000759 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000760
Anders Carlsson51873c22007-07-22 07:07:56 +0000761 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000762 if (TheDefaultStmt) {
763 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000764 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000765
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000766 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000767 // we'll return a valid AST. This requires recursing down the AST and
768 // finding it, not something we are set up to do right now. For now,
769 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000770 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000771 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000772 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000773
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000774 } else {
775 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000776
Chris Lattnera65e1f32008-01-16 19:17:22 +0000777 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000778
779 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
780 HasDependentValue = true;
781 break;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Richard Smithf8379a02012-01-18 23:55:52 +0000784 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000786 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000787 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
788 // constant expression of the promoted type of the switch condition.
789 ExprResult ConvLo =
790 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
791 if (ConvLo.isInvalid()) {
792 CaseListIsErroneous = true;
793 continue;
794 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000795 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000796 } else {
797 // We already verified that the expression has a i-c-e value (C99
798 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000799 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000800
801 // If the LHS is not the same type as the condition, insert an implicit
802 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000803 Lo = DefaultLvalueConversion(Lo).get();
804 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000805 }
806
Richard Smith077d0832014-08-04 00:40:48 +0000807 // Check the unconverted value is within the range of possible values of
808 // the switch expression.
809 checkCaseValue(*this, Lo->getLocStart(), LoVal,
810 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
811
812 // Convert the value to the same width/sign as the condition.
813 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000814
Chris Lattnera65e1f32008-01-16 19:17:22 +0000815 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattner10cb5e52007-08-23 06:23:56 +0000817 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000818 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000819 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000820 CS->getRHS()->isValueDependent()) {
821 HasDependentValue = true;
822 break;
823 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000824 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000825 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000826 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000827 }
828 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000829
830 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000831 // If we don't have a default statement, check whether the
832 // condition is constant.
833 llvm::APSInt ConstantCondValue;
834 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000835 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000836 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
837 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000838 assert(!HasConstantCond ||
839 (ConstantCondValue.getBitWidth() == CondWidth &&
840 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000841 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000842 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000843
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000844 // Sort all the scalar case values so we can easily detect duplicates.
845 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
846
847 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000848 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
849 if (ShouldCheckConstantCond &&
850 CaseVals[i].first == ConstantCondValue)
851 ShouldCheckConstantCond = false;
852
853 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000854 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000855 // First, determine if either case value has a name
856 StringRef PrevString, CurrString;
857 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
858 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
859 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
860 PrevString = DeclRef->getDecl()->getName();
861 }
862 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
863 CurrString = DeclRef->getDecl()->getName();
864 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000865 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000866 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000867
868 if (PrevString == CurrString)
869 Diag(CaseVals[i].second->getLHS()->getLocStart(),
870 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000871 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000872 else
873 Diag(CaseVals[i].second->getLHS()->getLocStart(),
874 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000875 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
876 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000877 CaseValStr;
878
John McCalld3dfbd62010-05-18 03:19:21 +0000879 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000880 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000881 // FIXME: We really want to remove the bogus case stmt from the
882 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000883 CaseListIsErroneous = true;
884 }
885 }
886 }
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000888 // Detect duplicate case ranges, which usually don't exist at all in
889 // the first place.
890 if (!CaseRanges.empty()) {
891 // Sort all the case ranges by their low value so we can easily detect
892 // overlaps between ranges.
893 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000894
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000895 // Scan the ranges, computing the high values and removing empty ranges.
896 std::vector<llvm::APSInt> HiVals;
897 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000898 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000899 CaseStmt *CR = CaseRanges[i].second;
900 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000901 llvm::APSInt HiVal;
902
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000903 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000904 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
905 // constant expression of the promoted type of the switch condition.
906 ExprResult ConvHi =
907 CheckConvertedConstantExpression(Hi, CondType, HiVal,
908 CCEK_CaseValue);
909 if (ConvHi.isInvalid()) {
910 CaseListIsErroneous = true;
911 continue;
912 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000913 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000914 } else {
915 HiVal = Hi->EvaluateKnownConstInt(Context);
916
917 // If the RHS is not the same type as the condition, insert an
918 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000919 Hi = DefaultLvalueConversion(Hi).get();
920 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Richard Smith077d0832014-08-04 00:40:48 +0000923 // Check the unconverted value is within the range of possible values of
924 // the switch expression.
925 checkCaseValue(*this, Hi->getLocStart(), HiVal,
926 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
927
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000928 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000929 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000930
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000931 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000933 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000934 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000935 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
936 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000937 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000938 CaseRanges.erase(CaseRanges.begin()+i);
939 --i, --e;
940 continue;
941 }
John McCalld3dfbd62010-05-18 03:19:21 +0000942
943 if (ShouldCheckConstantCond &&
944 LoVal <= ConstantCondValue &&
945 ConstantCondValue <= HiVal)
946 ShouldCheckConstantCond = false;
947
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000948 HiVals.push_back(HiVal);
949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000951 // Rescan the ranges, looking for overlap with singleton values and other
952 // ranges. Since the range list is sorted, we only need to compare case
953 // ranges with their neighbors.
954 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
955 llvm::APSInt &CRLo = CaseRanges[i].first;
956 llvm::APSInt &CRHi = HiVals[i];
957 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000958
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000959 // Check to see whether the case range overlaps with any
960 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000961 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000962 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000963
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000964 // Find the smallest value >= the lower bound. If I is in the
965 // case range, then we have overlap.
966 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
967 CaseVals.end(), CRLo,
968 CaseCompareFunctor());
969 if (I != CaseVals.end() && I->first < CRHi) {
970 OverlapVal = I->first; // Found overlap with scalar.
971 OverlapStmt = I->second;
972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000974 // Find the smallest value bigger than the upper bound.
975 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
976 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
977 OverlapVal = (I-1)->first; // Found overlap with scalar.
978 OverlapStmt = (I-1)->second;
979 }
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000981 // Check to see if this case stmt overlaps with the subsequent
982 // case range.
983 if (i && CRLo <= HiVals[i-1]) {
984 OverlapVal = HiVals[i-1]; // Found overlap with range.
985 OverlapStmt = CaseRanges[i-1].second;
986 }
Mike Stump11289f42009-09-09 15:08:12 +0000987
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000988 if (OverlapStmt) {
989 // If we have a duplicate, report it.
990 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
991 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000992 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000993 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000994 // FIXME: We really want to remove the bogus case stmt from the
995 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000996 CaseListIsErroneous = true;
997 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000998 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000999 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001000
John McCalld3dfbd62010-05-18 03:19:21 +00001001 // Complain if we have a constant condition and we didn't find a match.
1002 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1003 // TODO: it would be nice if we printed enums as enums, chars as
1004 // chars, etc.
1005 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1006 << ConstantCondValue.toString(10)
1007 << CondExpr->getSourceRange();
1008 }
1009
1010 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001011 // values. We only issue a warning if there is not 'default:', but
1012 // we still do the analysis to preserve this information in the AST
1013 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001014 //
Chris Lattner51679082010-09-16 17:09:42 +00001015 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001016
Douglas Gregorbd6839732010-02-08 22:24:16 +00001017 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001018 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001019 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001020 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +00001021 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001022 EnumValsTy EnumVals;
1023
John McCalld3dfbd62010-05-18 03:19:21 +00001024 // Gather all enum values, set their type and sort them,
1025 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001026 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001027 llvm::APSInt Val = EDI->getInitVal();
1028 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001029 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001030 }
1031 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +00001032 EnumValsTy::iterator EIend =
1033 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001034
1035 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001036 EnumValsTy::const_iterator EI = EnumVals.begin();
1037 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1038 CI != CaseVals.end(); CI++) {
1039 while (EI != EIend && EI->first < CI->first)
1040 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001041 if (EI == EIend || EI->first > CI->first) {
1042 Expr *CaseExpr = CI->second->getLHS();
1043 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1044 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1045 << CondTypeBeforePromotion;
1046 }
David Blaikiee476f972012-01-22 02:31:55 +00001047 }
1048 // See which of case ranges aren't in enum
1049 EI = EnumVals.begin();
1050 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1051 RI != CaseRanges.end() && EI != EIend; RI++) {
1052 while (EI != EIend && EI->first < RI->first)
1053 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054
David Blaikiee476f972012-01-22 02:31:55 +00001055 if (EI == EIend || EI->first != RI->first) {
Dmitri Gribenko58683752013-12-05 22:52:07 +00001056 Expr *CaseExpr = RI->second->getLHS();
1057 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1058 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1059 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +00001060 }
David Blaikiee476f972012-01-22 02:31:55 +00001061
Chad Rosier02a84392012-08-10 17:56:09 +00001062 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001063 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1064 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1065 while (EI != EIend && EI->first < Hi)
1066 EI++;
Dmitri Gribenko58683752013-12-05 22:52:07 +00001067 if (EI == EIend || EI->first != Hi) {
1068 Expr *CaseExpr = RI->second->getRHS();
1069 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1070 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1071 << CondTypeBeforePromotion;
1072 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001074
Ted Kremenekc42f3452010-09-09 00:05:53 +00001075 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001076 CaseValsTy::const_iterator CI = CaseVals.begin();
1077 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001078 bool hasCasesNotInSwitch = false;
1079
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001080 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001081
David Blaikiee476f972012-01-22 02:31:55 +00001082 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001083 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001084 while (CI != CaseVals.end() && CI->first < EI->first)
1085 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
Douglas Gregorbd6839732010-02-08 22:24:16 +00001087 if (CI != CaseVals.end() && CI->first == EI->first)
1088 continue;
1089
Ted Kremenekc42f3452010-09-09 00:05:53 +00001090 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001091 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001092 llvm::APSInt Hi =
1093 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001094 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001095 if (EI->first <= Hi)
1096 break;
1097 }
1098
Ted Kremenekc42f3452010-09-09 00:05:53 +00001099 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001100 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001101 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001102 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
David Blaikie60ac6382012-01-23 04:46:12 +00001105 if (TheDefaultStmt && UnhandledNames.empty())
1106 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001107
Chris Lattner51679082010-09-16 17:09:42 +00001108 // Produce a nice diagnostic if multiple values aren't handled.
1109 switch (UnhandledNames.size()) {
1110 case 0: break;
1111 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001112 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001113 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001114 << UnhandledNames[0];
1115 break;
1116 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001117 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001118 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001119 << UnhandledNames[0] << UnhandledNames[1];
1120 break;
1121 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001122 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1123 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001124 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1125 break;
1126 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001127 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1128 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001129 << (unsigned)UnhandledNames.size()
1130 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1131 break;
1132 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001133
1134 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001135 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001136 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001137 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001138
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001139 if (BodyStmt)
1140 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1141 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001142
Mike Stump87c57ac2009-05-16 07:39:55 +00001143 // FIXME: If the case list was broken is some way, we don't have a good system
1144 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001145 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001146 return StmtError();
1147
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001148 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001149}
1150
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001151void
1152Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1153 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001154 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001155 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001156
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001157 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001158 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001159 SrcType->isIntegerType()) {
1160 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1161 SrcExpr->isIntegerConstantExpr(Context)) {
1162 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001163 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001164 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1165
1166 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001167 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001168 const EnumDecl *ED = ET->getDecl();
Joey Gouly1ba27332013-06-06 13:48:00 +00001169 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1170 EnumValsTy;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001171 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001172
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001173 // Gather all enum values, set their type and sort them,
1174 // allowing easier comparison with rhs constant.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001175 for (auto *EDI : ED->enumerators()) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001176 llvm::APSInt Val = EDI->getInitVal();
Joey Gouly1ba27332013-06-06 13:48:00 +00001177 AdjustAPSInt(Val, DstWidth, DstIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001178 EnumVals.push_back(std::make_pair(Val, EDI));
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001179 }
1180 if (EnumVals.empty())
1181 return;
1182 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1183 EnumValsTy::iterator EIend =
Joey Gouly1ba27332013-06-06 13:48:00 +00001184 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001185
Joey Gouly1ba27332013-06-06 13:48:00 +00001186 // See which values aren't in the enum.
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001187 EnumValsTy::const_iterator EI = EnumVals.begin();
1188 while (EI != EIend && EI->first < RhsVal)
1189 EI++;
1190 if (EI == EIend || EI->first != RhsVal) {
Joey Gouly1ba27332013-06-06 13:48:00 +00001191 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001192 << DstType.getUnqualifiedType();
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001193 }
1194 }
1195 }
1196}
1197
John McCalldadc5752010-08-24 06:29:42 +00001198StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001200 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001201 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202
Craig Topperc3ec1492014-05-26 06:22:03 +00001203 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001204 if (CondVar) {
1205 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001206 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001207 if (CondResult.isInvalid())
1208 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001209 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001210 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001211 if (!ConditionExpr)
1212 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001213 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214
John McCallb268a282010-08-23 23:25:46 +00001215 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001217 if (isa<NullStmt>(Body))
1218 getCurCompoundScope().setHasEmptyLoopBodies();
1219
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001220 return new (Context)
1221 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001222}
1223
John McCalldadc5752010-08-24 06:29:42 +00001224StmtResult
John McCallb268a282010-08-23 23:25:46 +00001225Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001226 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001227 Expr *Cond, SourceLocation CondRParen) {
1228 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001229
Serge Pavlov09f99242014-01-23 15:05:00 +00001230 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001231 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001232 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001233 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001234 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001235
Richard Smith945f8d32013-01-14 22:39:08 +00001236 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001237 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001238 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001239 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240
John McCallb268a282010-08-23 23:25:46 +00001241 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001242
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001243 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001244}
1245
Richard Trieu451a5db2012-04-30 18:01:30 +00001246namespace {
1247 // This visitor will traverse a conditional statement and store all
1248 // the evaluated decls into a vector. Simple is set to true if none
1249 // of the excluded constructs are used.
1250 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001251 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001252 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001253 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001254 public:
1255 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001256
Craig Topper4dd9b432014-08-17 23:49:53 +00001257 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001258 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001259 Inherited(S.Context),
1260 Decls(Decls),
1261 Ranges(Ranges),
1262 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001263
Richard Trieu9d228802013-05-31 22:46:45 +00001264 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001265
Richard Trieu9d228802013-05-31 22:46:45 +00001266 // Replaces the method in EvaluatedExprVisitor.
1267 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001268 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001269 }
1270
1271 // Any Stmt not whitelisted will cause the condition to be marked complex.
1272 void VisitStmt(Stmt *S) {
1273 Simple = false;
1274 }
1275
1276 void VisitBinaryOperator(BinaryOperator *E) {
1277 Visit(E->getLHS());
1278 Visit(E->getRHS());
1279 }
1280
1281 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001282 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001283 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001284
Richard Trieu9d228802013-05-31 22:46:45 +00001285 void VisitUnaryOperator(UnaryOperator *E) {
1286 // Skip checking conditionals with derefernces.
1287 if (E->getOpcode() == UO_Deref)
1288 Simple = false;
1289 else
1290 Visit(E->getSubExpr());
1291 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001292
Richard Trieu9d228802013-05-31 22:46:45 +00001293 void VisitConditionalOperator(ConditionalOperator *E) {
1294 Visit(E->getCond());
1295 Visit(E->getTrueExpr());
1296 Visit(E->getFalseExpr());
1297 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001298
Richard Trieu9d228802013-05-31 22:46:45 +00001299 void VisitParenExpr(ParenExpr *E) {
1300 Visit(E->getSubExpr());
1301 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001302
Richard Trieu9d228802013-05-31 22:46:45 +00001303 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1304 Visit(E->getOpaqueValue()->getSourceExpr());
1305 Visit(E->getFalseExpr());
1306 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001307
Richard Trieu9d228802013-05-31 22:46:45 +00001308 void VisitIntegerLiteral(IntegerLiteral *E) { }
1309 void VisitFloatingLiteral(FloatingLiteral *E) { }
1310 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1311 void VisitCharacterLiteral(CharacterLiteral *E) { }
1312 void VisitGNUNullExpr(GNUNullExpr *E) { }
1313 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001314
Richard Trieu9d228802013-05-31 22:46:45 +00001315 void VisitDeclRefExpr(DeclRefExpr *E) {
1316 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1317 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001318
Richard Trieu9d228802013-05-31 22:46:45 +00001319 Ranges.push_back(E->getSourceRange());
1320
1321 Decls.insert(VD);
1322 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001323
1324 }; // end class DeclExtractor
1325
1326 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001327 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001328 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001329 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001330 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001331
Richard Trieu9d228802013-05-31 22:46:45 +00001332 public:
1333 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001334
Craig Topper4dd9b432014-08-17 23:49:53 +00001335 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001336 Stmt *Statement) :
1337 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1338 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001339
Richard Trieu9d228802013-05-31 22:46:45 +00001340 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001341 }
1342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 void VisitReturnStmt(ReturnStmt *S) {
1344 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001345 }
1346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 void VisitBreakStmt(BreakStmt *S) {
1348 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001349 }
1350
Richard Trieu9d228802013-05-31 22:46:45 +00001351 void VisitGotoStmt(GotoStmt *S) {
1352 FoundDecl = true;
1353 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001354
Richard Trieu9d228802013-05-31 22:46:45 +00001355 void VisitCastExpr(CastExpr *E) {
1356 if (E->getCastKind() == CK_LValueToRValue)
1357 CheckLValueToRValueCast(E->getSubExpr());
1358 else
1359 Visit(E->getSubExpr());
1360 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001361
Richard Trieu9d228802013-05-31 22:46:45 +00001362 void CheckLValueToRValueCast(Expr *E) {
1363 E = E->IgnoreParenImpCasts();
1364
1365 if (isa<DeclRefExpr>(E)) {
1366 return;
1367 }
1368
1369 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1370 Visit(CO->getCond());
1371 CheckLValueToRValueCast(CO->getTrueExpr());
1372 CheckLValueToRValueCast(CO->getFalseExpr());
1373 return;
1374 }
1375
1376 if (BinaryConditionalOperator *BCO =
1377 dyn_cast<BinaryConditionalOperator>(E)) {
1378 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1379 CheckLValueToRValueCast(BCO->getFalseExpr());
1380 return;
1381 }
1382
1383 Visit(E);
1384 }
1385
1386 void VisitDeclRefExpr(DeclRefExpr *E) {
1387 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1388 if (Decls.count(VD))
1389 FoundDecl = true;
1390 }
1391
1392 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001393
1394 }; // end class DeclMatcher
1395
1396 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1397 Expr *Third, Stmt *Body) {
1398 // Condition is empty
1399 if (!Second) return;
1400
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001401 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1402 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001403 return;
1404
1405 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1406 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001407 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001408 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001409 DE.Visit(Second);
1410
1411 // Don't analyze complex conditionals.
1412 if (!DE.isSimple()) return;
1413
1414 // No decls found.
1415 if (Decls.size() == 0) return;
1416
Richard Trieu0030f1d2012-05-04 03:01:54 +00001417 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001418 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1419 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001420 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001421 if ((*I)->getType().isVolatileQualified() ||
1422 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001423
1424 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1425 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1426 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1427 return;
1428
1429 // Load decl names into diagnostic.
1430 if (Decls.size() > 4)
1431 PDiag << 0;
1432 else {
1433 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001434 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1435 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001436 I != E; ++I)
1437 PDiag << (*I)->getDeclName();
1438 }
1439
1440 // Load SourceRanges into diagnostic if there is room.
1441 // Otherwise, load the SourceRange of the conditional expression.
1442 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001443 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001444 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001445 I != E; ++I)
1446 PDiag << *I;
1447 else
1448 PDiag << Second->getSourceRange();
1449
1450 S.Diag(Ranges.begin()->getBegin(), PDiag);
1451 }
1452
Richard Trieu4e7c9622013-08-06 21:31:54 +00001453 // If Statement is an incemement or decrement, return true and sets the
1454 // variables Increment and DRE.
1455 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1456 DeclRefExpr *&DRE) {
1457 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1458 switch (UO->getOpcode()) {
1459 default: return false;
1460 case UO_PostInc:
1461 case UO_PreInc:
1462 Increment = true;
1463 break;
1464 case UO_PostDec:
1465 case UO_PreDec:
1466 Increment = false;
1467 break;
1468 }
1469 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1470 return DRE;
1471 }
1472
1473 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1474 FunctionDecl *FD = Call->getDirectCallee();
1475 if (!FD || !FD->isOverloadedOperator()) return false;
1476 switch (FD->getOverloadedOperator()) {
1477 default: return false;
1478 case OO_PlusPlus:
1479 Increment = true;
1480 break;
1481 case OO_MinusMinus:
1482 Increment = false;
1483 break;
1484 }
1485 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1486 return DRE;
1487 }
1488
1489 return false;
1490 }
1491
Serge Pavlov09f99242014-01-23 15:05:00 +00001492 // A visitor to determine if a continue or break statement is a
1493 // subexpression.
1494 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1495 SourceLocation BreakLoc;
1496 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001497 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001498 BreakContinueFinder(Sema &S, Stmt* Body) :
1499 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001500 Visit(Body);
1501 }
1502
Serge Pavlov09f99242014-01-23 15:05:00 +00001503 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001504
1505 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001506 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001507 }
1508
Serge Pavlov09f99242014-01-23 15:05:00 +00001509 void VisitBreakStmt(BreakStmt* E) {
1510 BreakLoc = E->getBreakLoc();
1511 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001512
Serge Pavlov09f99242014-01-23 15:05:00 +00001513 bool ContinueFound() { return ContinueLoc.isValid(); }
1514 bool BreakFound() { return BreakLoc.isValid(); }
1515 SourceLocation GetContinueLoc() { return ContinueLoc; }
1516 SourceLocation GetBreakLoc() { return BreakLoc; }
1517
1518 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001519
1520 // Emit a warning when a loop increment/decrement appears twice per loop
1521 // iteration. The conditions which trigger this warning are:
1522 // 1) The last statement in the loop body and the third expression in the
1523 // for loop are both increment or both decrement of the same variable
1524 // 2) No continue statements in the loop body.
1525 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1526 // Return when there is nothing to check.
1527 if (!Body || !Third) return;
1528
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001529 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1530 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001531 return;
1532
1533 // Get the last statement from the loop body.
1534 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1535 if (!CS || CS->body_empty()) return;
1536 Stmt *LastStmt = CS->body_back();
1537 if (!LastStmt) return;
1538
1539 bool LoopIncrement, LastIncrement;
1540 DeclRefExpr *LoopDRE, *LastDRE;
1541
1542 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1543 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1544
1545 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001546 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001547 if (LoopIncrement != LastIncrement ||
1548 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1549
Serge Pavlov09f99242014-01-23 15:05:00 +00001550 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001551
1552 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1553 << LastDRE->getDecl() << LastIncrement;
1554 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1555 << LoopIncrement;
1556 }
1557
Richard Trieu451a5db2012-04-30 18:01:30 +00001558} // end namespace
1559
Serge Pavlov09f99242014-01-23 15:05:00 +00001560
1561void Sema::CheckBreakContinueBinding(Expr *E) {
1562 if (!E || getLangOpts().CPlusPlus)
1563 return;
1564 BreakContinueFinder BCFinder(*this, E);
1565 Scope *BreakParent = CurScope->getBreakParent();
1566 if (BCFinder.BreakFound() && BreakParent) {
1567 if (BreakParent->getFlags() & Scope::SwitchScope) {
1568 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1569 } else {
1570 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1571 << "break";
1572 }
1573 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1574 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1575 << "continue";
1576 }
1577}
1578
John McCalldadc5752010-08-24 06:29:42 +00001579StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001580Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001581 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001582 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001583 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001584 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001585 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001586 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1587 // declare identifiers for objects having storage class 'auto' or
1588 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001589 for (auto *DI : DS->decls()) {
1590 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001591 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001592 VD = nullptr;
1593 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001594 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1595 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001596 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001597 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001598 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001599 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001600
Serge Pavlov09f99242014-01-23 15:05:00 +00001601 CheckBreakContinueBinding(second.get());
1602 CheckBreakContinueBinding(third.get());
1603
Richard Trieu451a5db2012-04-30 18:01:30 +00001604 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001605 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001606
John McCalldadc5752010-08-24 06:29:42 +00001607 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001608 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001609 if (secondVar) {
1610 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001611 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001612 if (SecondResult.isInvalid())
1613 return StmtError();
1614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001616 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001617
Anders Carlsson1682af52009-08-01 01:39:59 +00001618 DiagnoseUnusedExprResult(First);
1619 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001620 DiagnoseUnusedExprResult(Body);
1621
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001622 if (isa<NullStmt>(Body))
1623 getCurCompoundScope().setHasEmptyLoopBodies();
1624
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001625 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1626 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001627}
1628
John McCall34376a62010-12-04 03:47:34 +00001629/// In an Objective C collection iteration statement:
1630/// for (x in y)
1631/// x can be an arbitrary l-value expression. Bind it up as a
1632/// full-expression.
1633StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001634 // Reduce placeholder expressions here. Note that this rejects the
1635 // use of pseudo-object l-values in this position.
1636 ExprResult result = CheckPlaceholderExpr(E);
1637 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001638 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001639
Richard Smith945f8d32013-01-14 22:39:08 +00001640 ExprResult FullExpr = ActOnFinishFullExpr(E);
1641 if (FullExpr.isInvalid())
1642 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001643 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001644}
1645
John McCall53848232011-07-27 01:07:15 +00001646ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001647Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1648 if (!collection)
1649 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001650
John McCall53848232011-07-27 01:07:15 +00001651 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001652 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001653
1654 // Perform normal l-value conversion.
1655 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1656 if (result.isInvalid())
1657 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001658 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001659
1660 // The operand needs to have object-pointer type.
1661 // TODO: should we do a contextual conversion?
1662 const ObjCObjectPointerType *pointerType =
1663 collection->getType()->getAs<ObjCObjectPointerType>();
1664 if (!pointerType)
1665 return Diag(forLoc, diag::err_collection_expr_type)
1666 << collection->getType() << collection->getSourceRange();
1667
1668 // Check that the operand provides
1669 // - countByEnumeratingWithState:objects:count:
1670 const ObjCObjectType *objectType = pointerType->getObjectType();
1671 ObjCInterfaceDecl *iface = objectType->getInterface();
1672
1673 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001674 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001675 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001676 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001677 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001678 ? diag::err_arc_collection_forward
1679 : 0,
1680 collection)) {
John McCall53848232011-07-27 01:07:15 +00001681 // Otherwise, if we have any useful type information, check that
1682 // the type declares the appropriate method.
1683 } else if (iface || !objectType->qual_empty()) {
1684 IdentifierInfo *selectorIdents[] = {
1685 &Context.Idents.get("countByEnumeratingWithState"),
1686 &Context.Idents.get("objects"),
1687 &Context.Idents.get("count")
1688 };
1689 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1690
Craig Topperc3ec1492014-05-26 06:22:03 +00001691 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001692
1693 // If there's an interface, look in both the public and private APIs.
1694 if (iface) {
1695 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001696 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001697 }
1698
1699 // Also check protocol qualifiers.
1700 if (!method)
1701 method = LookupMethodInQualifiedType(selector, pointerType,
1702 /*instance*/ true);
1703
1704 // If we didn't find it anywhere, give up.
1705 if (!method) {
1706 Diag(forLoc, diag::warn_collection_expr_type)
1707 << collection->getType() << selector << collection->getSourceRange();
1708 }
1709
1710 // TODO: check for an incompatible signature?
1711 }
1712
1713 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001714 return collection;
John McCall53848232011-07-27 01:07:15 +00001715}
1716
John McCalldadc5752010-08-24 06:29:42 +00001717StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001718Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001719 Stmt *First, Expr *collection,
1720 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001721
1722 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001723 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001724
Fariborz Jahanian93977672008-01-10 20:33:58 +00001725 if (First) {
1726 QualType FirstType;
1727 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001728 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001729 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1730 diag::err_toomany_element_decls));
1731
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001732 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1733 if (!D || D->isInvalidDecl())
1734 return StmtError();
1735
John McCall31168b02011-06-15 23:02:42 +00001736 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001737 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1738 // declare identifiers for objects having storage class 'auto' or
1739 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001740 if (!D->hasLocalStorage())
1741 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001742 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001743
1744 // If the type contained 'auto', deduce the 'auto' to 'id'.
1745 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001746 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1747 VK_RValue);
1748 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001749 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1750 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001751 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001752 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001753 D->setInvalidDecl();
1754 return StmtError();
1755 }
1756
Richard Smith061f1e22013-04-30 21:23:01 +00001757 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001758
1759 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001760 SourceLocation Loc =
1761 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001762 Diag(Loc, diag::warn_auto_var_is_id)
1763 << D->getDeclName();
1764 }
1765 }
1766
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001767 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001768 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001769 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001770 return StmtError(Diag(First->getLocStart(),
1771 diag::err_selector_element_not_lvalue)
1772 << First->getSourceRange());
1773
Mike Stump11289f42009-09-09 15:08:12 +00001774 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001775 if (FirstType.isConstQualified())
1776 Diag(ForLoc, diag::err_selector_element_const_type)
1777 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001778 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001779 if (!FirstType->isDependentType() &&
1780 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001781 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001782 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1783 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001784 }
Chad Rosier02a84392012-08-10 17:56:09 +00001785
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001786 if (CollectionExprResult.isInvalid())
1787 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001788
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001789 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001790 if (CollectionExprResult.isInvalid())
1791 return StmtError();
1792
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001793 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1794 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001795}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001796
Richard Smith02e85f32011-04-14 22:09:26 +00001797/// Finish building a variable declaration for a for-range statement.
1798/// \return true if an error occurs.
1799static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001800 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001801 // Deduce the type for the iterator variable now rather than leaving it to
1802 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001803 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001804 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001805 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001806 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001807 SemaRef.Diag(Loc, DiagID) << Init->getType();
1808 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001809 Decl->setInvalidDecl();
1810 return true;
1811 }
Richard Smith061f1e22013-04-30 21:23:01 +00001812 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001813
John McCall31168b02011-06-15 23:02:42 +00001814 // In ARC, infer lifetime.
1815 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1816 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001817 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001818 SemaRef.inferObjCARCLifetime(Decl))
1819 Decl->setInvalidDecl();
1820
Richard Smith02e85f32011-04-14 22:09:26 +00001821 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1822 /*TypeMayContainAuto=*/false);
1823 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001824 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001825 return false;
1826}
1827
Sam Panzer0f384432012-08-21 00:52:01 +00001828namespace {
1829
Richard Smith02e85f32011-04-14 22:09:26 +00001830/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001831/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001832/// nor from the diagnostics produced when analysing the implicit expressions
1833/// required in a for-range statement.
1834void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001835 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001836 CallExpr *CE = dyn_cast<CallExpr>(E);
1837 if (!CE)
1838 return;
1839 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1840 if (!D)
1841 return;
1842 SourceLocation Loc = D->getLocation();
1843
1844 std::string Description;
1845 bool IsTemplate = false;
1846 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1847 Description = SemaRef.getTemplateArgumentBindingsText(
1848 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1849 IsTemplate = true;
1850 }
1851
1852 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1853 << BEF << IsTemplate << Description << E->getType();
1854}
1855
Sam Panzer0f384432012-08-21 00:52:01 +00001856/// Build a variable declaration for a for-range statement.
1857VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1858 QualType Type, const char *Name) {
1859 DeclContext *DC = SemaRef.CurContext;
1860 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1861 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1862 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001863 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001864 Decl->setImplicit();
1865 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001866}
1867
1868}
1869
Fariborz Jahanian00213472012-07-06 19:04:04 +00001870static bool ObjCEnumerationCollection(Expr *Collection) {
1871 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001873}
1874
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001875/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001876///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001877/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001878/// A range-based for statement is equivalent to
1879///
1880/// {
1881/// auto && __range = range-init;
1882/// for ( auto __begin = begin-expr,
1883/// __end = end-expr;
1884/// __begin != __end;
1885/// ++__begin ) {
1886/// for-range-declaration = *__begin;
1887/// statement
1888/// }
1889/// }
1890///
1891/// The body of the loop is not available yet, since it cannot be analysed until
1892/// we have determined the type of the for-range-declaration.
1893StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001894Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001895 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001896 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001897 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001898 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001899
Richard Smith3249fed2013-08-21 01:40:36 +00001900 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001901 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001902
1903 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1904 assert(DS && "first part of for range not a decl stmt");
1905
1906 if (!DS->isSingleDecl()) {
1907 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1908 return StmtError();
1909 }
Richard Smith02e85f32011-04-14 22:09:26 +00001910
Richard Smith3249fed2013-08-21 01:40:36 +00001911 Decl *LoopVar = DS->getSingleDecl();
1912 if (LoopVar->isInvalidDecl() || !Range ||
1913 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1914 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001915 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001916 }
Richard Smith02e85f32011-04-14 22:09:26 +00001917
1918 // Build auto && __range = range-init
1919 SourceLocation RangeLoc = Range->getLocStart();
1920 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1921 Context.getAutoRRefDeductType(),
1922 "__range");
1923 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001924 diag::err_for_range_deduction_failure)) {
1925 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001926 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001927 }
Richard Smith02e85f32011-04-14 22:09:26 +00001928
1929 // Claim the type doesn't contain auto: we've already done the checking.
1930 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001931 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001932 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001933 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001934 if (RangeDecl.isInvalid()) {
1935 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001936 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001937 }
Richard Smith02e85f32011-04-14 22:09:26 +00001938
1939 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001940 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1941 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001942}
1943
1944/// \brief Create the initialization, compare, and increment steps for
1945/// the range-based for loop expression.
1946/// This function does not handle array-based for loops,
1947/// which are created in Sema::BuildCXXForRangeStmt.
1948///
1949/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1950/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1951/// CandidateSet and BEF are set and some non-success value is returned on
1952/// failure.
1953static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1954 Expr *BeginRange, Expr *EndRange,
1955 QualType RangeType,
1956 VarDecl *BeginVar,
1957 VarDecl *EndVar,
1958 SourceLocation ColonLoc,
1959 OverloadCandidateSet *CandidateSet,
1960 ExprResult *BeginExpr,
1961 ExprResult *EndExpr,
1962 Sema::BeginEndFunction *BEF) {
1963 DeclarationNameInfo BeginNameInfo(
1964 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1965 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1966 ColonLoc);
1967
1968 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1969 Sema::LookupMemberName);
1970 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1971
1972 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1973 // - if _RangeT is a class type, the unqualified-ids begin and end are
1974 // looked up in the scope of class _RangeT as if by class member access
1975 // lookup (3.4.5), and if either (or both) finds at least one
1976 // declaration, begin-expr and end-expr are __range.begin() and
1977 // __range.end(), respectively;
1978 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1979 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1980
1981 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1982 SourceLocation RangeLoc = BeginVar->getLocation();
1983 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1984
1985 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1986 << RangeLoc << BeginRange->getType() << *BEF;
1987 return Sema::FRS_DiagnosticIssued;
1988 }
1989 } else {
1990 // - otherwise, begin-expr and end-expr are begin(__range) and
1991 // end(__range), respectively, where begin and end are looked up with
1992 // argument-dependent lookup (3.4.2). For the purposes of this name
1993 // lookup, namespace std is an associated namespace.
1994
1995 }
1996
1997 *BEF = Sema::BEF_begin;
1998 Sema::ForRangeStatus RangeStatus =
1999 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2000 Sema::BEF_begin, BeginNameInfo,
2001 BeginMemberLookup, CandidateSet,
2002 BeginRange, BeginExpr);
2003
2004 if (RangeStatus != Sema::FRS_Success)
2005 return RangeStatus;
2006 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2007 diag::err_for_range_iter_deduction_failure)) {
2008 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2009 return Sema::FRS_DiagnosticIssued;
2010 }
2011
2012 *BEF = Sema::BEF_end;
2013 RangeStatus =
2014 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2015 Sema::BEF_end, EndNameInfo,
2016 EndMemberLookup, CandidateSet,
2017 EndRange, EndExpr);
2018 if (RangeStatus != Sema::FRS_Success)
2019 return RangeStatus;
2020 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2021 diag::err_for_range_iter_deduction_failure)) {
2022 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2023 return Sema::FRS_DiagnosticIssued;
2024 }
2025 return Sema::FRS_Success;
2026}
2027
2028/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002029/// If the attempt fails, this function will return a valid, null StmtResult
2030/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002031static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2032 SourceLocation ForLoc,
2033 Stmt *LoopVarDecl,
2034 SourceLocation ColonLoc,
2035 Expr *Range,
2036 SourceLocation RangeLoc,
2037 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002038 // Determine whether we can rebuild the for-range statement with a
2039 // dereferenced range expression.
2040 ExprResult AdjustedRange;
2041 {
2042 Sema::SFINAETrap Trap(SemaRef);
2043
2044 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2045 if (AdjustedRange.isInvalid())
2046 return StmtResult();
2047
2048 StmtResult SR =
2049 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2050 AdjustedRange.get(), RParenLoc,
2051 Sema::BFRK_Check);
2052 if (SR.isInvalid())
2053 return StmtResult();
2054 }
2055
2056 // The attempt to dereference worked well enough that it could produce a valid
2057 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2058 // case there are any other (non-fatal) problems with it.
2059 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2060 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2061 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2062 AdjustedRange.get(), RParenLoc,
2063 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002064}
2065
Richard Smith3249fed2013-08-21 01:40:36 +00002066namespace {
2067/// RAII object to automatically invalidate a declaration if an error occurs.
2068struct InvalidateOnErrorScope {
2069 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2070 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2071 ~InvalidateOnErrorScope() {
2072 if (Enabled && Trap.hasErrorOccurred())
2073 D->setInvalidDecl();
2074 }
2075
2076 DiagnosticErrorTrap Trap;
2077 Decl *D;
2078 bool Enabled;
2079};
2080}
2081
Richard Smitha05b3b52012-09-20 21:52:32 +00002082/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002083StmtResult
2084Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2085 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2086 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002087 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002088 Scope *S = getCurScope();
2089
2090 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2091 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2092 QualType RangeVarType = RangeVar->getType();
2093
2094 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2095 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2096
Richard Smith3249fed2013-08-21 01:40:36 +00002097 // If we hit any errors, mark the loop variable as invalid if its type
2098 // contains 'auto'.
2099 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2100 LoopVar->getType()->isUndeducedType());
2101
Richard Smith02e85f32011-04-14 22:09:26 +00002102 StmtResult BeginEndDecl = BeginEnd;
2103 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2104
Richard Smith27d807c2013-04-30 13:56:41 +00002105 if (RangeVarType->isDependentType()) {
2106 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002107 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002108
2109 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2110 // them in properly when we instantiate the loop.
2111 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2112 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2113 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002114 SourceLocation RangeLoc = RangeVar->getLocation();
2115
Ted Kremenekbed648e2011-10-10 22:36:28 +00002116 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2117
2118 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2119 VK_LValue, ColonLoc);
2120 if (BeginRangeRef.isInvalid())
2121 return StmtError();
2122
2123 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2124 VK_LValue, ColonLoc);
2125 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002126 return StmtError();
2127
2128 QualType AutoType = Context.getAutoDeductType();
2129 Expr *Range = RangeVar->getInit();
2130 if (!Range)
2131 return StmtError();
2132 QualType RangeType = Range->getType();
2133
2134 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002135 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002136 return StmtError();
2137
2138 // Build auto __begin = begin-expr, __end = end-expr.
2139 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2140 "__begin");
2141 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2142 "__end");
2143
2144 // Build begin-expr and end-expr and attach to __begin and __end variables.
2145 ExprResult BeginExpr, EndExpr;
2146 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2147 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2148 // __range + __bound, respectively, where __bound is the array bound. If
2149 // _RangeT is an array of unknown size or an array of incomplete type,
2150 // the program is ill-formed;
2151
2152 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002153 BeginExpr = BeginRangeRef;
2154 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002155 diag::err_for_range_iter_deduction_failure)) {
2156 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2157 return StmtError();
2158 }
2159
2160 // Find the array bound.
2161 ExprResult BoundExpr;
2162 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002163 BoundExpr = IntegerLiteral::Create(
2164 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002165 else if (const VariableArrayType *VAT =
2166 dyn_cast<VariableArrayType>(UnqAT))
2167 BoundExpr = VAT->getSizeExpr();
2168 else {
2169 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2170 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002171 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002172 }
2173
2174 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002175 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002176 BoundExpr.get());
2177 if (EndExpr.isInvalid())
2178 return StmtError();
2179 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2180 diag::err_for_range_iter_deduction_failure)) {
2181 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2182 return StmtError();
2183 }
2184 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002185 OverloadCandidateSet CandidateSet(RangeLoc,
2186 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002187 Sema::BeginEndFunction BEFFailure;
2188 ForRangeStatus RangeStatus =
2189 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2190 EndRangeRef.get(), RangeType,
2191 BeginVar, EndVar, ColonLoc, &CandidateSet,
2192 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002193
Richard Smitha05b3b52012-09-20 21:52:32 +00002194 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002195 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002196 // If the range is being built from an array parameter, emit a
2197 // a diagnostic that it is being treated as a pointer.
2198 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2199 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2200 QualType ArrayTy = PVD->getOriginalType();
2201 QualType PointerTy = PVD->getType();
2202 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2203 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2204 << RangeLoc << PVD << ArrayTy << PointerTy;
2205 Diag(PVD->getLocation(), diag::note_declared_at);
2206 return StmtError();
2207 }
2208 }
2209 }
2210
2211 // If building the range failed, try dereferencing the range expression
2212 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002213 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2214 LoopVarDecl, ColonLoc,
2215 Range, RangeLoc,
2216 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002217 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002218 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002219 }
2220
Sam Panzer0f384432012-08-21 00:52:01 +00002221 // Otherwise, emit diagnostics if we haven't already.
2222 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002223 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002224 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2225 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002226 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002227 }
2228 // Return an error if no fix was discovered.
2229 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002230 return StmtError();
2231 }
2232
Sam Panzer0f384432012-08-21 00:52:01 +00002233 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2234 "invalid range expression in for loop");
2235
2236 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002237 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2238 if (!Context.hasSameType(BeginType, EndType)) {
2239 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2240 << BeginType << EndType;
2241 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2242 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2243 }
2244
2245 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2246 // Claim the type doesn't contain auto: we've already done the checking.
2247 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002248 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002249 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002250 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2251
Ted Kremenekbed648e2011-10-10 22:36:28 +00002252 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2253 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002254 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002255 if (BeginRef.isInvalid())
2256 return StmtError();
2257
Richard Smith02e85f32011-04-14 22:09:26 +00002258 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2259 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002260 if (EndRef.isInvalid())
2261 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002262
2263 // Build and check __begin != __end expression.
2264 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2265 BeginRef.get(), EndRef.get());
2266 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2267 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2268 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002269 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2270 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002271 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2272 if (!Context.hasSameType(BeginType, EndType))
2273 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2274 return StmtError();
2275 }
2276
2277 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002278 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2279 VK_LValue, ColonLoc);
2280 if (BeginRef.isInvalid())
2281 return StmtError();
2282
Richard Smith02e85f32011-04-14 22:09:26 +00002283 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2284 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2285 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002286 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2287 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002288 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2289 return StmtError();
2290 }
2291
2292 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002293 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2294 VK_LValue, ColonLoc);
2295 if (BeginRef.isInvalid())
2296 return StmtError();
2297
Richard Smith02e85f32011-04-14 22:09:26 +00002298 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2299 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002300 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2301 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002302 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2303 return StmtError();
2304 }
2305
Richard Smitha05b3b52012-09-20 21:52:32 +00002306 // Attach *__begin as initializer for VD. Don't touch it if we're just
2307 // trying to determine whether this would be a valid range.
2308 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002309 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2310 /*TypeMayContainAuto=*/true);
2311 if (LoopVar->isInvalidDecl())
2312 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2313 }
2314 }
2315
Richard Smitha05b3b52012-09-20 21:52:32 +00002316 // Don't bother to actually allocate the result if we're just trying to
2317 // determine whether it would be valid.
2318 if (Kind == BFRK_Check)
2319 return StmtResult();
2320
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002321 return new (Context) CXXForRangeStmt(
2322 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2323 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002324}
2325
Chad Rosier02a84392012-08-10 17:56:09 +00002326/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002327/// statement.
2328StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2329 if (!S || !B)
2330 return StmtError();
2331 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002332
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002333 ForStmt->setBody(B);
2334 return S;
2335}
2336
Richard Smith02e85f32011-04-14 22:09:26 +00002337/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2338/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2339/// body cannot be performed until after the type of the range variable is
2340/// determined.
2341StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2342 if (!S || !B)
2343 return StmtError();
2344
Fariborz Jahanian00213472012-07-06 19:04:04 +00002345 if (isa<ObjCForCollectionStmt>(S))
2346 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002347
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002348 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2349 ForStmt->setBody(B);
2350
2351 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2352 diag::warn_empty_range_based_for_body);
2353
Richard Smith02e85f32011-04-14 22:09:26 +00002354 return S;
2355}
2356
Chris Lattnercab02a62011-02-17 20:34:02 +00002357StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2358 SourceLocation LabelLoc,
2359 LabelDecl *TheDecl) {
2360 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002361 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002362 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002363}
Chris Lattner1c310502007-05-31 06:00:00 +00002364
John McCalldadc5752010-08-24 06:29:42 +00002365StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002366Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002367 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002368 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002369 if (!E->isTypeDependent()) {
2370 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002371 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002372 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002373 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002374 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2375 if (ExprRes.isInvalid())
2376 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002377 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002378 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002379 return StmtError();
2380 }
John McCalla95172b2010-08-01 00:26:45 +00002381
Richard Smith945f8d32013-01-14 22:39:08 +00002382 ExprResult ExprRes = ActOnFinishFullExpr(E);
2383 if (ExprRes.isInvalid())
2384 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002385 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002386
John McCallaab3e412010-08-25 08:40:02 +00002387 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002388
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002389 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002390}
2391
John McCalldadc5752010-08-24 06:29:42 +00002392StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002393Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002394 Scope *S = CurScope->getContinueParent();
2395 if (!S) {
2396 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002397 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002398 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002399
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002400 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002401}
2402
John McCalldadc5752010-08-24 06:29:42 +00002403StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002404Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002405 Scope *S = CurScope->getBreakParent();
2406 if (!S) {
2407 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002408 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002409 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002410 if (S->isOpenMPLoopScope())
2411 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2412 << "break");
Sebastian Redl573feed2009-01-18 13:19:59 +00002413
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002414 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002415}
2416
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002418/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002419///
Douglas Gregor5d369002011-01-21 18:05:27 +00002420/// \param ReturnType If we're determining the copy elision candidate for
2421/// a return statement, this is the return type of the function. If we're
2422/// determining the copy elision candidate for a throw expression, this will
2423/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002424///
Douglas Gregor5d369002011-01-21 18:05:27 +00002425/// \param E The expression being returned from the function or block, or
2426/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002427///
Douglas Gregor86394412011-05-20 15:00:53 +00002428/// \param AllowFunctionParameter Whether we allow function parameters to
2429/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2430/// we re-use this logic to determine whether we should try to move as part of
2431/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002432///
2433/// \returns The NRVO candidate variable, if the return statement may use the
2434/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002435VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2436 Expr *E,
2437 bool AllowFunctionParameter) {
2438 if (!getLangOpts().CPlusPlus)
2439 return nullptr;
2440
2441 // - in a return statement in a function [where] ...
2442 // ... the expression is the name of a non-volatile automatic object ...
2443 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2444 if (!DR || DR->refersToEnclosingLocal())
2445 return nullptr;
2446 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2447 if (!VD)
2448 return nullptr;
2449
2450 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2451 return VD;
2452 return nullptr;
2453}
2454
2455bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2456 bool AllowFunctionParameter) {
2457 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002458 // - in a return statement in a function with ...
2459 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002460 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002461 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002462 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002463 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002464 if (!VDType->isDependentType() &&
2465 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2466 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468
John McCall03318c12011-11-11 03:57:31 +00002469 // ...object (other than a function or catch-clause parameter)...
2470 if (VD->getKind() != Decl::Var &&
2471 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002472 return false;
2473 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002474
John McCall03318c12011-11-11 03:57:31 +00002475 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002476 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002477
2478 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002479 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002480
2481 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002482 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002483
2484 // Variables with higher required alignment than their type's ABI
2485 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002486 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002487 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002488 return false;
John McCall03318c12011-11-11 03:57:31 +00002489
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002490 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002491}
2492
Douglas Gregor626fbed2011-01-21 21:08:57 +00002493/// \brief Perform the initialization of a potentially-movable value, which
2494/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002495///
2496/// This routine implements C++0x [class.copy]p33, which attempts to treat
2497/// returned lvalues as rvalues in certain cases (to prefer move construction),
2498/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002500Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2501 const VarDecl *NRVOCandidate,
2502 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002503 Expr *Value,
2504 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002505 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506 // When the criteria for elision of a copy operation are met or would
2507 // be met save for the fact that the source object is a function
2508 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002509 // overload resolution to select the constructor for the copy is first
2510 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002511 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002512 if (AllowNRVO &&
2513 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002515 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516
Douglas Gregorf282a762011-01-21 19:38:21 +00002517 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002519 = InitializationKind::CreateCopy(Value->getLocStart(),
2520 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002521 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002522
2523 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002524 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002525 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002526 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002527 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002528 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2529 StepEnd = Seq.step_end();
2530 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002531 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002532 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
2534 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002535 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002536
Douglas Gregorf282a762011-01-21 19:38:21 +00002537 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002538 = Constructor->getParamDecl(0)->getType()
2539 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002540
Douglas Gregorf282a762011-01-21 19:38:21 +00002541 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002543 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2544 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002545 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002546
Douglas Gregorf282a762011-01-21 19:38:21 +00002547 // Promote "AsRvalue" to the heap, since we now need this
2548 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002549 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002550 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551
Douglas Gregorf282a762011-01-21 19:38:21 +00002552 // Complete type-checking the initialization of the return type
2553 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002554 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002555 }
2556 }
2557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002558
Douglas Gregorf282a762011-01-21 19:38:21 +00002559 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002561 // (again) now with the return value expression as written.
2562 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002563 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002564
Douglas Gregorf282a762011-01-21 19:38:21 +00002565 return Res;
2566}
2567
Richard Smith4db51c22013-09-25 05:02:54 +00002568/// \brief Determine whether the declared return type of the specified function
2569/// contains 'auto'.
2570static bool hasDeducedReturnType(FunctionDecl *FD) {
2571 const FunctionProtoType *FPT =
2572 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002573 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002574}
2575
Eli Friedman34b49062012-01-26 03:00:14 +00002576/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2577/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002578///
John McCalldadc5752010-08-24 06:29:42 +00002579StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002580Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2581 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002582 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002583 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002584 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002585 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002586
Richard Smith4db51c22013-09-25 05:02:54 +00002587 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2588 // In C++1y, the return type may involve 'auto'.
2589 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2590 FunctionDecl *FD = CurLambda->CallOperator;
2591 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002592 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002593
2594 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2595 assert(AT && "lost auto type from lambda return type");
2596 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2597 FD->setInvalidDecl();
2598 return StmtError();
2599 }
Alp Toker314cc812014-01-25 16:55:45 +00002600 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002601 } else if (CurCap->HasImplicitReturnType) {
2602 // For blocks/lambdas with implicit return types, we check each return
2603 // statement individually, and deduce the common return type when the block
2604 // or lambda is completed.
2605 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002606 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002607 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2608 if (Result.isInvalid())
2609 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002610 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002611
Richard Smith4db51c22013-09-25 05:02:54 +00002612 if (!CurContext->isDependentContext())
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002613 FnRetType = RetValExp->getType();
Richard Smith4db51c22013-09-25 05:02:54 +00002614 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002615 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002616 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002617 if (RetValExp) {
2618 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2619 // initializer list, because it is not an expression (even
2620 // though we represent it as one). We still deduce 'void'.
2621 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2622 << RetValExp->getSourceRange();
2623 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002624
Jordan Rosed39e5f12012-07-02 21:19:23 +00002625 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002626 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002627
2628 // Although we'll properly infer the type of the block once it's completed,
2629 // make sure we provide a return type now for better error recovery.
2630 if (CurCap->ReturnType.isNull())
2631 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002632 }
Eli Friedman34b49062012-01-26 03:00:14 +00002633 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002634
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002635 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002636 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2637 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2638 return StmtError();
2639 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002640 } else if (CapturedRegionScopeInfo *CurRegion =
2641 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2642 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2643 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002644 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002645 assert(CurLambda && "unknown kind of captured scope");
2646 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2647 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002648 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2649 return StmtError();
2650 }
2651 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002652
Steve Naroffc540d662008-09-03 18:15:37 +00002653 // Otherwise, verify that this result type matches the previous one. We are
2654 // pickier with blocks than for normal functions because we don't have GCC
2655 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002656 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002657 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002658 // Delay processing for now. TODO: there are lots of dependent
2659 // types we can conclusively prove aren't void.
2660 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002661 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002662 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002663 (RetValExp->isTypeDependent() ||
2664 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002665 if (!getLangOpts().CPlusPlus &&
2666 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002667 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002668 else {
2669 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002670 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002671 }
Steve Naroffc540d662008-09-03 18:15:37 +00002672 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002673 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002674 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2675 } else if (!RetValExp->isTypeDependent()) {
2676 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002677
John McCall5500ef22011-08-17 22:09:46 +00002678 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2679 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2680 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002681
John McCall5500ef22011-08-17 22:09:46 +00002682 // In C++ the return statement is handled via a copy initialization.
2683 // the C version of which boils down to CheckSingleAssignmentConstraints.
2684 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2685 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2686 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002687 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002688 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2689 FnRetType, RetValExp);
2690 if (Res.isInvalid()) {
2691 // FIXME: Cleanup temporaries here, anyway?
2692 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002693 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002694 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002695 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002696 } else {
2697 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002698 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002699
John McCall75f92b52011-08-17 21:34:14 +00002700 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002701 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2702 if (ER.isInvalid())
2703 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002704 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002705 }
John McCall5500ef22011-08-17 22:09:46 +00002706 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2707 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002708
Jordan Rosed39e5f12012-07-02 21:19:23 +00002709 // If we need to check for the named return value optimization,
2710 // or if we need to infer the return type,
2711 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002712 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002713 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002714
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002715 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002716}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002717
Nico Weber72889432014-09-06 01:25:55 +00002718namespace {
2719/// \brief Marks all typedefs in all local classes in a type referenced.
2720///
2721/// In a function like
2722/// auto f() {
2723/// struct S { typedef int a; };
2724/// return S();
2725/// }
2726///
2727/// the local type escapes and could be referenced in some TUs but not in
2728/// others. Pretend that all local typedefs are always referenced, to not warn
2729/// on this. This isn't necessary if f has internal linkage, or the typedef
2730/// is private.
2731class LocalTypedefNameReferencer
2732 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2733public:
2734 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2735 bool VisitRecordType(const RecordType *RT);
2736private:
2737 Sema &S;
2738};
2739bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2740 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2741 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2742 R->isDependentType())
2743 return true;
2744 for (auto *TmpD : R->decls())
2745 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2746 if (T->getAccess() != AS_private || R->hasFriends())
2747 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2748 return true;
2749}
2750}
2751
Richard Smith2a7d4812013-05-04 07:00:32 +00002752/// Deduce the return type for a function from a returned expression, per
2753/// C++1y [dcl.spec.auto]p6.
2754bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2755 SourceLocation ReturnLoc,
2756 Expr *&RetExpr,
2757 AutoType *AT) {
2758 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00002759 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith2a7d4812013-05-04 07:00:32 +00002760 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002761
Richard Smithc58f38f2013-08-14 20:16:31 +00002762 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2763 // If the deduction is for a return statement and the initializer is
2764 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002765 Diag(RetExpr->getExprLoc(),
2766 getCurLambda() ? diag::err_lambda_return_init_list
2767 : diag::err_auto_fn_return_init_list)
2768 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002769 return true;
2770 }
2771
2772 if (FD->isDependentContext()) {
2773 // C++1y [dcl.spec.auto]p12:
2774 // Return type deduction [...] occurs when the definition is
2775 // instantiated even if the function body contains a return
2776 // statement with a non-type-dependent operand.
2777 assert(AT->isDeduced() && "should have deduced to dependent type");
2778 return false;
2779 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002780 // If the deduction is for a return statement and the initializer is
2781 // a braced-init-list, the program is ill-formed.
2782 if (isa<InitListExpr>(RetExpr)) {
2783 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2784 return true;
2785 }
2786
2787 // Otherwise, [...] deduce a value for U using the rules of template
2788 // argument deduction.
2789 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2790
2791 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2792 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2793 << OrigResultType.getType() << RetExpr->getType();
2794
2795 if (DAR != DAR_Succeeded)
2796 return true;
Nico Weber72889432014-09-06 01:25:55 +00002797
2798 // If a local type is part of the returned type, mark its fields as
2799 // referenced.
2800 LocalTypedefNameReferencer Referencer(*this);
2801 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00002802 } else {
2803 // In the case of a return with no operand, the initializer is considered
2804 // to be void().
2805 //
2806 // Deduction here can only succeed if the return type is exactly 'cv auto'
2807 // or 'decltype(auto)', so just check for that case directly.
2808 if (!OrigResultType.getType()->getAs<AutoType>()) {
2809 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2810 << OrigResultType.getType();
2811 return true;
2812 }
2813 // We always deduce U = void in this case.
2814 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2815 if (Deduced.isNull())
2816 return true;
2817 }
2818
2819 // If a function with a declared return type that contains a placeholder type
2820 // has multiple return statements, the return type is deduced for each return
2821 // statement. [...] if the type deduced is not the same in each deduction,
2822 // the program is ill-formed.
2823 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2824 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002825 if (!FD->isDependentContext() &&
2826 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002827 const LambdaScopeInfo *LambdaSI = getCurLambda();
2828 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2829 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2830 << NewAT->getDeducedType() << AT->getDeducedType()
2831 << true /*IsLambda*/;
2832 } else {
2833 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2834 << (AT->isDecltypeAuto() ? 1 : 0)
2835 << NewAT->getDeducedType() << AT->getDeducedType();
2836 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002837 return true;
2838 }
2839 } else if (!FD->isInvalidDecl()) {
2840 // Update all declarations of the function to have the deduced return type.
2841 Context.adjustDeducedFunctionResultType(FD, Deduced);
2842 }
2843
2844 return false;
2845}
2846
John McCalldadc5752010-08-24 06:29:42 +00002847StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002848Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2849 Scope *CurScope) {
2850 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2851 if (R.isInvalid()) {
2852 return R;
2853 }
2854
2855 if (VarDecl *VD =
2856 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2857 CurScope->addNRVOCandidate(VD);
2858 } else {
2859 CurScope->setNoNRVO();
2860 }
2861
2862 return R;
2863}
2864
2865StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002866 // Check for unexpanded parameter packs.
2867 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2868 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002869
Eli Friedman34b49062012-01-26 03:00:14 +00002870 if (isa<CapturingScopeInfo>(getCurFunction()))
2871 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002872
Chris Lattner79413952008-12-04 23:50:19 +00002873 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002874 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002876 bool isObjCMethod = false;
2877
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002878 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002879 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002880 if (FD->hasAttrs())
2881 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002882 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002883 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002884 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002885 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002886 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002887 isObjCMethod = true;
2888 if (MD->hasAttrs())
2889 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002890 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2891 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002892 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002893 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002894 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2895 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002896 }
2897 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002898 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002899
Richard Smith2a7d4812013-05-04 07:00:32 +00002900 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2901 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002902 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002903 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2904 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002905 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002906 FD->setInvalidDecl();
2907 return StmtError();
2908 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002909 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002910 }
2911 }
2912 }
2913
Richard Smithc58f38f2013-08-14 20:16:31 +00002914 bool HasDependentReturnType = FnRetType->isDependentType();
2915
Craig Topperc3ec1492014-05-26 06:22:03 +00002916 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002917 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002918 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002919 if (isa<InitListExpr>(RetValExp)) {
2920 // We simply never allow init lists as the return value of void
2921 // functions. This is compatible because this was never allowed before,
2922 // so there's no legacy code to deal with.
2923 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2924 int FunctionKind = 0;
2925 if (isa<ObjCMethodDecl>(CurDecl))
2926 FunctionKind = 1;
2927 else if (isa<CXXConstructorDecl>(CurDecl))
2928 FunctionKind = 2;
2929 else if (isa<CXXDestructorDecl>(CurDecl))
2930 FunctionKind = 3;
2931
2932 Diag(ReturnLoc, diag::err_return_init_list)
2933 << CurDecl->getDeclName() << FunctionKind
2934 << RetValExp->getSourceRange();
2935
2936 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002937 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002938 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002939 // C99 6.8.6.4p1 (ext_ since GCC warns)
2940 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002941 if (RetValExp->getType()->isVoidType()) {
2942 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2943 if (isa<CXXConstructorDecl>(CurDecl) ||
2944 isa<CXXDestructorDecl>(CurDecl))
2945 D = diag::err_ctor_dtor_returns_void;
2946 else
2947 D = diag::ext_return_has_void_expr;
2948 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002949 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002950 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002951 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00002952 if (Result.isInvalid())
2953 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002954 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002955 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002956 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00002957 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002958 // return of void in constructor/destructor is illegal in C++.
2959 if (D == diag::err_ctor_dtor_returns_void) {
2960 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2961 Diag(ReturnLoc, D)
2962 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2963 << RetValExp->getSourceRange();
2964 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002965 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002966 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002967 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002968 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002969
2970 int FunctionKind = 0;
2971 if (isa<ObjCMethodDecl>(CurDecl))
2972 FunctionKind = 1;
2973 else if (isa<CXXConstructorDecl>(CurDecl))
2974 FunctionKind = 2;
2975 else if (isa<CXXDestructorDecl>(CurDecl))
2976 FunctionKind = 3;
2977
Nick Lewycky1be750a2011-06-01 07:44:31 +00002978 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002979 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002980 << RetValExp->getSourceRange();
2981 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002982 }
Mike Stump11289f42009-09-09 15:08:12 +00002983
Sebastian Redleef474c2012-02-22 10:50:08 +00002984 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002985 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2986 if (ER.isInvalid())
2987 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002988 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00002989 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002990 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002991
Craig Topperc3ec1492014-05-26 06:22:03 +00002992 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00002993 } else if (!RetValExp && !HasDependentReturnType) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002994 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2995 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002996 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002997
2998 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002999 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003000 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003001 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003002 Result = new (Context) ReturnStmt(ReturnLoc);
3003 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003004 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003005 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003006
3007 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3008
3009 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3010 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3011 // function return.
3012
3013 // In C++ the return statement is handled via a copy initialization,
3014 // the C version of which boils down to CheckSingleAssignmentConstraints.
3015 if (RetValExp)
3016 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003017 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003018 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003020 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003021 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003023 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003024 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003025 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003026 return StmtError();
3027 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003028 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003029
3030 // If we have a related result type, we need to implicitly
3031 // convert back to the formal result type. We can't pretend to
3032 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003033 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003034 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003035 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3036 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003037 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3038 if (Res.isInvalid()) {
3039 // FIXME: Clean up temporaries here anyway?
3040 return StmtError();
3041 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003042 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003043 }
3044
Artyom Skrobov9f213442014-01-24 11:10:39 +00003045 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3046 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
John McCallacf0ee52010-10-08 02:01:28 +00003049 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003050 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3051 if (ER.isInvalid())
3052 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003053 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003054 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003055 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003056 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
3058 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003059 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003060 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003061 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003062
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003063 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003064}
3065
John McCalldadc5752010-08-24 06:29:42 +00003066StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003067Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003068 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003069 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003070 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003071 if (Var && Var->isInvalidDecl())
3072 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003074 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003075}
3076
John McCalldadc5752010-08-24 06:29:42 +00003077StmtResult
John McCallb268a282010-08-23 23:25:46 +00003078Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003079 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003080}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003081
John McCalldadc5752010-08-24 06:29:42 +00003082StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003084 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003085 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003086 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3087
John McCallaab3e412010-08-25 08:40:02 +00003088 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003089 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003090 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3091 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003092}
3093
John McCall0bd3e402012-05-08 21:41:25 +00003094StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003095 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003096 ExprResult Result = DefaultLvalueConversion(Throw);
3097 if (Result.isInvalid())
3098 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003099
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003100 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003101 if (Result.isInvalid())
3102 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003103 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003104
Douglas Gregor2900c162010-04-22 21:44:01 +00003105 QualType ThrowType = Throw->getType();
3106 // Make sure the expression type is an ObjC pointer or "void *".
3107 if (!ThrowType->isDependentType() &&
3108 !ThrowType->isObjCObjectPointerType()) {
3109 const PointerType *PT = ThrowType->getAs<PointerType>();
3110 if (!PT || !PT->getPointeeType()->isVoidType())
3111 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3112 << Throw->getType() << Throw->getSourceRange());
3113 }
3114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003116 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003117}
3118
John McCalldadc5752010-08-24 06:29:42 +00003119StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003121 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003122 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003123 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3124
John McCallb268a282010-08-23 23:25:46 +00003125 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003126 // @throw without an expression designates a rethrow (which much occur
3127 // in the context of an @catch clause).
3128 Scope *AtCatchParent = CurScope;
3129 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3130 AtCatchParent = AtCatchParent->getParent();
3131 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003132 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133 }
John McCallb268a282010-08-23 23:25:46 +00003134 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003135}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003136
John McCalld9bb7432011-07-27 21:50:02 +00003137ExprResult
3138Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3139 ExprResult result = DefaultLvalueConversion(operand);
3140 if (result.isInvalid())
3141 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003142 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003143
3144 // Make sure the expression type is an ObjC pointer or "void *".
3145 QualType type = operand->getType();
3146 if (!type->isDependentType() &&
3147 !type->isObjCObjectPointerType()) {
3148 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003149 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3150 if (getLangOpts().CPlusPlus) {
3151 if (RequireCompleteType(atLoc, type,
3152 diag::err_incomplete_receiver_type))
3153 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3154 << type << operand->getSourceRange();
3155
3156 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3157 if (!result.isUsable())
3158 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3159 << type << operand->getSourceRange();
3160
3161 operand = result.get();
3162 } else {
3163 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3164 << type << operand->getSourceRange();
3165 }
3166 }
John McCalld9bb7432011-07-27 21:50:02 +00003167 }
3168
3169 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003170 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003171}
3172
John McCalldadc5752010-08-24 06:29:42 +00003173StmtResult
John McCallb268a282010-08-23 23:25:46 +00003174Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3175 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003176 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003177 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003178 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003179}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003180
3181/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3182/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003183StmtResult
John McCall48871652010-08-21 09:40:31 +00003184Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003185 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003186 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003187 return new (Context)
3188 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003189}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003190
John McCall31168b02011-06-15 23:02:42 +00003191StmtResult
3192Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3193 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003194 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003195}
3196
Dan Gohman28ade552010-07-26 21:25:24 +00003197namespace {
3198
Sebastian Redl63c4da02009-07-29 17:15:45 +00003199class TypeWithHandler {
3200 QualType t;
3201 CXXCatchStmt *stmt;
3202public:
3203 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3204 : t(type), stmt(statement) {}
3205
John McCall8ccfcb52009-09-24 19:53:00 +00003206 // An arbitrary order is fine as long as it places identical
3207 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003208 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003209 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003210 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003211 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003212 return false;
3213 else
3214 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3215 }
Mike Stump11289f42009-09-09 15:08:12 +00003216
Sebastian Redl63c4da02009-07-29 17:15:45 +00003217 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003218 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003219 }
Mike Stump11289f42009-09-09 15:08:12 +00003220
Sebastian Redl63c4da02009-07-29 17:15:45 +00003221 CXXCatchStmt *getCatchStmt() const { return stmt; }
3222 SourceLocation getTypeSpecStartLoc() const {
3223 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3224 }
3225};
3226
Dan Gohman28ade552010-07-26 21:25:24 +00003227}
3228
Sebastian Redl9b244a82008-12-22 21:35:02 +00003229/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3230/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003231StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3232 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003233 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003234 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003235 !getSourceManager().isInSystemHeader(TryLoc))
3236 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003237
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003238 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3239 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3240
Robert Wilhelmcafda822013-08-22 09:20:03 +00003241 const unsigned NumHandlers = Handlers.size();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003242 assert(NumHandlers > 0 &&
3243 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003244
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003245 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003246
3247 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003248 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003249 if (!Handler->getExceptionDecl()) {
3250 if (i < NumHandlers - 1)
3251 return StmtError(Diag(Handler->getLocStart(),
3252 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003253
Sebastian Redl63c4da02009-07-29 17:15:45 +00003254 continue;
3255 }
Mike Stump11289f42009-09-09 15:08:12 +00003256
Sebastian Redl63c4da02009-07-29 17:15:45 +00003257 const QualType CaughtType = Handler->getCaughtType();
3258 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3259 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003260 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003261
3262 // Detect handlers for the same type as an earlier one.
3263 if (NumHandlers > 1) {
3264 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003265
Sebastian Redl63c4da02009-07-29 17:15:45 +00003266 TypeWithHandler prev = TypesWithHandlers[0];
3267 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3268 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003269
Sebastian Redl63c4da02009-07-29 17:15:45 +00003270 if (curr == prev) {
3271 Diag(curr.getTypeSpecStartLoc(),
3272 diag::warn_exception_caught_by_earlier_handler)
3273 << curr.getCatchStmt()->getCaughtType().getAsString();
3274 Diag(prev.getTypeSpecStartLoc(),
3275 diag::note_previous_exception_handler)
3276 << prev.getCatchStmt()->getCaughtType().getAsString();
3277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Sebastian Redl63c4da02009-07-29 17:15:45 +00003279 prev = curr;
3280 }
3281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282
John McCallaab3e412010-08-25 08:40:02 +00003283 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003284
Sebastian Redl9b244a82008-12-22 21:35:02 +00003285 // FIXME: We should detect handlers that cannot catch anything because an
3286 // earlier handler catches a superclass. Need to find a method that is not
3287 // quadratic for this.
3288 // Neither of these are explicitly forbidden, but every compiler detects them
3289 // and warns.
3290
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003291 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003292}
John Wiegley1c0675e2011-04-28 01:08:34 +00003293
Warren Huntf6be4cb2014-07-25 20:52:51 +00003294StmtResult
3295Sema::ActOnSEHTryBlock(bool IsCXXTry,
3296 SourceLocation TryLoc,
3297 Stmt *TryBlock,
3298 Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003299 assert(TryBlock && Handler);
3300
3301 getCurFunction()->setHasBranchProtectedScope();
3302
Warren Huntf6be4cb2014-07-25 20:52:51 +00003303 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003304}
3305
3306StmtResult
3307Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3308 Expr *FilterExpr,
3309 Stmt *Block) {
3310 assert(FilterExpr && Block);
3311
3312 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003313 return StmtError(Diag(FilterExpr->getExprLoc(),
3314 diag::err_filter_expression_integral)
3315 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003316 }
3317
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003318 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003319}
3320
3321StmtResult
3322Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3323 Stmt *Block) {
3324 assert(Block);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003325 return SEHFinallyStmt::Create(Context,Loc,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003326}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003327
Nico Weberc7d05962014-07-06 22:32:59 +00003328StmtResult
3329Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003330 Scope *SEHTryParent = CurScope;
3331 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3332 SEHTryParent = SEHTryParent->getParent();
3333 if (!SEHTryParent)
3334 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3335
Nico Weber9b982072014-07-07 00:12:30 +00003336 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003337}
3338
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003339StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3340 bool IsIfExists,
3341 NestedNameSpecifierLoc QualifierLoc,
3342 DeclarationNameInfo NameInfo,
3343 Stmt *Nested)
3344{
3345 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003346 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003347 cast<CompoundStmt>(Nested));
3348}
3349
3350
Chad Rosier02a84392012-08-10 17:56:09 +00003351StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003352 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003353 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003354 UnqualifiedId &Name,
3355 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003356 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003357 SS.getWithLocInContext(Context),
3358 GetNameFromUnqualifiedId(Name),
3359 Nested);
3360}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003361
3362RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003363Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3364 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003365 DeclContext *DC = CurContext;
3366 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3367 DC = DC->getParent();
3368
Craig Topperc3ec1492014-05-26 06:22:03 +00003369 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003370 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003371 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3372 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003373 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003374 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003375
3376 DC->addDecl(RD);
3377 RD->setImplicit();
3378 RD->startDefinition();
3379
Alexey Bataev9959db52014-05-06 10:08:46 +00003380 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003381 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003382 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003383 return RD;
3384}
3385
3386static void buildCapturedStmtCaptureList(
3387 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3388 SmallVectorImpl<Expr *> &CaptureInits,
3389 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3390
3391 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3392 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3393
3394 if (Cap->isThisCapture()) {
3395 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3396 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003397 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003398 continue;
3399 }
3400
3401 assert(Cap->isReferenceCapture() &&
3402 "non-reference capture not yet implemented");
3403
3404 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3405 CapturedStmt::VCK_ByRef,
3406 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003407 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003408 }
3409}
3410
3411void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003412 CapturedRegionKind Kind,
3413 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003414 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003415 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003416
Alexey Bataev9959db52014-05-06 10:08:46 +00003417 // Build the context parameter
3418 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3419 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3420 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3421 ImplicitParamDecl *Param
3422 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3423 DC->addDecl(Param);
3424
3425 CD->setContextParam(0, Param);
3426
3427 // Enter the capturing scope for this captured region.
3428 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3429
3430 if (CurScope)
3431 PushDeclContext(CurScope, CD);
3432 else
3433 CurContext = CD;
3434
3435 PushExpressionEvaluationContext(PotentiallyEvaluated);
3436}
3437
3438void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3439 CapturedRegionKind Kind,
3440 ArrayRef<CapturedParamNameType> Params) {
3441 CapturedDecl *CD = nullptr;
3442 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3443
3444 // Build the context parameter
3445 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3446 bool ContextIsFound = false;
3447 unsigned ParamNum = 0;
3448 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3449 E = Params.end();
3450 I != E; ++I, ++ParamNum) {
3451 if (I->second.isNull()) {
3452 assert(!ContextIsFound &&
3453 "null type has been found already for '__context' parameter");
3454 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3455 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3456 ImplicitParamDecl *Param
3457 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3458 DC->addDecl(Param);
3459 CD->setContextParam(ParamNum, Param);
3460 ContextIsFound = true;
3461 } else {
3462 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3463 ImplicitParamDecl *Param
3464 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3465 DC->addDecl(Param);
3466 CD->setParam(ParamNum, Param);
3467 }
3468 }
3469 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003470 if (!ContextIsFound) {
3471 // Add __context implicitly if it is not specified.
3472 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3473 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3474 ImplicitParamDecl *Param =
3475 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3476 DC->addDecl(Param);
3477 CD->setContextParam(ParamNum, Param);
3478 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003479 // Enter the capturing scope for this captured region.
3480 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3481
3482 if (CurScope)
3483 PushDeclContext(CurScope, CD);
3484 else
3485 CurContext = CD;
3486
3487 PushExpressionEvaluationContext(PotentiallyEvaluated);
3488}
3489
Wei Pan17fbf6e2013-05-04 03:59:06 +00003490void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003491 DiscardCleanupsInEvaluationContext();
3492 PopExpressionEvaluationContext();
3493
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003494 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3495 RecordDecl *Record = RSI->TheRecordDecl;
3496 Record->setInvalidDecl();
3497
Aaron Ballman62e47c42014-03-10 13:43:55 +00003498 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003499 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3500 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003501
Wei Pan17fbf6e2013-05-04 03:59:06 +00003502 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003503 PopFunctionScopeInfo();
3504}
3505
3506StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3507 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3508
3509 SmallVector<CapturedStmt::Capture, 4> Captures;
3510 SmallVector<Expr *, 4> CaptureInits;
3511 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3512
3513 CapturedDecl *CD = RSI->TheCapturedDecl;
3514 RecordDecl *RD = RSI->TheRecordDecl;
3515
Wei Pan17fbf6e2013-05-04 03:59:06 +00003516 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3517 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003518 CaptureInits, CD, RD);
3519
3520 CD->setBody(Res->getCapturedStmt());
3521 RD->completeDefinition();
3522
Wei Pan17fbf6e2013-05-04 03:59:06 +00003523 DiscardCleanupsInEvaluationContext();
3524 PopExpressionEvaluationContext();
3525
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003526 PopDeclContext();
3527 PopFunctionScopeInfo();
3528
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003529 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003530}