blob: f1377eb45ed6d25a1abe3352f7e18b56f09295b8 [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"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Richard Smith945f8d32013-01-14 22:39:08 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45 if (FE.isInvalid())
46 return StmtError();
47
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
50 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000141 switch (Op->getOperator()) {
142 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000143 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000144 case OO_EqualEqual:
145 case OO_ExclaimEqual:
146 IsRelational = false;
147 break;
148 case OO_Less:
149 case OO_Greater:
150 case OO_GreaterEqual:
151 case OO_LessEqual:
152 IsRelational = true;
153 break;
154 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else {
160 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162 }
163
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthe2669392011-08-17 09:34:37 +0000169 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000174 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000175 if (IsNotEqual)
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
178 else
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
181 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000182
183 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184}
185
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
189
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000190 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000191 if (!E)
192 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000193
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
197 return;
198
Nico Weber0e631632015-10-27 19:47:40 +0000199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000210 SourceLocation Loc;
211 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000213 return;
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattner6dc7e572012-08-31 22:39:21 +0000215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
218 // false positive.
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
220 return;
221
Nico Weber0e631632015-10-27 19:47:40 +0000222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228 return;
229 }
230
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
233 // cases now.
234 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000236 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000239
Chandler Carruthe2669392011-08-17 09:34:37 +0000240 if (DiagnoseUnusedComparison(*this, E))
241 return;
242
Eli Friedmanc11535c2012-05-24 00:47:05 +0000243 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000245 if (E->getType()->isVoidType())
246 return;
247
Chris Lattner1a6babf2009-10-13 04:53:48 +0000248 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
251 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000252 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 return;
258 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000259 if (ShouldSuppress)
260 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000261 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263 return;
264 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000265 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 } else if (ShouldSuppress)
271 return;
272
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
276 return;
277 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000279 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000282 return;
283 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
289 else
290 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
293 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
294 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
295 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000296 }
John McCall2351cb92010-04-06 22:24:14 +0000297 // Diagnose "(void*) blah" as a typo for "(void) blah".
298 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
299 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
300 QualType T = TI->getType();
301
302 // We really do want to use the non-canonical type here.
303 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000304 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000305
306 Diag(Loc, diag::warn_unused_voidptr)
307 << FixItHint::CreateRemoval(TL.getStarLoc());
308 return;
309 }
310 }
311
Eli Friedmanc11535c2012-05-24 00:47:05 +0000312 if (E->isGLValue() && E->getType().isVolatileQualified()) {
313 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
314 return;
315 }
316
Craig Topperc3ec1492014-05-26 06:22:03 +0000317 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000318}
319
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000320void Sema::ActOnStartOfCompoundStmt() {
321 PushCompoundScope();
322}
323
324void Sema::ActOnFinishOfCompoundStmt() {
325 PopCompoundScope();
326}
327
328sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
329 return getCurFunction()->CompoundScopes.back();
330}
331
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000332StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
333 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
334 const unsigned NumElts = Elts.size();
335
Chris Lattnerd864daf2007-08-27 04:29:41 +0000336 // If we're in C89 mode, check that we don't have any decls after stmts. If
337 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 // Note that __extension__ can be around a decl.
340 unsigned i = 0;
341 // Skip over all declarations.
342 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
343 /*empty*/;
344
345 // We found the end of the list or a statement. Scan for another declstmt.
346 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
347 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000348
Chris Lattnerd864daf2007-08-27 04:29:41 +0000349 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000350 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000351 Diag(D->getLocation(), diag::ext_mixed_decls_code);
352 }
353 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000354 // Warn about unused expressions in statements.
355 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000356 // Ignore statements that are last in a statement expression.
357 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000358 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000360 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000361 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000362
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000363 // Check for suspicious empty body (null statement) in `for' and `while'
364 // statements. Don't do anything for template instantiations, this just adds
365 // noise.
366 if (NumElts != 0 && !CurrentInstantiationScope &&
367 getCurCompoundScope().HasEmptyLoopBodies) {
368 for (unsigned i = 0; i != NumElts - 1; ++i)
369 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
370 }
371
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000372 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000373}
374
John McCalldadc5752010-08-24 06:29:42 +0000375StmtResult
John McCallb268a282010-08-23 23:25:46 +0000376Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
377 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000378 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000379 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000380
John McCallaab3e412010-08-25 08:40:02 +0000381 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000382 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000383 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000384 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000385
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000386 ExprResult LHS =
387 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
388 if (!getLangOpts().CPlusPlus11)
389 return VerifyIntegerConstantExpression(E);
390 if (Expr *CondExpr =
391 getCurFunction()->SwitchStack.back()->getCond()) {
392 QualType CondType = CondExpr->getType();
393 llvm::APSInt TempVal;
394 return CheckConvertedConstantExpression(E, CondType, TempVal,
395 CCEK_CaseValue);
396 }
397 return ExprError();
398 });
399 if (LHS.isInvalid())
400 return StmtError();
401 LHSVal = LHS.get();
402
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000403 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000404 // C99 6.8.4.2p3: The expression shall be an integer constant.
405 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000406 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000407 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000408 if (!LHSVal)
409 return StmtError();
410 }
Richard Smithf8379a02012-01-18 23:55:52 +0000411
412 // GCC extension: The expression shall be an integer constant.
413
Richard Smithf4c51d92012-02-04 09:53:13 +0000414 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000415 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000416 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000417 }
418 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000419
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000420 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000421 getLangOpts().CPlusPlus11);
422 if (LHS.isInvalid())
423 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000424
Richard Smith5b555da2014-11-20 01:24:12 +0000425 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
426 getLangOpts().CPlusPlus11)
427 : ExprResult();
428 if (RHS.isInvalid())
429 return StmtError();
430
431 CaseStmt *CS = new (Context)
432 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000433 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000434 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000435}
436
Chris Lattner34a22092009-03-04 04:23:07 +0000437/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000438void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000439 DiagnoseUnusedExprResult(SubStmt);
440
Chris Lattner34a22092009-03-04 04:23:07 +0000441 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000442 CS->setSubStmt(SubStmt);
443}
444
John McCalldadc5752010-08-24 06:29:42 +0000445StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000446Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000447 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000448 DiagnoseUnusedExprResult(SubStmt);
449
John McCallaab3e412010-08-25 08:40:02 +0000450 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000451 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000452 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000453 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000454
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000455 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000456 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000458}
459
John McCalldadc5752010-08-24 06:29:42 +0000460StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000461Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
462 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000463 // If the label was multiply defined, reject it now.
464 if (TheDecl->getStmt()) {
465 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
466 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000467 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000468 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000469
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000470 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000471 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
472 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000473 if (!TheDecl->isGnuLocal()) {
474 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000475 if (!TheDecl->isMSAsmLabel()) {
476 // Don't update the location of MS ASM labels. These will result in
477 // a diagnostic, and changing the location here will mess that up.
478 TheDecl->setLocation(IdentLoc);
479 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000480 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000481 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000482}
483
Richard Smithc202b282012-04-14 00:33:13 +0000484StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000485 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000486 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000487 // Fill in the declaration and return it.
488 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000489 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000490}
491
Richard Trieufaca2d82016-02-18 23:58:40 +0000492namespace {
493class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
494 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
495 Sema &SemaRef;
496public:
497 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
498 void VisitBinaryOperator(BinaryOperator *E) {
499 if (E->getOpcode() == BO_Comma)
500 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
501 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
502 }
503};
504}
505
John McCalldadc5752010-08-24 06:29:42 +0000506StmtResult
John McCall48871652010-08-21 09:40:31 +0000507Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000508 Stmt *thenStmt, SourceLocation ElseLoc,
509 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000510 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000511
Craig Topperc3ec1492014-05-26 06:22:03 +0000512 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000513 if (CondVar) {
514 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000515 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +0000516 CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
Douglas Gregor633caca2009-11-23 23:44:04 +0000517 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000518 Expr *ConditionExpr = CondResult.getAs<Expr>();
Olivier Goffart122993b2015-10-11 17:27:29 +0000519 if (ConditionExpr) {
Richard Trieufaca2d82016-02-18 23:58:40 +0000520
521 if (!Diags.isIgnored(diag::warn_comma_operator,
522 ConditionExpr->getExprLoc()))
523 CommaVisitor(*this).Visit(ConditionExpr);
524
Olivier Goffart122993b2015-10-11 17:27:29 +0000525 DiagnoseUnusedExprResult(thenStmt);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Olivier Goffart122993b2015-10-11 17:27:29 +0000527 if (!elseStmt) {
528 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
529 diag::warn_empty_if_body);
530 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000531
Olivier Goffart122993b2015-10-11 17:27:29 +0000532 DiagnoseUnusedExprResult(elseStmt);
533 } else {
534 // Create a dummy Expr for the condition for error recovery
535 ConditionExpr = new (Context) OpaqueValueExpr(SourceLocation(),
536 Context.BoolTy, VK_RValue);
Anders Carlssondb83d772007-10-10 20:50:11 +0000537 }
538
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000539 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
540 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000541}
Steve Naroff86272ea2007-05-29 02:14:17 +0000542
Chris Lattner67998452007-08-23 18:29:20 +0000543namespace {
544 struct CaseCompareFunctor {
545 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
546 const llvm::APSInt &RHS) {
547 return LHS.first < RHS;
548 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000549 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
550 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
551 return LHS.first < RHS.first;
552 }
Chris Lattner67998452007-08-23 18:29:20 +0000553 bool operator()(const llvm::APSInt &LHS,
554 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
555 return LHS < RHS.first;
556 }
557 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000558}
Chris Lattner67998452007-08-23 18:29:20 +0000559
Chris Lattner4b2ff022007-09-21 18:15:22 +0000560/// CmpCaseVals - Comparison predicate for sorting case values.
561///
562static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
563 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
564 if (lhs.first < rhs.first)
565 return true;
566
567 if (lhs.first == rhs.first &&
568 lhs.second->getCaseLoc().getRawEncoding()
569 < rhs.second->getCaseLoc().getRawEncoding())
570 return true;
571 return false;
572}
573
Douglas Gregorbd6839732010-02-08 22:24:16 +0000574/// CmpEnumVals - Comparison predicate for sorting enumeration values.
575///
576static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
577 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
578{
579 return lhs.first < rhs.first;
580}
581
582/// EqEnumVals - Comparison preficate for uniqing enumeration values.
583///
584static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
585 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
586{
587 return lhs.first == rhs.first;
588}
589
Chris Lattnera96d4272009-10-16 16:45:22 +0000590/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
591/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000592static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
593 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
594 expr = cleanups->getSubExpr();
595 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
596 if (impcast->getCastKind() != CK_IntegralCast) break;
597 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000598 }
599 return expr->getType();
600}
601
John McCalldadc5752010-08-24 06:29:42 +0000602StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000604 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000605 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000606
Craig Topperc3ec1492014-05-26 06:22:03 +0000607 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000608 if (CondVar) {
609 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000610 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
611 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000612 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000614 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
John McCallb268a282010-08-23 23:25:46 +0000617 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000618 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregore2b37442012-05-04 22:38:52 +0000620 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
621 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000622
Douglas Gregore2b37442012-05-04 22:38:52 +0000623 public:
624 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000625 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
626 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000627
Craig Toppere14c0f82014-03-12 04:55:44 +0000628 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
629 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000630 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
631 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000632
Craig Toppere14c0f82014-03-12 04:55:44 +0000633 SemaDiagnosticBuilder diagnoseIncomplete(
634 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000635 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
636 << T << Cond->getSourceRange();
637 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000638
Craig Toppere14c0f82014-03-12 04:55:44 +0000639 SemaDiagnosticBuilder diagnoseExplicitConv(
640 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000641 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
642 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000643
Craig Toppere14c0f82014-03-12 04:55:44 +0000644 SemaDiagnosticBuilder noteExplicitConv(
645 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000646 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
647 << ConvTy->isEnumeralType() << ConvTy;
648 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000649
Craig Toppere14c0f82014-03-12 04:55:44 +0000650 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
651 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000652 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
653 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000654
Craig Toppere14c0f82014-03-12 04:55:44 +0000655 SemaDiagnosticBuilder noteAmbiguous(
656 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000657 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
658 << ConvTy->isEnumeralType() << ConvTy;
659 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000660
Craig Toppere14c0f82014-03-12 04:55:44 +0000661 SemaDiagnosticBuilder diagnoseConversion(
662 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000663 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000664 }
665 } SwitchDiagnoser(Cond);
666
Richard Smithccc11812013-05-21 19:05:48 +0000667 CondResult =
668 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000669 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000670 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
John McCall5939b162011-08-06 07:30:58 +0000672 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
673 CondResult = UsualUnaryConversions(Cond);
674 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000675 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000676
Meador Ingef0af05c2015-06-25 22:06:40 +0000677 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
678 if (CondResult.isInvalid())
679 return StmtError();
680 Cond = CondResult.get();
John McCalla95172b2010-08-01 00:26:45 +0000681
John McCallaab3e412010-08-25 08:40:02 +0000682 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
John McCallb268a282010-08-23 23:25:46 +0000684 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000685 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000686 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000687}
688
Gabor Greif16e02862010-10-01 22:05:14 +0000689static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000690 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000691 Val.setIsSigned(IsSigned);
692}
693
Richard Smith077d0832014-08-04 00:40:48 +0000694/// Check the specified case value is in range for the given unpromoted switch
695/// type.
696static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
697 unsigned UnpromotedWidth, bool UnpromotedSign) {
698 // If the case value was signed and negative and the switch expression is
699 // unsigned, don't bother to warn: this is implementation-defined behavior.
700 // FIXME: Introduce a second, default-ignored warning for this case?
701 if (UnpromotedWidth < Val.getBitWidth()) {
702 llvm::APSInt ConvVal(Val);
703 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
704 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
705 // FIXME: Use different diagnostics for overflow in conversion to promoted
706 // type versus "switch expression cannot have this value". Use proper
707 // IntRange checking rather than just looking at the unpromoted type here.
708 if (ConvVal != Val)
709 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
710 << ConvVal.toString(10);
711 }
712}
713
Alexis Hunt724f14e2014-11-28 00:53:20 +0000714typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
715
Dmitri Gribenko58683752013-12-05 22:52:07 +0000716/// Returns true if we should emit a diagnostic about this case expression not
717/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000718static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000719 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000720 const Expr *CaseExpr,
721 EnumValsTy::iterator &EI,
722 EnumValsTy::iterator &EIEnd,
723 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000724 if (const DeclRefExpr *DRE =
725 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000726 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000727 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000728 QualType EnumType = S.Context.getTypeDeclType(ED);
729 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
730 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000731 return false;
732 }
733 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000734
Richard Smith332653c2015-09-04 01:03:03 +0000735 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000736 return !S.IsValueInFlagEnum(ED, Val, false);
737 } else {
738 while (EI != EIEnd && EI->first < Val)
739 EI++;
740
741 if (EI != EIEnd && EI->first == Val)
742 return false;
743 }
744
Dmitri Gribenko58683752013-12-05 22:52:07 +0000745 return true;
746}
747
John McCalldadc5752010-08-24 06:29:42 +0000748StmtResult
John McCallb268a282010-08-23 23:25:46 +0000749Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
750 Stmt *BodyStmt) {
751 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000752 assert(SS == getCurFunction()->SwitchStack.back() &&
753 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000754
David Majnemer418ad3f2014-12-15 07:46:12 +0000755 getCurFunction()->SwitchStack.pop_back();
756
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000757 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000758 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000759
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000760 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000761 if (!CondExpr) return StmtError();
762
763 QualType CondType = CondExpr->getType();
764
John McCalld3dfbd62010-05-18 03:19:21 +0000765 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000766 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000767 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000768
Chris Lattnera96d4272009-10-16 16:45:22 +0000769 // C++ 6.4.2.p2:
770 // Integral promotions are performed (on the switch condition).
771 //
772 // A case value unrepresentable by the original switch condition
773 // type (before the promotion) doesn't make sense, even when it can
774 // be represented by the promoted type. Therefore we need to find
775 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000776 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000777 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000779 // appropriate type now, just return an error.
780 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000781 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000782
Chris Lattner4ebae652010-04-16 23:34:13 +0000783 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000784 // switch(bool_expr) {...} is often a programmer error, e.g.
785 // switch(n && mask) { ... } // Doh - should be "n & mask".
786 // One can always use an if statement instead of switch(bool_expr).
787 Diag(SwitchLoc, diag::warn_bool_switch_condition)
788 << CondExpr->getSourceRange();
789 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000790 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000791
Richard Smith077d0832014-08-04 00:40:48 +0000792 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000793 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000794 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000795 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000796 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
797 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
798
799 // Get the width and signedness that the condition might actually have, for
800 // warning purposes.
801 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
802 // type.
803 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000804 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000805 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000806 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000807
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000808 // Accumulate all of the case values in a vector so that we can sort them
809 // and detect duplicates. This vector contains the APInt for the case after
810 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000811 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000812 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000813
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000814 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000815 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
816 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000817
Craig Topperc3ec1492014-05-26 06:22:03 +0000818 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000819
Chris Lattner10cb5e52007-08-23 06:23:56 +0000820 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000821
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000822 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000823 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000824
Anders Carlsson51873c22007-07-22 07:07:56 +0000825 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000826 if (TheDefaultStmt) {
827 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000828 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000829
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000830 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000831 // we'll return a valid AST. This requires recursing down the AST and
832 // finding it, not something we are set up to do right now. For now,
833 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000834 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000835 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000836 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000838 } else {
839 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000840
Chris Lattnera65e1f32008-01-16 19:17:22 +0000841 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000842
843 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
844 HasDependentValue = true;
845 break;
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Richard Smithf8379a02012-01-18 23:55:52 +0000848 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000849
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000850 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000851 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
852 // constant expression of the promoted type of the switch condition.
853 ExprResult ConvLo =
854 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
855 if (ConvLo.isInvalid()) {
856 CaseListIsErroneous = true;
857 continue;
858 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000859 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000860 } else {
861 // We already verified that the expression has a i-c-e value (C99
862 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000863 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000864
865 // If the LHS is not the same type as the condition, insert an implicit
866 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000867 Lo = DefaultLvalueConversion(Lo).get();
868 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000869 }
870
Richard Smith077d0832014-08-04 00:40:48 +0000871 // Check the unconverted value is within the range of possible values of
872 // the switch expression.
873 checkCaseValue(*this, Lo->getLocStart(), LoVal,
874 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
875
876 // Convert the value to the same width/sign as the condition.
877 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000878
Chris Lattnera65e1f32008-01-16 19:17:22 +0000879 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000880
Chris Lattner10cb5e52007-08-23 06:23:56 +0000881 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000882 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000883 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000884 CS->getRHS()->isValueDependent()) {
885 HasDependentValue = true;
886 break;
887 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000888 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000889 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000890 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000891 }
892 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000893
894 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000895 // If we don't have a default statement, check whether the
896 // condition is constant.
897 llvm::APSInt ConstantCondValue;
898 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000899 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000900 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
901 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000902 assert(!HasConstantCond ||
903 (ConstantCondValue.getBitWidth() == CondWidth &&
904 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000905 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000906 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000907
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 // Sort all the scalar case values so we can easily detect duplicates.
909 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
910
911 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000912 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
913 if (ShouldCheckConstantCond &&
914 CaseVals[i].first == ConstantCondValue)
915 ShouldCheckConstantCond = false;
916
917 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000918 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000919 // First, determine if either case value has a name
920 StringRef PrevString, CurrString;
921 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
922 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
923 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
924 PrevString = DeclRef->getDecl()->getName();
925 }
926 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
927 CurrString = DeclRef->getDecl()->getName();
928 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000929 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000930 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000931
932 if (PrevString == CurrString)
933 Diag(CaseVals[i].second->getLHS()->getLocStart(),
934 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000935 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000936 else
937 Diag(CaseVals[i].second->getLHS()->getLocStart(),
938 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000939 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
940 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000941 CaseValStr;
942
John McCalld3dfbd62010-05-18 03:19:21 +0000943 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000944 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000945 // FIXME: We really want to remove the bogus case stmt from the
946 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000947 CaseListIsErroneous = true;
948 }
949 }
950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000952 // Detect duplicate case ranges, which usually don't exist at all in
953 // the first place.
954 if (!CaseRanges.empty()) {
955 // Sort all the case ranges by their low value so we can easily detect
956 // overlaps between ranges.
957 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000958
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000959 // Scan the ranges, computing the high values and removing empty ranges.
960 std::vector<llvm::APSInt> HiVals;
961 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000962 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000963 CaseStmt *CR = CaseRanges[i].second;
964 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000965 llvm::APSInt HiVal;
966
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000967 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000968 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
969 // constant expression of the promoted type of the switch condition.
970 ExprResult ConvHi =
971 CheckConvertedConstantExpression(Hi, CondType, HiVal,
972 CCEK_CaseValue);
973 if (ConvHi.isInvalid()) {
974 CaseListIsErroneous = true;
975 continue;
976 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000977 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000978 } else {
979 HiVal = Hi->EvaluateKnownConstInt(Context);
980
981 // If the RHS is not the same type as the condition, insert an
982 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000983 Hi = DefaultLvalueConversion(Hi).get();
984 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
Richard Smith077d0832014-08-04 00:40:48 +0000987 // Check the unconverted value is within the range of possible values of
988 // the switch expression.
989 checkCaseValue(*this, Hi->getLocStart(), HiVal,
990 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000993 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000996
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000997 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000998 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000999 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1000 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +00001001 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001002 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001003 --i;
1004 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001005 continue;
1006 }
John McCalld3dfbd62010-05-18 03:19:21 +00001007
1008 if (ShouldCheckConstantCond &&
1009 LoVal <= ConstantCondValue &&
1010 ConstantCondValue <= HiVal)
1011 ShouldCheckConstantCond = false;
1012
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001013 HiVals.push_back(HiVal);
1014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001016 // Rescan the ranges, looking for overlap with singleton values and other
1017 // ranges. Since the range list is sorted, we only need to compare case
1018 // ranges with their neighbors.
1019 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1020 llvm::APSInt &CRLo = CaseRanges[i].first;
1021 llvm::APSInt &CRHi = HiVals[i];
1022 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001023
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001024 // Check to see whether the case range overlaps with any
1025 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001026 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001027 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 // Find the smallest value >= the lower bound. If I is in the
1030 // case range, then we have overlap.
1031 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1032 CaseVals.end(), CRLo,
1033 CaseCompareFunctor());
1034 if (I != CaseVals.end() && I->first < CRHi) {
1035 OverlapVal = I->first; // Found overlap with scalar.
1036 OverlapStmt = I->second;
1037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001039 // Find the smallest value bigger than the upper bound.
1040 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1041 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1042 OverlapVal = (I-1)->first; // Found overlap with scalar.
1043 OverlapStmt = (I-1)->second;
1044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001046 // Check to see if this case stmt overlaps with the subsequent
1047 // case range.
1048 if (i && CRLo <= HiVals[i-1]) {
1049 OverlapVal = HiVals[i-1]; // Found overlap with range.
1050 OverlapStmt = CaseRanges[i-1].second;
1051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001053 if (OverlapStmt) {
1054 // If we have a duplicate, report it.
1055 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1056 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001057 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001058 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001059 // FIXME: We really want to remove the bogus case stmt from the
1060 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001061 CaseListIsErroneous = true;
1062 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001063 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001064 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001065
John McCalld3dfbd62010-05-18 03:19:21 +00001066 // Complain if we have a constant condition and we didn't find a match.
1067 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1068 // TODO: it would be nice if we printed enums as enums, chars as
1069 // chars, etc.
1070 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1071 << ConstantCondValue.toString(10)
1072 << CondExpr->getSourceRange();
1073 }
1074
1075 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001076 // values. We only issue a warning if there is not 'default:', but
1077 // we still do the analysis to preserve this information in the AST
1078 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001079 //
Chris Lattner51679082010-09-16 17:09:42 +00001080 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001081
Douglas Gregorbd6839732010-02-08 22:24:16 +00001082 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001083 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001084 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001085 EnumValsTy EnumVals;
1086
John McCalld3dfbd62010-05-18 03:19:21 +00001087 // Gather all enum values, set their type and sort them,
1088 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001089 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001090 llvm::APSInt Val = EDI->getInitVal();
1091 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001092 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001093 }
1094 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001095 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001096 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001097
1098 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001099 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001100 CI != CaseVals.end(); CI++) {
1101 Expr *CaseExpr = CI->second->getLHS();
1102 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1103 CI->first))
1104 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1105 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001106 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001107
David Blaikiee476f972012-01-22 02:31:55 +00001108 // See which of case ranges aren't in enum
1109 EI = EnumVals.begin();
1110 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001111 RI != CaseRanges.end(); RI++) {
1112 Expr *CaseExpr = RI->second->getLHS();
1113 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1114 RI->first))
1115 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1116 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001117
Chad Rosier02a84392012-08-10 17:56:09 +00001118 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001119 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1120 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001121
1122 CaseExpr = RI->second->getRHS();
1123 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1124 Hi))
1125 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1126 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128
Ted Kremenekc42f3452010-09-09 00:05:53 +00001129 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001130 auto CI = CaseVals.begin();
1131 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001132 bool hasCasesNotInSwitch = false;
1133
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001134 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
Alexis Hunt724f14e2014-11-28 00:53:20 +00001136 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001137 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001138 while (CI != CaseVals.end() && CI->first < EI->first)
1139 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Douglas Gregorbd6839732010-02-08 22:24:16 +00001141 if (CI != CaseVals.end() && CI->first == EI->first)
1142 continue;
1143
Ted Kremenekc42f3452010-09-09 00:05:53 +00001144 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001145 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001146 llvm::APSInt Hi =
1147 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001148 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001149 if (EI->first <= Hi)
1150 break;
1151 }
1152
Ted Kremenekc42f3452010-09-09 00:05:53 +00001153 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001154 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001155 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001156 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158
David Blaikie60ac6382012-01-23 04:46:12 +00001159 if (TheDefaultStmt && UnhandledNames.empty())
1160 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001161
Chris Lattner51679082010-09-16 17:09:42 +00001162 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001163 if (!UnhandledNames.empty()) {
1164 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1165 TheDefaultStmt ? diag::warn_def_missing_case
1166 : diag::warn_missing_case)
1167 << (int)UnhandledNames.size();
1168
1169 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1170 I != E; ++I)
1171 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001172 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001173
1174 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001175 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001176 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001177 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001178
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001179 if (BodyStmt)
1180 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1181 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001182
Mike Stump87c57ac2009-05-16 07:39:55 +00001183 // FIXME: If the case list was broken is some way, we don't have a good system
1184 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001185 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001186 return StmtError();
1187
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001188 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001189}
1190
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001191void
1192Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1193 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001194 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001195 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001196
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001197 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001198 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001199 SrcType->isIntegerType()) {
1200 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1201 SrcExpr->isIntegerConstantExpr(Context)) {
1202 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001203 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001204 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1205
1206 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001207 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001208 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001209
Alexis Hunt724f14e2014-11-28 00:53:20 +00001210 if (ED->hasAttr<FlagEnumAttr>()) {
1211 if (!IsValueInFlagEnum(ED, RhsVal, true))
1212 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001213 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001214 } else {
1215 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1216 EnumValsTy;
1217 EnumValsTy EnumVals;
1218
1219 // Gather all enum values, set their type and sort them,
1220 // allowing easier comparison with rhs constant.
1221 for (auto *EDI : ED->enumerators()) {
1222 llvm::APSInt Val = EDI->getInitVal();
1223 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1224 EnumVals.push_back(std::make_pair(Val, EDI));
1225 }
1226 if (EnumVals.empty())
1227 return;
1228 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1229 EnumValsTy::iterator EIend =
1230 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1231
1232 // See which values aren't in the enum.
1233 EnumValsTy::const_iterator EI = EnumVals.begin();
1234 while (EI != EIend && EI->first < RhsVal)
1235 EI++;
1236 if (EI == EIend || EI->first != RhsVal) {
1237 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1238 << DstType.getUnqualifiedType();
1239 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001240 }
1241 }
1242 }
1243}
1244
John McCalldadc5752010-08-24 06:29:42 +00001245StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001246Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001247 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001248 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001249
Craig Topperc3ec1492014-05-26 06:22:03 +00001250 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001251 if (CondVar) {
1252 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001253 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001254 CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001255 if (CondResult.isInvalid())
1256 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001257 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001258 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001259 if (!ConditionExpr)
1260 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001261 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262
Richard Trieufaca2d82016-02-18 23:58:40 +00001263 if (ConditionExpr &&
1264 !Diags.isIgnored(diag::warn_comma_operator, ConditionExpr->getExprLoc()))
1265 CommaVisitor(*this).Visit(ConditionExpr);
1266
John McCallb268a282010-08-23 23:25:46 +00001267 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001268
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001269 if (isa<NullStmt>(Body))
1270 getCurCompoundScope().setHasEmptyLoopBodies();
1271
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001272 return new (Context)
1273 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001274}
1275
John McCalldadc5752010-08-24 06:29:42 +00001276StmtResult
John McCallb268a282010-08-23 23:25:46 +00001277Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001278 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001279 Expr *Cond, SourceLocation CondRParen) {
1280 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001281
Serge Pavlov09f99242014-01-23 15:05:00 +00001282 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001283 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001284 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001285 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001286 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001287
Richard Smith945f8d32013-01-14 22:39:08 +00001288 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001289 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001290 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001291 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
John McCallb268a282010-08-23 23:25:46 +00001293 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001294
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001295 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001296}
1297
Richard Trieu451a5db2012-04-30 18:01:30 +00001298namespace {
1299 // This visitor will traverse a conditional statement and store all
1300 // the evaluated decls into a vector. Simple is set to true if none
1301 // of the excluded constructs are used.
1302 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001303 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001304 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001305 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001306 public:
1307 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001308
Craig Topper4dd9b432014-08-17 23:49:53 +00001309 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001310 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001311 Inherited(S.Context),
1312 Decls(Decls),
1313 Ranges(Ranges),
1314 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001315
Richard Trieu9d228802013-05-31 22:46:45 +00001316 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001317
Richard Trieu9d228802013-05-31 22:46:45 +00001318 // Replaces the method in EvaluatedExprVisitor.
1319 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001320 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001321 }
1322
1323 // Any Stmt not whitelisted will cause the condition to be marked complex.
1324 void VisitStmt(Stmt *S) {
1325 Simple = false;
1326 }
1327
1328 void VisitBinaryOperator(BinaryOperator *E) {
1329 Visit(E->getLHS());
1330 Visit(E->getRHS());
1331 }
1332
1333 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001334 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001335 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001336
Richard Trieu9d228802013-05-31 22:46:45 +00001337 void VisitUnaryOperator(UnaryOperator *E) {
1338 // Skip checking conditionals with derefernces.
1339 if (E->getOpcode() == UO_Deref)
1340 Simple = false;
1341 else
1342 Visit(E->getSubExpr());
1343 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001344
Richard Trieu9d228802013-05-31 22:46:45 +00001345 void VisitConditionalOperator(ConditionalOperator *E) {
1346 Visit(E->getCond());
1347 Visit(E->getTrueExpr());
1348 Visit(E->getFalseExpr());
1349 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001350
Richard Trieu9d228802013-05-31 22:46:45 +00001351 void VisitParenExpr(ParenExpr *E) {
1352 Visit(E->getSubExpr());
1353 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001354
Richard Trieu9d228802013-05-31 22:46:45 +00001355 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1356 Visit(E->getOpaqueValue()->getSourceExpr());
1357 Visit(E->getFalseExpr());
1358 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001359
Richard Trieu9d228802013-05-31 22:46:45 +00001360 void VisitIntegerLiteral(IntegerLiteral *E) { }
1361 void VisitFloatingLiteral(FloatingLiteral *E) { }
1362 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1363 void VisitCharacterLiteral(CharacterLiteral *E) { }
1364 void VisitGNUNullExpr(GNUNullExpr *E) { }
1365 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001366
Richard Trieu9d228802013-05-31 22:46:45 +00001367 void VisitDeclRefExpr(DeclRefExpr *E) {
1368 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1369 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001370
Richard Trieu9d228802013-05-31 22:46:45 +00001371 Ranges.push_back(E->getSourceRange());
1372
1373 Decls.insert(VD);
1374 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001375
1376 }; // end class DeclExtractor
1377
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001378 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001379 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001380 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001381 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001382 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001383
Richard Trieu9d228802013-05-31 22:46:45 +00001384 public:
1385 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001386
Craig Topper4dd9b432014-08-17 23:49:53 +00001387 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001388 Stmt *Statement) :
1389 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1390 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001391
Richard Trieu9d228802013-05-31 22:46:45 +00001392 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001393 }
1394
Richard Trieu9d228802013-05-31 22:46:45 +00001395 void VisitReturnStmt(ReturnStmt *S) {
1396 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001397 }
1398
Richard Trieu9d228802013-05-31 22:46:45 +00001399 void VisitBreakStmt(BreakStmt *S) {
1400 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001401 }
1402
Richard Trieu9d228802013-05-31 22:46:45 +00001403 void VisitGotoStmt(GotoStmt *S) {
1404 FoundDecl = true;
1405 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001406
Richard Trieu9d228802013-05-31 22:46:45 +00001407 void VisitCastExpr(CastExpr *E) {
1408 if (E->getCastKind() == CK_LValueToRValue)
1409 CheckLValueToRValueCast(E->getSubExpr());
1410 else
1411 Visit(E->getSubExpr());
1412 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001413
Richard Trieu9d228802013-05-31 22:46:45 +00001414 void CheckLValueToRValueCast(Expr *E) {
1415 E = E->IgnoreParenImpCasts();
1416
1417 if (isa<DeclRefExpr>(E)) {
1418 return;
1419 }
1420
1421 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1422 Visit(CO->getCond());
1423 CheckLValueToRValueCast(CO->getTrueExpr());
1424 CheckLValueToRValueCast(CO->getFalseExpr());
1425 return;
1426 }
1427
1428 if (BinaryConditionalOperator *BCO =
1429 dyn_cast<BinaryConditionalOperator>(E)) {
1430 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1431 CheckLValueToRValueCast(BCO->getFalseExpr());
1432 return;
1433 }
1434
1435 Visit(E);
1436 }
1437
1438 void VisitDeclRefExpr(DeclRefExpr *E) {
1439 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1440 if (Decls.count(VD))
1441 FoundDecl = true;
1442 }
1443
Steven Wu92910f62016-03-10 02:02:48 +00001444 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1445 // Only need to visit the semantics for POE.
1446 // SyntaticForm doesn't really use the Decal.
1447 for (auto *S : POE->semantics()) {
1448 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1449 // Look past the OVE into the expression it binds.
1450 Visit(OVE->getSourceExpr());
1451 else
1452 Visit(S);
1453 }
1454 }
1455
Richard Trieu9d228802013-05-31 22:46:45 +00001456 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001457
1458 }; // end class DeclMatcher
1459
1460 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1461 Expr *Third, Stmt *Body) {
1462 // Condition is empty
1463 if (!Second) return;
1464
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001465 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1466 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001467 return;
1468
1469 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1470 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001471 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001472 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001473 DE.Visit(Second);
1474
1475 // Don't analyze complex conditionals.
1476 if (!DE.isSimple()) return;
1477
1478 // No decls found.
1479 if (Decls.size() == 0) return;
1480
Richard Trieu0030f1d2012-05-04 03:01:54 +00001481 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001482 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1483 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001484 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001485 if ((*I)->getType().isVolatileQualified() ||
1486 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001487
1488 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1489 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1490 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1491 return;
1492
1493 // Load decl names into diagnostic.
1494 if (Decls.size() > 4)
1495 PDiag << 0;
1496 else {
1497 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001498 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1499 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001500 I != E; ++I)
1501 PDiag << (*I)->getDeclName();
1502 }
1503
1504 // Load SourceRanges into diagnostic if there is room.
1505 // Otherwise, load the SourceRange of the conditional expression.
1506 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001507 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001508 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001509 I != E; ++I)
1510 PDiag << *I;
1511 else
1512 PDiag << Second->getSourceRange();
1513
1514 S.Diag(Ranges.begin()->getBegin(), PDiag);
1515 }
1516
Richard Trieu4e7c9622013-08-06 21:31:54 +00001517 // If Statement is an incemement or decrement, return true and sets the
1518 // variables Increment and DRE.
1519 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1520 DeclRefExpr *&DRE) {
1521 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1522 switch (UO->getOpcode()) {
1523 default: return false;
1524 case UO_PostInc:
1525 case UO_PreInc:
1526 Increment = true;
1527 break;
1528 case UO_PostDec:
1529 case UO_PreDec:
1530 Increment = false;
1531 break;
1532 }
1533 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1534 return DRE;
1535 }
1536
1537 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1538 FunctionDecl *FD = Call->getDirectCallee();
1539 if (!FD || !FD->isOverloadedOperator()) return false;
1540 switch (FD->getOverloadedOperator()) {
1541 default: return false;
1542 case OO_PlusPlus:
1543 Increment = true;
1544 break;
1545 case OO_MinusMinus:
1546 Increment = false;
1547 break;
1548 }
1549 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1550 return DRE;
1551 }
1552
1553 return false;
1554 }
1555
Serge Pavlov09f99242014-01-23 15:05:00 +00001556 // A visitor to determine if a continue or break statement is a
1557 // subexpression.
1558 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1559 SourceLocation BreakLoc;
1560 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001561 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001562 BreakContinueFinder(Sema &S, Stmt* Body) :
1563 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001564 Visit(Body);
1565 }
1566
Serge Pavlov09f99242014-01-23 15:05:00 +00001567 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001568
1569 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001570 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001571 }
1572
Serge Pavlov09f99242014-01-23 15:05:00 +00001573 void VisitBreakStmt(BreakStmt* E) {
1574 BreakLoc = E->getBreakLoc();
1575 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001576
Serge Pavlov09f99242014-01-23 15:05:00 +00001577 bool ContinueFound() { return ContinueLoc.isValid(); }
1578 bool BreakFound() { return BreakLoc.isValid(); }
1579 SourceLocation GetContinueLoc() { return ContinueLoc; }
1580 SourceLocation GetBreakLoc() { return BreakLoc; }
1581
1582 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001583
1584 // Emit a warning when a loop increment/decrement appears twice per loop
1585 // iteration. The conditions which trigger this warning are:
1586 // 1) The last statement in the loop body and the third expression in the
1587 // for loop are both increment or both decrement of the same variable
1588 // 2) No continue statements in the loop body.
1589 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1590 // Return when there is nothing to check.
1591 if (!Body || !Third) return;
1592
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001593 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1594 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001595 return;
1596
1597 // Get the last statement from the loop body.
1598 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1599 if (!CS || CS->body_empty()) return;
1600 Stmt *LastStmt = CS->body_back();
1601 if (!LastStmt) return;
1602
1603 bool LoopIncrement, LastIncrement;
1604 DeclRefExpr *LoopDRE, *LastDRE;
1605
1606 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1607 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1608
1609 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001610 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001611 if (LoopIncrement != LastIncrement ||
1612 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1613
Serge Pavlov09f99242014-01-23 15:05:00 +00001614 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001615
1616 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1617 << LastDRE->getDecl() << LastIncrement;
1618 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1619 << LoopIncrement;
1620 }
1621
Richard Trieu451a5db2012-04-30 18:01:30 +00001622} // end namespace
1623
Serge Pavlov09f99242014-01-23 15:05:00 +00001624
1625void Sema::CheckBreakContinueBinding(Expr *E) {
1626 if (!E || getLangOpts().CPlusPlus)
1627 return;
1628 BreakContinueFinder BCFinder(*this, E);
1629 Scope *BreakParent = CurScope->getBreakParent();
1630 if (BCFinder.BreakFound() && BreakParent) {
1631 if (BreakParent->getFlags() & Scope::SwitchScope) {
1632 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1633 } else {
1634 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1635 << "break";
1636 }
1637 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1638 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1639 << "continue";
1640 }
1641}
1642
John McCalldadc5752010-08-24 06:29:42 +00001643StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001644Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001645 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001646 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001647 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001648 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001649 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001650 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1651 // declare identifiers for objects having storage class 'auto' or
1652 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001653 for (auto *DI : DS->decls()) {
1654 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001655 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001656 VD = nullptr;
1657 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001658 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1659 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001660 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001661 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001662 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001663 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001664
Serge Pavlov09f99242014-01-23 15:05:00 +00001665 CheckBreakContinueBinding(second.get());
1666 CheckBreakContinueBinding(third.get());
1667
Richard Trieu451a5db2012-04-30 18:01:30 +00001668 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001669 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001670
John McCalldadc5752010-08-24 06:29:42 +00001671 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001672 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001673 if (secondVar) {
1674 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001675 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001676 SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001677 if (SecondResult.isInvalid())
1678 return StmtError();
1679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680
Richard Trieufaca2d82016-02-18 23:58:40 +00001681 if (SecondResult.get() &&
1682 !Diags.isIgnored(diag::warn_comma_operator,
1683 SecondResult.get()->getExprLoc()))
1684 CommaVisitor(*this).Visit(SecondResult.get());
1685
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001686 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001687
Anders Carlsson1682af52009-08-01 01:39:59 +00001688 DiagnoseUnusedExprResult(First);
1689 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001690 DiagnoseUnusedExprResult(Body);
1691
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001692 if (isa<NullStmt>(Body))
1693 getCurCompoundScope().setHasEmptyLoopBodies();
1694
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001695 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1696 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001697}
1698
John McCall34376a62010-12-04 03:47:34 +00001699/// In an Objective C collection iteration statement:
1700/// for (x in y)
1701/// x can be an arbitrary l-value expression. Bind it up as a
1702/// full-expression.
1703StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001704 // Reduce placeholder expressions here. Note that this rejects the
1705 // use of pseudo-object l-values in this position.
1706 ExprResult result = CheckPlaceholderExpr(E);
1707 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001708 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001709
Richard Smith945f8d32013-01-14 22:39:08 +00001710 ExprResult FullExpr = ActOnFinishFullExpr(E);
1711 if (FullExpr.isInvalid())
1712 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001713 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001714}
1715
John McCall53848232011-07-27 01:07:15 +00001716ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001717Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1718 if (!collection)
1719 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001720
Kaelyn Takata15867822014-11-21 18:48:04 +00001721 ExprResult result = CorrectDelayedTyposInExpr(collection);
1722 if (!result.isUsable())
1723 return ExprError();
1724 collection = result.get();
1725
John McCall53848232011-07-27 01:07:15 +00001726 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001727 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001728
1729 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001730 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001731 if (result.isInvalid())
1732 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001733 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001734
1735 // The operand needs to have object-pointer type.
1736 // TODO: should we do a contextual conversion?
1737 const ObjCObjectPointerType *pointerType =
1738 collection->getType()->getAs<ObjCObjectPointerType>();
1739 if (!pointerType)
1740 return Diag(forLoc, diag::err_collection_expr_type)
1741 << collection->getType() << collection->getSourceRange();
1742
1743 // Check that the operand provides
1744 // - countByEnumeratingWithState:objects:count:
1745 const ObjCObjectType *objectType = pointerType->getObjectType();
1746 ObjCInterfaceDecl *iface = objectType->getInterface();
1747
1748 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001749 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001750 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001751 (getLangOpts().ObjCAutoRefCount
1752 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1753 diag::err_arc_collection_forward, collection)
1754 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001755 // Otherwise, if we have any useful type information, check that
1756 // the type declares the appropriate method.
1757 } else if (iface || !objectType->qual_empty()) {
1758 IdentifierInfo *selectorIdents[] = {
1759 &Context.Idents.get("countByEnumeratingWithState"),
1760 &Context.Idents.get("objects"),
1761 &Context.Idents.get("count")
1762 };
1763 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1764
Craig Topperc3ec1492014-05-26 06:22:03 +00001765 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001766
1767 // If there's an interface, look in both the public and private APIs.
1768 if (iface) {
1769 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001770 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001771 }
1772
1773 // Also check protocol qualifiers.
1774 if (!method)
1775 method = LookupMethodInQualifiedType(selector, pointerType,
1776 /*instance*/ true);
1777
1778 // If we didn't find it anywhere, give up.
1779 if (!method) {
1780 Diag(forLoc, diag::warn_collection_expr_type)
1781 << collection->getType() << selector << collection->getSourceRange();
1782 }
1783
1784 // TODO: check for an incompatible signature?
1785 }
1786
1787 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001788 return collection;
John McCall53848232011-07-27 01:07:15 +00001789}
1790
John McCalldadc5752010-08-24 06:29:42 +00001791StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001792Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001793 Stmt *First, Expr *collection,
1794 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001795
1796 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001797 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001798
Fariborz Jahanian93977672008-01-10 20:33:58 +00001799 if (First) {
1800 QualType FirstType;
1801 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001802 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001803 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1804 diag::err_toomany_element_decls));
1805
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001806 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1807 if (!D || D->isInvalidDecl())
1808 return StmtError();
1809
John McCall31168b02011-06-15 23:02:42 +00001810 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001811 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1812 // declare identifiers for objects having storage class 'auto' or
1813 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001814 if (!D->hasLocalStorage())
1815 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001816 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001817
1818 // If the type contained 'auto', deduce the 'auto' to 'id'.
1819 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001820 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1821 VK_RValue);
1822 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001823 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1824 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001825 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001826 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001827 D->setInvalidDecl();
1828 return StmtError();
1829 }
1830
Richard Smith061f1e22013-04-30 21:23:01 +00001831 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001832
1833 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001834 SourceLocation Loc =
1835 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001836 Diag(Loc, diag::warn_auto_var_is_id)
1837 << D->getDeclName();
1838 }
1839 }
1840
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001841 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001842 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001843 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001844 return StmtError(Diag(First->getLocStart(),
1845 diag::err_selector_element_not_lvalue)
1846 << First->getSourceRange());
1847
Mike Stump11289f42009-09-09 15:08:12 +00001848 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001849 if (FirstType.isConstQualified())
1850 Diag(ForLoc, diag::err_selector_element_const_type)
1851 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001852 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001853 if (!FirstType->isDependentType() &&
1854 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001855 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001856 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1857 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001858 }
Chad Rosier02a84392012-08-10 17:56:09 +00001859
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001860 if (CollectionExprResult.isInvalid())
1861 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001862
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001863 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001864 if (CollectionExprResult.isInvalid())
1865 return StmtError();
1866
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001867 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1868 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001869}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001870
Richard Smith02e85f32011-04-14 22:09:26 +00001871/// Finish building a variable declaration for a for-range statement.
1872/// \return true if an error occurs.
1873static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001874 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001875 if (Decl->getType()->isUndeducedType()) {
1876 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1877 if (!Res.isUsable()) {
1878 Decl->setInvalidDecl();
1879 return true;
1880 }
1881 Init = Res.get();
1882 }
1883
Richard Smith02e85f32011-04-14 22:09:26 +00001884 // Deduce the type for the iterator variable now rather than leaving it to
1885 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001886 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001887 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001888 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001889 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001890 SemaRef.Diag(Loc, DiagID) << Init->getType();
1891 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001892 Decl->setInvalidDecl();
1893 return true;
1894 }
Richard Smith061f1e22013-04-30 21:23:01 +00001895 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001896
John McCall31168b02011-06-15 23:02:42 +00001897 // In ARC, infer lifetime.
1898 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1899 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001900 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001901 SemaRef.inferObjCARCLifetime(Decl))
1902 Decl->setInvalidDecl();
1903
Richard Smith02e85f32011-04-14 22:09:26 +00001904 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1905 /*TypeMayContainAuto=*/false);
1906 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001907 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001908 return false;
1909}
1910
Sam Panzer0f384432012-08-21 00:52:01 +00001911namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001912// An enum to represent whether something is dealing with a call to begin()
1913// or a call to end() in a range-based for loop.
1914enum BeginEndFunction {
1915 BEF_begin,
1916 BEF_end
1917};
Sam Panzer0f384432012-08-21 00:52:01 +00001918
Richard Smith02e85f32011-04-14 22:09:26 +00001919/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001920/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001921/// nor from the diagnostics produced when analysing the implicit expressions
1922/// required in a for-range statement.
1923void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001924 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001925 CallExpr *CE = dyn_cast<CallExpr>(E);
1926 if (!CE)
1927 return;
1928 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1929 if (!D)
1930 return;
1931 SourceLocation Loc = D->getLocation();
1932
1933 std::string Description;
1934 bool IsTemplate = false;
1935 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1936 Description = SemaRef.getTemplateArgumentBindingsText(
1937 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1938 IsTemplate = true;
1939 }
1940
1941 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1942 << BEF << IsTemplate << Description << E->getType();
1943}
1944
Sam Panzer0f384432012-08-21 00:52:01 +00001945/// Build a variable declaration for a for-range statement.
1946VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1947 QualType Type, const char *Name) {
1948 DeclContext *DC = SemaRef.CurContext;
1949 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1950 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1951 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001952 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001953 Decl->setImplicit();
1954 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001955}
1956
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001957}
Richard Smith02e85f32011-04-14 22:09:26 +00001958
Fariborz Jahanian00213472012-07-06 19:04:04 +00001959static bool ObjCEnumerationCollection(Expr *Collection) {
1960 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001961 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001962}
1963
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001964/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001965///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001966/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001967/// A range-based for statement is equivalent to
1968///
1969/// {
1970/// auto && __range = range-init;
1971/// for ( auto __begin = begin-expr,
1972/// __end = end-expr;
1973/// __begin != __end;
1974/// ++__begin ) {
1975/// for-range-declaration = *__begin;
1976/// statement
1977/// }
1978/// }
1979///
1980/// The body of the loop is not available yet, since it cannot be analysed until
1981/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001982StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1983 SourceLocation CoawaitLoc, Stmt *First,
1984 SourceLocation ColonLoc, Expr *Range,
1985 SourceLocation RParenLoc,
1986 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001987 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001988 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001989
Richard Smith3249fed2013-08-21 01:40:36 +00001990 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001991 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001992
1993 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1994 assert(DS && "first part of for range not a decl stmt");
1995
1996 if (!DS->isSingleDecl()) {
1997 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1998 return StmtError();
1999 }
Richard Smith02e85f32011-04-14 22:09:26 +00002000
Richard Smith3249fed2013-08-21 01:40:36 +00002001 Decl *LoopVar = DS->getSingleDecl();
2002 if (LoopVar->isInvalidDecl() || !Range ||
2003 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2004 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002005 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002006 }
Richard Smith02e85f32011-04-14 22:09:26 +00002007
Richard Smithcfd53b42015-10-22 06:13:50 +00002008 // Coroutines: 'for co_await' implicitly co_awaits its range.
2009 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002010 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00002011 if (Coawait.isInvalid()) return StmtError();
2012 Range = Coawait.get();
2013 }
2014
Richard Smith02e85f32011-04-14 22:09:26 +00002015 // Build auto && __range = range-init
2016 SourceLocation RangeLoc = Range->getLocStart();
2017 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2018 Context.getAutoRRefDeductType(),
2019 "__range");
2020 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002021 diag::err_for_range_deduction_failure)) {
2022 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002023 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002024 }
Richard Smith02e85f32011-04-14 22:09:26 +00002025
2026 // Claim the type doesn't contain auto: we've already done the checking.
2027 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002028 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00002029 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002030 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002031 if (RangeDecl.isInvalid()) {
2032 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002033 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002034 }
Richard Smith02e85f32011-04-14 22:09:26 +00002035
Richard Smithcfd53b42015-10-22 06:13:50 +00002036 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002037 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2038 /*Cond=*/nullptr, /*Inc=*/nullptr,
2039 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002040}
2041
2042/// \brief Create the initialization, compare, and increment steps for
2043/// the range-based for loop expression.
2044/// This function does not handle array-based for loops,
2045/// which are created in Sema::BuildCXXForRangeStmt.
2046///
2047/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2048/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2049/// CandidateSet and BEF are set and some non-success value is returned on
2050/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002051static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002052 Expr *BeginRange, Expr *EndRange,
2053 QualType RangeType,
2054 VarDecl *BeginVar,
2055 VarDecl *EndVar,
2056 SourceLocation ColonLoc,
2057 OverloadCandidateSet *CandidateSet,
2058 ExprResult *BeginExpr,
2059 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002060 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002061 DeclarationNameInfo BeginNameInfo(
2062 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2063 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2064 ColonLoc);
2065
2066 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2067 Sema::LookupMemberName);
2068 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2069
2070 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2071 // - if _RangeT is a class type, the unqualified-ids begin and end are
2072 // looked up in the scope of class _RangeT as if by class member access
2073 // lookup (3.4.5), and if either (or both) finds at least one
2074 // declaration, begin-expr and end-expr are __range.begin() and
2075 // __range.end(), respectively;
2076 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2077 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2078
2079 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2080 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002081 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002082
2083 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2084 << RangeLoc << BeginRange->getType() << *BEF;
2085 return Sema::FRS_DiagnosticIssued;
2086 }
2087 } else {
2088 // - otherwise, begin-expr and end-expr are begin(__range) and
2089 // end(__range), respectively, where begin and end are looked up with
2090 // argument-dependent lookup (3.4.2). For the purposes of this name
2091 // lookup, namespace std is an associated namespace.
2092
2093 }
2094
Richard Smith9f690bd2015-10-27 06:02:45 +00002095 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002096 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002097 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002098 BeginMemberLookup, CandidateSet,
2099 BeginRange, BeginExpr);
2100
Richard Smith9f690bd2015-10-27 06:02:45 +00002101 if (RangeStatus != Sema::FRS_Success) {
2102 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2103 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2104 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002105 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002106 }
Sam Panzer0f384432012-08-21 00:52:01 +00002107 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2108 diag::err_for_range_iter_deduction_failure)) {
2109 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2110 return Sema::FRS_DiagnosticIssued;
2111 }
2112
Richard Smith9f690bd2015-10-27 06:02:45 +00002113 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002114 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002115 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002116 EndMemberLookup, CandidateSet,
2117 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002118 if (RangeStatus != Sema::FRS_Success) {
2119 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2120 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2121 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002122 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002123 }
Sam Panzer0f384432012-08-21 00:52:01 +00002124 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2125 diag::err_for_range_iter_deduction_failure)) {
2126 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2127 return Sema::FRS_DiagnosticIssued;
2128 }
2129 return Sema::FRS_Success;
2130}
2131
2132/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002133/// If the attempt fails, this function will return a valid, null StmtResult
2134/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002135static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2136 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002137 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002138 Stmt *LoopVarDecl,
2139 SourceLocation ColonLoc,
2140 Expr *Range,
2141 SourceLocation RangeLoc,
2142 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002143 // Determine whether we can rebuild the for-range statement with a
2144 // dereferenced range expression.
2145 ExprResult AdjustedRange;
2146 {
2147 Sema::SFINAETrap Trap(SemaRef);
2148
2149 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2150 if (AdjustedRange.isInvalid())
2151 return StmtResult();
2152
Richard Smith9f690bd2015-10-27 06:02:45 +00002153 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2154 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2155 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002156 if (SR.isInvalid())
2157 return StmtResult();
2158 }
2159
2160 // The attempt to dereference worked well enough that it could produce a valid
2161 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2162 // case there are any other (non-fatal) problems with it.
2163 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2164 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002165 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2166 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002167 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002168}
2169
Richard Smith3249fed2013-08-21 01:40:36 +00002170namespace {
2171/// RAII object to automatically invalidate a declaration if an error occurs.
2172struct InvalidateOnErrorScope {
2173 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2174 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2175 ~InvalidateOnErrorScope() {
2176 if (Enabled && Trap.hasErrorOccurred())
2177 D->setInvalidDecl();
2178 }
2179
2180 DiagnosticErrorTrap Trap;
2181 Decl *D;
2182 bool Enabled;
2183};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002184}
Richard Smith3249fed2013-08-21 01:40:36 +00002185
Richard Smitha05b3b52012-09-20 21:52:32 +00002186/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002187StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002188Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002189 SourceLocation ColonLoc, Stmt *RangeDecl,
2190 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002191 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002192 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002193 // FIXME: This should not be used during template instantiation. We should
2194 // pick up the set of unqualified lookup results for the != and + operators
2195 // in the initial parse.
2196 //
2197 // Testcase (accepts-invalid):
2198 // template<typename T> void f() { for (auto x : T()) {} }
2199 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2200 // bool operator!=(N::X, N::X); void operator++(N::X);
2201 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002202 Scope *S = getCurScope();
2203
2204 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2205 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2206 QualType RangeVarType = RangeVar->getType();
2207
2208 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2209 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2210
Richard Smith3249fed2013-08-21 01:40:36 +00002211 // If we hit any errors, mark the loop variable as invalid if its type
2212 // contains 'auto'.
2213 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2214 LoopVar->getType()->isUndeducedType());
2215
Richard Smith01694c32016-03-20 10:33:40 +00002216 StmtResult BeginDeclStmt = Begin;
2217 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002218 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2219
Richard Smith27d807c2013-04-30 13:56:41 +00002220 if (RangeVarType->isDependentType()) {
2221 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002222 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002223
2224 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2225 // them in properly when we instantiate the loop.
2226 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2227 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Richard Smith01694c32016-03-20 10:33:40 +00002228 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002229 SourceLocation RangeLoc = RangeVar->getLocation();
2230
Ted Kremenekbed648e2011-10-10 22:36:28 +00002231 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2232
2233 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2234 VK_LValue, ColonLoc);
2235 if (BeginRangeRef.isInvalid())
2236 return StmtError();
2237
2238 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2239 VK_LValue, ColonLoc);
2240 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002241 return StmtError();
2242
2243 QualType AutoType = Context.getAutoDeductType();
2244 Expr *Range = RangeVar->getInit();
2245 if (!Range)
2246 return StmtError();
2247 QualType RangeType = Range->getType();
2248
2249 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002250 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002251 return StmtError();
2252
2253 // Build auto __begin = begin-expr, __end = end-expr.
2254 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2255 "__begin");
2256 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2257 "__end");
2258
2259 // Build begin-expr and end-expr and attach to __begin and __end variables.
2260 ExprResult BeginExpr, EndExpr;
2261 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2262 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2263 // __range + __bound, respectively, where __bound is the array bound. If
2264 // _RangeT is an array of unknown size or an array of incomplete type,
2265 // the program is ill-formed;
2266
2267 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002268 BeginExpr = BeginRangeRef;
2269 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002270 diag::err_for_range_iter_deduction_failure)) {
2271 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2272 return StmtError();
2273 }
2274
2275 // Find the array bound.
2276 ExprResult BoundExpr;
2277 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002278 BoundExpr = IntegerLiteral::Create(
2279 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002280 else if (const VariableArrayType *VAT =
2281 dyn_cast<VariableArrayType>(UnqAT))
2282 BoundExpr = VAT->getSizeExpr();
2283 else {
2284 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2285 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002286 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002287 }
2288
2289 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002290 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002291 BoundExpr.get());
2292 if (EndExpr.isInvalid())
2293 return StmtError();
2294 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2295 diag::err_for_range_iter_deduction_failure)) {
2296 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2297 return StmtError();
2298 }
2299 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002300 OverloadCandidateSet CandidateSet(RangeLoc,
2301 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002302 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002303 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002304 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002305 EndRangeRef.get(), RangeType,
2306 BeginVar, EndVar, ColonLoc, &CandidateSet,
2307 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002308
Richard Smitha05b3b52012-09-20 21:52:32 +00002309 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002310 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002311 // If the range is being built from an array parameter, emit a
2312 // a diagnostic that it is being treated as a pointer.
2313 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2314 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2315 QualType ArrayTy = PVD->getOriginalType();
2316 QualType PointerTy = PVD->getType();
2317 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2318 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2319 << RangeLoc << PVD << ArrayTy << PointerTy;
2320 Diag(PVD->getLocation(), diag::note_declared_at);
2321 return StmtError();
2322 }
2323 }
2324 }
2325
2326 // If building the range failed, try dereferencing the range expression
2327 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002328 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002329 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002330 LoopVarDecl, ColonLoc,
2331 Range, RangeLoc,
2332 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002333 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002334 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002335 }
2336
Sam Panzer0f384432012-08-21 00:52:01 +00002337 // Otherwise, emit diagnostics if we haven't already.
2338 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002339 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002340 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2341 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002342 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002343 }
2344 // Return an error if no fix was discovered.
2345 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002346 return StmtError();
2347 }
2348
Sam Panzer0f384432012-08-21 00:52:01 +00002349 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2350 "invalid range expression in for loop");
2351
2352 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002353 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002354 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2355 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002356 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2357 ? diag::warn_for_range_begin_end_types_differ
2358 : diag::ext_for_range_begin_end_types_differ)
2359 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002360 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2361 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2362 }
2363
Richard Smith01694c32016-03-20 10:33:40 +00002364 BeginDeclStmt =
2365 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2366 EndDeclStmt =
2367 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002368
Ted Kremenekbed648e2011-10-10 22:36:28 +00002369 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2370 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002371 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002372 if (BeginRef.isInvalid())
2373 return StmtError();
2374
Richard Smith02e85f32011-04-14 22:09:26 +00002375 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2376 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002377 if (EndRef.isInvalid())
2378 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002379
2380 // Build and check __begin != __end expression.
2381 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2382 BeginRef.get(), EndRef.get());
2383 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2384 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2385 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002386 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2387 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002388 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2389 if (!Context.hasSameType(BeginType, EndType))
2390 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2391 return StmtError();
2392 }
2393
2394 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002395 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2396 VK_LValue, ColonLoc);
2397 if (BeginRef.isInvalid())
2398 return StmtError();
2399
Richard Smith02e85f32011-04-14 22:09:26 +00002400 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002401 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002402 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002403 if (!IncrExpr.isInvalid())
2404 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002405 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002406 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2407 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002408 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2409 return StmtError();
2410 }
2411
2412 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002413 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2414 VK_LValue, ColonLoc);
2415 if (BeginRef.isInvalid())
2416 return StmtError();
2417
Richard Smith02e85f32011-04-14 22:09:26 +00002418 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2419 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002420 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2421 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002422 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2423 return StmtError();
2424 }
2425
Richard Smitha05b3b52012-09-20 21:52:32 +00002426 // Attach *__begin as initializer for VD. Don't touch it if we're just
2427 // trying to determine whether this would be a valid range.
2428 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002429 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2430 /*TypeMayContainAuto=*/true);
2431 if (LoopVar->isInvalidDecl())
2432 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2433 }
2434 }
2435
Richard Smitha05b3b52012-09-20 21:52:32 +00002436 // Don't bother to actually allocate the result if we're just trying to
2437 // determine whether it would be valid.
2438 if (Kind == BFRK_Check)
2439 return StmtResult();
2440
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002441 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002442 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2443 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002444 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2445 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002446}
2447
Chad Rosier02a84392012-08-10 17:56:09 +00002448/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002449/// statement.
2450StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2451 if (!S || !B)
2452 return StmtError();
2453 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002454
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002455 ForStmt->setBody(B);
2456 return S;
2457}
2458
Richard Trieu3e1d4832015-04-13 22:08:55 +00002459// Warn when the loop variable is a const reference that creates a copy.
2460// Suggest using the non-reference type for copies. If a copy can be prevented
2461// suggest the const reference type that would do so.
2462// For instance, given "for (const &Foo : Range)", suggest
2463// "for (const Foo : Range)" to denote a copy is made for the loop. If
2464// possible, also suggest "for (const &Bar : Range)" if this type prevents
2465// the copy altogether.
2466static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2467 const VarDecl *VD,
2468 QualType RangeInitType) {
2469 const Expr *InitExpr = VD->getInit();
2470 if (!InitExpr)
2471 return;
2472
2473 QualType VariableType = VD->getType();
2474
2475 const MaterializeTemporaryExpr *MTE =
2476 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2477
2478 // No copy made.
2479 if (!MTE)
2480 return;
2481
2482 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2483
2484 // Searching for either UnaryOperator for dereference of a pointer or
2485 // CXXOperatorCallExpr for handling iterators.
2486 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2487 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2488 E = CCE->getArg(0);
2489 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2490 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2491 E = ME->getBase();
2492 } else {
2493 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2494 E = MTE->GetTemporaryExpr();
2495 }
2496 E = E->IgnoreImpCasts();
2497 }
2498
2499 bool ReturnsReference = false;
2500 if (isa<UnaryOperator>(E)) {
2501 ReturnsReference = true;
2502 } else {
2503 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2504 const FunctionDecl *FD = Call->getDirectCallee();
2505 QualType ReturnType = FD->getReturnType();
2506 ReturnsReference = ReturnType->isReferenceType();
2507 }
2508
2509 if (ReturnsReference) {
2510 // Loop variable creates a temporary. Suggest either to go with
2511 // non-reference loop variable to indiciate a copy is made, or
2512 // the correct time to bind a const reference.
2513 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2514 << VD << VariableType << E->getType();
2515 QualType NonReferenceType = VariableType.getNonReferenceType();
2516 NonReferenceType.removeLocalConst();
2517 QualType NewReferenceType =
2518 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2519 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2520 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2521 } else {
2522 // The range always returns a copy, so a temporary is always created.
2523 // Suggest removing the reference from the loop variable.
2524 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2525 << VD << RangeInitType;
2526 QualType NonReferenceType = VariableType.getNonReferenceType();
2527 NonReferenceType.removeLocalConst();
2528 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2529 << NonReferenceType << VD->getSourceRange();
2530 }
2531}
2532
2533// Warns when the loop variable can be changed to a reference type to
2534// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2535// "for (const Foo &x : Range)" if this form does not make a copy.
2536static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2537 const VarDecl *VD) {
2538 const Expr *InitExpr = VD->getInit();
2539 if (!InitExpr)
2540 return;
2541
2542 QualType VariableType = VD->getType();
2543
2544 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2545 if (!CE->getConstructor()->isCopyConstructor())
2546 return;
2547 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2548 if (CE->getCastKind() != CK_LValueToRValue)
2549 return;
2550 } else {
2551 return;
2552 }
2553
2554 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2555 // should be emitted. Also, only ignore POD types with trivial copy
2556 // constructors.
2557 if (VariableType.isPODType(SemaRef.Context))
2558 return;
2559
2560 // Suggest changing from a const variable to a const reference variable
2561 // if doing so will prevent a copy.
2562 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2563 << VD << VariableType << InitExpr->getType();
2564 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2565 << SemaRef.Context.getLValueReferenceType(VariableType)
2566 << VD->getSourceRange();
2567}
2568
2569/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2570/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2571/// using "const foo x" to show that a copy is made
2572/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2573/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2574/// prevent the copy.
2575/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2576/// Suggest "const foo &x" to prevent the copy.
2577static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2578 const CXXForRangeStmt *ForStmt) {
2579 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2580 ForStmt->getLocStart()) &&
2581 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2582 ForStmt->getLocStart()) &&
2583 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2584 ForStmt->getLocStart())) {
2585 return;
2586 }
2587
2588 const VarDecl *VD = ForStmt->getLoopVariable();
2589 if (!VD)
2590 return;
2591
2592 QualType VariableType = VD->getType();
2593
2594 if (VariableType->isIncompleteType())
2595 return;
2596
2597 const Expr *InitExpr = VD->getInit();
2598 if (!InitExpr)
2599 return;
2600
2601 if (VariableType->isReferenceType()) {
2602 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2603 ForStmt->getRangeInit()->getType());
2604 } else if (VariableType.isConstQualified()) {
2605 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2606 }
2607}
2608
Richard Smith02e85f32011-04-14 22:09:26 +00002609/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2610/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2611/// body cannot be performed until after the type of the range variable is
2612/// determined.
2613StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2614 if (!S || !B)
2615 return StmtError();
2616
Fariborz Jahanian00213472012-07-06 19:04:04 +00002617 if (isa<ObjCForCollectionStmt>(S))
2618 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002619
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002620 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2621 ForStmt->setBody(B);
2622
2623 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2624 diag::warn_empty_range_based_for_body);
2625
Richard Trieu3e1d4832015-04-13 22:08:55 +00002626 DiagnoseForRangeVariableCopies(*this, ForStmt);
2627
Richard Smith02e85f32011-04-14 22:09:26 +00002628 return S;
2629}
2630
Chris Lattnercab02a62011-02-17 20:34:02 +00002631StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2632 SourceLocation LabelLoc,
2633 LabelDecl *TheDecl) {
2634 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002635 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002636 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002637}
Chris Lattner1c310502007-05-31 06:00:00 +00002638
John McCalldadc5752010-08-24 06:29:42 +00002639StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002640Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002641 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002642 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002643 if (!E->isTypeDependent()) {
2644 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002645 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002646 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002647 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002648 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2649 if (ExprRes.isInvalid())
2650 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002651 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002652 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002653 return StmtError();
2654 }
John McCalla95172b2010-08-01 00:26:45 +00002655
Richard Smith945f8d32013-01-14 22:39:08 +00002656 ExprResult ExprRes = ActOnFinishFullExpr(E);
2657 if (ExprRes.isInvalid())
2658 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002659 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002660
John McCallaab3e412010-08-25 08:40:02 +00002661 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002662
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002663 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002664}
2665
Nico Weberd64657f2015-03-09 02:47:59 +00002666static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2667 const Scope &DestScope) {
2668 if (!S.CurrentSEHFinally.empty() &&
2669 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2670 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2671 }
2672}
2673
John McCalldadc5752010-08-24 06:29:42 +00002674StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002675Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002676 Scope *S = CurScope->getContinueParent();
2677 if (!S) {
2678 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002679 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002680 }
Nico Weberd64657f2015-03-09 02:47:59 +00002681 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002682
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002683 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002684}
2685
John McCalldadc5752010-08-24 06:29:42 +00002686StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002687Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002688 Scope *S = CurScope->getBreakParent();
2689 if (!S) {
2690 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002691 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002692 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002693 if (S->isOpenMPLoopScope())
2694 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2695 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002696 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002697
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002698 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002699}
2700
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002702/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002703///
Douglas Gregor5d369002011-01-21 18:05:27 +00002704/// \param ReturnType If we're determining the copy elision candidate for
2705/// a return statement, this is the return type of the function. If we're
2706/// determining the copy elision candidate for a throw expression, this will
2707/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002708///
Douglas Gregor5d369002011-01-21 18:05:27 +00002709/// \param E The expression being returned from the function or block, or
2710/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002711///
Douglas Gregor86394412011-05-20 15:00:53 +00002712/// \param AllowFunctionParameter Whether we allow function parameters to
2713/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2714/// we re-use this logic to determine whether we should try to move as part of
2715/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002716///
2717/// \returns The NRVO candidate variable, if the return statement may use the
2718/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002719VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2720 Expr *E,
2721 bool AllowFunctionParameter) {
2722 if (!getLangOpts().CPlusPlus)
2723 return nullptr;
2724
2725 // - in a return statement in a function [where] ...
2726 // ... the expression is the name of a non-volatile automatic object ...
2727 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002728 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002729 return nullptr;
2730 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2731 if (!VD)
2732 return nullptr;
2733
2734 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2735 return VD;
2736 return nullptr;
2737}
2738
2739bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2740 bool AllowFunctionParameter) {
2741 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002742 // - in a return statement in a function with ...
2743 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002744 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002745 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002746 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002747 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002748 if (!VDType->isDependentType() &&
2749 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2750 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002752
John McCall03318c12011-11-11 03:57:31 +00002753 // ...object (other than a function or catch-clause parameter)...
2754 if (VD->getKind() != Decl::Var &&
2755 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002756 return false;
2757 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002758
John McCall03318c12011-11-11 03:57:31 +00002759 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002760 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002761
2762 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002763 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002764
2765 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002766 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002767
2768 // Variables with higher required alignment than their type's ABI
2769 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002770 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002771 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002772 return false;
John McCall03318c12011-11-11 03:57:31 +00002773
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002774 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002775}
2776
Douglas Gregor626fbed2011-01-21 21:08:57 +00002777/// \brief Perform the initialization of a potentially-movable value, which
2778/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002779///
2780/// This routine implements C++0x [class.copy]p33, which attempts to treat
2781/// returned lvalues as rvalues in certain cases (to prefer move construction),
2782/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002784Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2785 const VarDecl *NRVOCandidate,
2786 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002787 Expr *Value,
2788 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002789 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790 // When the criteria for elision of a copy operation are met or would
2791 // be met save for the fact that the source object is a function
2792 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002793 // overload resolution to select the constructor for the copy is first
2794 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002795 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002796 if (AllowNRVO &&
2797 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002799 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002800
Douglas Gregorf282a762011-01-21 19:38:21 +00002801 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002803 = InitializationKind::CreateCopy(Value->getLocStart(),
2804 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002805 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002806
2807 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002808 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002809 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002810 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002811 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002812 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2813 StepEnd = Seq.step_end();
2814 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002815 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002816 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817
2818 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002819 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002820
Douglas Gregorf282a762011-01-21 19:38:21 +00002821 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002822 = Constructor->getParamDecl(0)->getType()
2823 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824
Douglas Gregorf282a762011-01-21 19:38:21 +00002825 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002827 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2828 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002829 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830
Douglas Gregorf282a762011-01-21 19:38:21 +00002831 // Promote "AsRvalue" to the heap, since we now need this
2832 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002833 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002834 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835
Douglas Gregorf282a762011-01-21 19:38:21 +00002836 // Complete type-checking the initialization of the return type
2837 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002838 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002839 }
2840 }
2841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002842
Douglas Gregorf282a762011-01-21 19:38:21 +00002843 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002845 // (again) now with the return value expression as written.
2846 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002847 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848
Douglas Gregorf282a762011-01-21 19:38:21 +00002849 return Res;
2850}
2851
Richard Smith4db51c22013-09-25 05:02:54 +00002852/// \brief Determine whether the declared return type of the specified function
2853/// contains 'auto'.
2854static bool hasDeducedReturnType(FunctionDecl *FD) {
2855 const FunctionProtoType *FPT =
2856 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002857 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002858}
2859
Eli Friedman34b49062012-01-26 03:00:14 +00002860/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2861/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002862///
John McCalldadc5752010-08-24 06:29:42 +00002863StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002864Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2865 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002866 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002867 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002868 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002869 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002870
Richard Smith4db51c22013-09-25 05:02:54 +00002871 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2872 // In C++1y, the return type may involve 'auto'.
2873 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2874 FunctionDecl *FD = CurLambda->CallOperator;
2875 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002876 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002877
2878 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2879 assert(AT && "lost auto type from lambda return type");
2880 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2881 FD->setInvalidDecl();
2882 return StmtError();
2883 }
Alp Toker314cc812014-01-25 16:55:45 +00002884 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002885 } else if (CurCap->HasImplicitReturnType) {
2886 // For blocks/lambdas with implicit return types, we check each return
2887 // statement individually, and deduce the common return type when the block
2888 // or lambda is completed.
2889 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002890 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002891 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2892 if (Result.isInvalid())
2893 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002894 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002895
Richard Smith5a0e50c2014-12-19 22:10:51 +00002896 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2897 // when deducing a return type for a lambda-expression (or by extension
2898 // for a block). These rules differ from the stated C++11 rules only in
2899 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002900 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002901 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002902 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002903 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002904 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002905 if (RetValExp) {
2906 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2907 // initializer list, because it is not an expression (even
2908 // though we represent it as one). We still deduce 'void'.
2909 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2910 << RetValExp->getSourceRange();
2911 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002912
Jordan Rosed39e5f12012-07-02 21:19:23 +00002913 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002914 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002915
2916 // Although we'll properly infer the type of the block once it's completed,
2917 // make sure we provide a return type now for better error recovery.
2918 if (CurCap->ReturnType.isNull())
2919 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002920 }
Eli Friedman34b49062012-01-26 03:00:14 +00002921 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002922
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002923 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002924 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2925 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2926 return StmtError();
2927 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002928 } else if (CapturedRegionScopeInfo *CurRegion =
2929 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2930 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2931 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002932 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002933 assert(CurLambda && "unknown kind of captured scope");
2934 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2935 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002936 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2937 return StmtError();
2938 }
2939 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002940
Steve Naroffc540d662008-09-03 18:15:37 +00002941 // Otherwise, verify that this result type matches the previous one. We are
2942 // pickier with blocks than for normal functions because we don't have GCC
2943 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002944 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002945 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002946 // Delay processing for now. TODO: there are lots of dependent
2947 // types we can conclusively prove aren't void.
2948 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002949 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002950 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002951 (RetValExp->isTypeDependent() ||
2952 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002953 if (!getLangOpts().CPlusPlus &&
2954 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002955 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002956 else {
2957 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002958 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002959 }
Steve Naroffc540d662008-09-03 18:15:37 +00002960 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002961 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002962 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2963 } else if (!RetValExp->isTypeDependent()) {
2964 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002965
John McCall5500ef22011-08-17 22:09:46 +00002966 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2967 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2968 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002969
John McCall5500ef22011-08-17 22:09:46 +00002970 // In C++ the return statement is handled via a copy initialization.
2971 // the C version of which boils down to CheckSingleAssignmentConstraints.
2972 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2973 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2974 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002975 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002976 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2977 FnRetType, RetValExp);
2978 if (Res.isInvalid()) {
2979 // FIXME: Cleanup temporaries here, anyway?
2980 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002981 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002982 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002983 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002984 } else {
2985 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002986 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002987
John McCall75f92b52011-08-17 21:34:14 +00002988 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002989 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2990 if (ER.isInvalid())
2991 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002992 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002993 }
John McCall5500ef22011-08-17 22:09:46 +00002994 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2995 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002996
Jordan Rosed39e5f12012-07-02 21:19:23 +00002997 // If we need to check for the named return value optimization,
2998 // or if we need to infer the return type,
2999 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003000 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003001 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
Richard Smith9f690bd2015-10-27 06:02:45 +00003003 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3004 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3005
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003006 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003007}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003008
Nico Weber72889432014-09-06 01:25:55 +00003009namespace {
3010/// \brief Marks all typedefs in all local classes in a type referenced.
3011///
3012/// In a function like
3013/// auto f() {
3014/// struct S { typedef int a; };
3015/// return S();
3016/// }
3017///
3018/// the local type escapes and could be referenced in some TUs but not in
3019/// others. Pretend that all local typedefs are always referenced, to not warn
3020/// on this. This isn't necessary if f has internal linkage, or the typedef
3021/// is private.
3022class LocalTypedefNameReferencer
3023 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3024public:
3025 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3026 bool VisitRecordType(const RecordType *RT);
3027private:
3028 Sema &S;
3029};
3030bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3031 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3032 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3033 R->isDependentType())
3034 return true;
3035 for (auto *TmpD : R->decls())
3036 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3037 if (T->getAccess() != AS_private || R->hasFriends())
3038 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3039 return true;
3040}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003041}
Nico Weber72889432014-09-06 01:25:55 +00003042
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003043TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003044 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003045 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3046 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003047 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003048}
3049
Richard Smith2a7d4812013-05-04 07:00:32 +00003050/// Deduce the return type for a function from a returned expression, per
3051/// C++1y [dcl.spec.auto]p6.
3052bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3053 SourceLocation ReturnLoc,
3054 Expr *&RetExpr,
3055 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003056 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003057 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003058
Richard Smithc58f38f2013-08-14 20:16:31 +00003059 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3060 // If the deduction is for a return statement and the initializer is
3061 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003062 Diag(RetExpr->getExprLoc(),
3063 getCurLambda() ? diag::err_lambda_return_init_list
3064 : diag::err_auto_fn_return_init_list)
3065 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003066 return true;
3067 }
3068
3069 if (FD->isDependentContext()) {
3070 // C++1y [dcl.spec.auto]p12:
3071 // Return type deduction [...] occurs when the definition is
3072 // instantiated even if the function body contains a return
3073 // statement with a non-type-dependent operand.
3074 assert(AT->isDeduced() && "should have deduced to dependent type");
3075 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003076 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003077
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003078 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003079 // Otherwise, [...] deduce a value for U using the rules of template
3080 // argument deduction.
3081 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3082
3083 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3084 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3085 << OrigResultType.getType() << RetExpr->getType();
3086
3087 if (DAR != DAR_Succeeded)
3088 return true;
Nico Weber72889432014-09-06 01:25:55 +00003089
3090 // If a local type is part of the returned type, mark its fields as
3091 // referenced.
3092 LocalTypedefNameReferencer Referencer(*this);
3093 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003094 } else {
3095 // In the case of a return with no operand, the initializer is considered
3096 // to be void().
3097 //
3098 // Deduction here can only succeed if the return type is exactly 'cv auto'
3099 // or 'decltype(auto)', so just check for that case directly.
3100 if (!OrigResultType.getType()->getAs<AutoType>()) {
3101 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3102 << OrigResultType.getType();
3103 return true;
3104 }
3105 // We always deduce U = void in this case.
3106 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3107 if (Deduced.isNull())
3108 return true;
3109 }
3110
3111 // If a function with a declared return type that contains a placeholder type
3112 // has multiple return statements, the return type is deduced for each return
3113 // statement. [...] if the type deduced is not the same in each deduction,
3114 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003115 QualType DeducedT = AT->getDeducedType();
3116 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003117 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003118 // It is possible that NewAT->getDeducedType() is null. When that happens,
3119 // we should not crash, instead we ignore this deduction.
3120 if (NewAT->getDeducedType().isNull())
3121 return false;
3122
Douglas Gregora602a152015-10-01 20:20:47 +00003123 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003124 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003125 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3126 NewAT->getDeducedType());
3127 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003128 const LambdaScopeInfo *LambdaSI = getCurLambda();
3129 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3130 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003131 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003132 << true /*IsLambda*/;
3133 } else {
3134 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3135 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003136 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003137 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003138 return true;
3139 }
3140 } else if (!FD->isInvalidDecl()) {
3141 // Update all declarations of the function to have the deduced return type.
3142 Context.adjustDeducedFunctionResultType(FD, Deduced);
3143 }
3144
3145 return false;
3146}
3147
John McCalldadc5752010-08-24 06:29:42 +00003148StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003149Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3150 Scope *CurScope) {
3151 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3152 if (R.isInvalid()) {
3153 return R;
3154 }
3155
3156 if (VarDecl *VD =
3157 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3158 CurScope->addNRVOCandidate(VD);
3159 } else {
3160 CurScope->setNoNRVO();
3161 }
3162
Nico Weberd64657f2015-03-09 02:47:59 +00003163 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3164
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003165 return R;
3166}
3167
3168StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003169 // Check for unexpanded parameter packs.
3170 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3171 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003172
Eli Friedman34b49062012-01-26 03:00:14 +00003173 if (isa<CapturingScopeInfo>(getCurFunction()))
3174 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003175
Chris Lattner79413952008-12-04 23:50:19 +00003176 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003177 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003178 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003179 bool isObjCMethod = false;
3180
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003181 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003182 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003183 if (FD->hasAttrs())
3184 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003185 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003186 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003187 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003188 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003189 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003190 isObjCMethod = true;
3191 if (MD->hasAttrs())
3192 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003193 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3194 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003195 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003196 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003197 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3198 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003199 }
3200 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003201 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003202
Richard Smith2a7d4812013-05-04 07:00:32 +00003203 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3204 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003205 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003206 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3207 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003208 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003209 FD->setInvalidDecl();
3210 return StmtError();
3211 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003212 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003213 }
3214 }
3215 }
3216
Richard Smithc58f38f2013-08-14 20:16:31 +00003217 bool HasDependentReturnType = FnRetType->isDependentType();
3218
Craig Topperc3ec1492014-05-26 06:22:03 +00003219 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003220 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003221 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003222 if (isa<InitListExpr>(RetValExp)) {
3223 // We simply never allow init lists as the return value of void
3224 // functions. This is compatible because this was never allowed before,
3225 // so there's no legacy code to deal with.
3226 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3227 int FunctionKind = 0;
3228 if (isa<ObjCMethodDecl>(CurDecl))
3229 FunctionKind = 1;
3230 else if (isa<CXXConstructorDecl>(CurDecl))
3231 FunctionKind = 2;
3232 else if (isa<CXXDestructorDecl>(CurDecl))
3233 FunctionKind = 3;
3234
3235 Diag(ReturnLoc, diag::err_return_init_list)
3236 << CurDecl->getDeclName() << FunctionKind
3237 << RetValExp->getSourceRange();
3238
3239 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003240 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003241 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003242 // C99 6.8.6.4p1 (ext_ since GCC warns)
3243 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003244 if (RetValExp->getType()->isVoidType()) {
3245 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3246 if (isa<CXXConstructorDecl>(CurDecl) ||
3247 isa<CXXDestructorDecl>(CurDecl))
3248 D = diag::err_ctor_dtor_returns_void;
3249 else
3250 D = diag::ext_return_has_void_expr;
3251 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003252 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003253 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003254 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003255 if (Result.isInvalid())
3256 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003257 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003258 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003259 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003260 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003261 // return of void in constructor/destructor is illegal in C++.
3262 if (D == diag::err_ctor_dtor_returns_void) {
3263 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3264 Diag(ReturnLoc, D)
3265 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3266 << RetValExp->getSourceRange();
3267 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003268 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003269 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003270 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003271 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003272
3273 int FunctionKind = 0;
3274 if (isa<ObjCMethodDecl>(CurDecl))
3275 FunctionKind = 1;
3276 else if (isa<CXXConstructorDecl>(CurDecl))
3277 FunctionKind = 2;
3278 else if (isa<CXXDestructorDecl>(CurDecl))
3279 FunctionKind = 3;
3280
Nick Lewycky1be750a2011-06-01 07:44:31 +00003281 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003282 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003283 << RetValExp->getSourceRange();
3284 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003285 }
Mike Stump11289f42009-09-09 15:08:12 +00003286
Sebastian Redleef474c2012-02-22 10:50:08 +00003287 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003288 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3289 if (ER.isInvalid())
3290 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003291 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003292 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294
Craig Topperc3ec1492014-05-26 06:22:03 +00003295 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003296 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003297 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003298
David Majnemer2887ad32014-12-13 08:12:56 +00003299 unsigned DiagID;
3300 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3301 // C++11 [stmt.return]p2
3302 DiagID = diag::err_constexpr_return_missing_expr;
3303 FD->setInvalidDecl();
3304 } else if (getLangOpts().C99) {
3305 // C99 6.8.6.4p1 (ext_ since GCC warns)
3306 DiagID = diag::ext_return_missing_expr;
3307 } else {
3308 // C90 6.6.6.4p4
3309 DiagID = diag::warn_return_missing_expr;
3310 }
3311
3312 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003313 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003314 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003315 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003316
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003317 Result = new (Context) ReturnStmt(ReturnLoc);
3318 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003319 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003320 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003321
3322 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3323
3324 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3325 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3326 // function return.
3327
3328 // In C++ the return statement is handled via a copy initialization,
3329 // the C version of which boils down to CheckSingleAssignmentConstraints.
3330 if (RetValExp)
3331 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003332 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003333 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003335 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003336 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003338 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003339 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003340 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003341 return StmtError();
3342 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003343 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003344
3345 // If we have a related result type, we need to implicitly
3346 // convert back to the formal result type. We can't pretend to
3347 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003348 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003349 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003350 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3351 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003352 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3353 if (Res.isInvalid()) {
3354 // FIXME: Clean up temporaries here anyway?
3355 return StmtError();
3356 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003357 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003358 }
3359
Artyom Skrobov9f213442014-01-24 11:10:39 +00003360 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3361 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003362 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003363
John McCallacf0ee52010-10-08 02:01:28 +00003364 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003365 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3366 if (ER.isInvalid())
3367 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003368 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003369 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003370 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372
3373 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003374 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003375 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003376 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003377
Richard Smith9f690bd2015-10-27 06:02:45 +00003378 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3379 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3380
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003381 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003382}
3383
John McCalldadc5752010-08-24 06:29:42 +00003384StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003385Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003386 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003387 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003388 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003389 if (Var && Var->isInvalidDecl())
3390 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003392 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003393}
3394
John McCalldadc5752010-08-24 06:29:42 +00003395StmtResult
John McCallb268a282010-08-23 23:25:46 +00003396Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003397 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003398}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003399
John McCalldadc5752010-08-24 06:29:42 +00003400StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003402 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003403 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003404 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3405
John McCallaab3e412010-08-25 08:40:02 +00003406 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003407 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003408 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3409 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003410}
3411
John McCall0bd3e402012-05-08 21:41:25 +00003412StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003413 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003414 ExprResult Result = DefaultLvalueConversion(Throw);
3415 if (Result.isInvalid())
3416 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003417
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003418 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003419 if (Result.isInvalid())
3420 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003421 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003422
Douglas Gregor2900c162010-04-22 21:44:01 +00003423 QualType ThrowType = Throw->getType();
3424 // Make sure the expression type is an ObjC pointer or "void *".
3425 if (!ThrowType->isDependentType() &&
3426 !ThrowType->isObjCObjectPointerType()) {
3427 const PointerType *PT = ThrowType->getAs<PointerType>();
3428 if (!PT || !PT->getPointeeType()->isVoidType())
3429 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3430 << Throw->getType() << Throw->getSourceRange());
3431 }
3432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003434 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003435}
3436
John McCalldadc5752010-08-24 06:29:42 +00003437StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003439 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003440 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003441 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3442
John McCallb268a282010-08-23 23:25:46 +00003443 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003444 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003445 // in the context of an @catch clause).
3446 Scope *AtCatchParent = CurScope;
3447 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3448 AtCatchParent = AtCatchParent->getParent();
3449 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003450 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451 }
John McCallb268a282010-08-23 23:25:46 +00003452 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003453}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003454
John McCalld9bb7432011-07-27 21:50:02 +00003455ExprResult
3456Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3457 ExprResult result = DefaultLvalueConversion(operand);
3458 if (result.isInvalid())
3459 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003460 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003461
3462 // Make sure the expression type is an ObjC pointer or "void *".
3463 QualType type = operand->getType();
3464 if (!type->isDependentType() &&
3465 !type->isObjCObjectPointerType()) {
3466 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003467 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3468 if (getLangOpts().CPlusPlus) {
3469 if (RequireCompleteType(atLoc, type,
3470 diag::err_incomplete_receiver_type))
3471 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3472 << type << operand->getSourceRange();
3473
3474 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3475 if (!result.isUsable())
3476 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3477 << type << operand->getSourceRange();
3478
3479 operand = result.get();
3480 } else {
3481 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3482 << type << operand->getSourceRange();
3483 }
3484 }
John McCalld9bb7432011-07-27 21:50:02 +00003485 }
3486
3487 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003488 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003489}
3490
John McCalldadc5752010-08-24 06:29:42 +00003491StmtResult
John McCallb268a282010-08-23 23:25:46 +00003492Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3493 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003494 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003495 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003496 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003497}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003498
3499/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3500/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003501StmtResult
John McCall48871652010-08-21 09:40:31 +00003502Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003503 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003504 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003505 return new (Context)
3506 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003507}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003508
John McCall31168b02011-06-15 23:02:42 +00003509StmtResult
3510Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3511 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003512 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003513}
3514
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003515namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003516class CatchHandlerType {
3517 QualType QT;
3518 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003519
Aaron Ballman8aee642902015-04-08 00:05:29 +00003520 // This is a special constructor to be used only with DenseMapInfo's
3521 // getEmptyKey() and getTombstoneKey() functions.
3522 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3523 enum Unique { ForDenseMap };
3524 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3525
Sebastian Redl63c4da02009-07-29 17:15:45 +00003526public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003527 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003528 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003529 /// level pointer and cv-qualifiers.
3530 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3531 if (QT->isPointerType())
3532 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003533
Aaron Ballman8aee642902015-04-08 00:05:29 +00003534 if (IsPointer || QT->isReferenceType())
3535 QT = QT->getPointeeType();
3536 QT = QT.getUnqualifiedType();
3537 }
3538
3539 /// Used when creating a CatchHandlerType from a base class type; pretends the
3540 /// type passed in had the pointer qualifier, does not need to get an
3541 /// unqualified type.
3542 CatchHandlerType(QualType QT, bool IsPointer)
3543 : QT(QT), IsPointer(IsPointer) {}
3544
3545 QualType underlying() const { return QT; }
3546 bool isPointer() const { return IsPointer; }
3547
3548 friend bool operator==(const CatchHandlerType &LHS,
3549 const CatchHandlerType &RHS) {
3550 // If the pointer qualification does not match, we can return early.
3551 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003552 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003553 // Otherwise, check the underlying type without cv-qualifiers.
3554 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003555 }
3556};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003557} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003558
Aaron Ballman8aee642902015-04-08 00:05:29 +00003559namespace llvm {
3560template <> struct DenseMapInfo<CatchHandlerType> {
3561 static CatchHandlerType getEmptyKey() {
3562 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3563 CatchHandlerType::ForDenseMap);
3564 }
3565
3566 static CatchHandlerType getTombstoneKey() {
3567 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3568 CatchHandlerType::ForDenseMap);
3569 }
3570
3571 static unsigned getHashValue(const CatchHandlerType &Base) {
3572 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3573 }
3574
3575 static bool isEqual(const CatchHandlerType &LHS,
3576 const CatchHandlerType &RHS) {
3577 return LHS == RHS;
3578 }
3579};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003580}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003581
3582namespace {
3583class CatchTypePublicBases {
3584 ASTContext &Ctx;
3585 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3586 const bool CheckAgainstPointer;
3587
3588 CXXCatchStmt *FoundHandler;
3589 CanQualType FoundHandlerType;
3590
3591public:
3592 CatchTypePublicBases(
3593 ASTContext &Ctx,
3594 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3595 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3596 FoundHandler(nullptr) {}
3597
3598 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3599 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3600
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003601 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003602 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003603 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003604 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003605 auto I = M.find(Check);
3606 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003607 FoundHandler = I->second;
3608 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003609 return true;
3610 }
3611 }
3612 return false;
3613 }
3614};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003615}
Dan Gohman28ade552010-07-26 21:25:24 +00003616
Sebastian Redl9b244a82008-12-22 21:35:02 +00003617/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3618/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003619StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3620 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003621 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003622 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003623 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003624 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003625
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003626 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3627 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3628
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003629 sema::FunctionScopeInfo *FSI = getCurFunction();
3630
Reid Klecknere7175912015-02-02 22:15:31 +00003631 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003632 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003633 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003634 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003635 }
3636
Robert Wilhelmcafda822013-08-22 09:20:03 +00003637 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003638 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003639 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003640
Aaron Ballman8aee642902015-04-08 00:05:29 +00003641 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003642 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003643 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003644
Aaron Ballman8aee642902015-04-08 00:05:29 +00003645 // Diagnose when the handler is a catch-all handler, but it isn't the last
3646 // handler for the try block. [except.handle]p5. Also, skip exception
3647 // declarations that are invalid, since we can't usefully report on them.
3648 if (!H->getExceptionDecl()) {
3649 if (i < NumHandlers - 1)
3650 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003651 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003652 } else if (H->getExceptionDecl()->isInvalidDecl())
3653 continue;
3654
3655 // Walk the type hierarchy to diagnose when this type has already been
3656 // handled (duplication), or cannot be handled (derivation inversion). We
3657 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003658 CatchHandlerType HandlerCHT =
3659 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003660
3661 // We can ignore whether the type is a reference or a pointer; we need the
3662 // underlying declaration type in order to get at the underlying record
3663 // decl, if there is one.
3664 QualType Underlying = HandlerCHT.underlying();
3665 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3666 if (!RD->hasDefinition())
3667 continue;
3668 // Check that none of the public, unambiguous base classes are in the
3669 // map ([except.handle]p1). Give the base classes the same pointer
3670 // qualification as the original type we are basing off of. This allows
3671 // comparison against the handler type using the same top-level pointer
3672 // as the original type.
3673 CXXBasePaths Paths;
3674 Paths.setOrigin(RD);
3675 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003676 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003677 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3678 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3679 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3680 diag::warn_exception_caught_by_earlier_handler)
3681 << H->getCaughtType();
3682 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3683 diag::note_previous_exception_handler)
3684 << Problem->getCaughtType();
3685 }
3686 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
Aaron Ballman8aee642902015-04-08 00:05:29 +00003689 // Add the type the list of ones we have handled; diagnose if we've already
3690 // handled it.
3691 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3692 if (!R.second) {
3693 const CXXCatchStmt *Problem = R.first->second;
3694 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3695 diag::warn_exception_caught_by_earlier_handler)
3696 << H->getCaughtType();
3697 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3698 diag::note_previous_exception_handler)
3699 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003700 }
3701 }
Mike Stump11289f42009-09-09 15:08:12 +00003702
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003703 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003704
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003705 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003706}
John Wiegley1c0675e2011-04-28 01:08:34 +00003707
Reid Klecknere7175912015-02-02 22:15:31 +00003708StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3709 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003710 assert(TryBlock && Handler);
3711
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003712 sema::FunctionScopeInfo *FSI = getCurFunction();
3713
Reid Klecknere7175912015-02-02 22:15:31 +00003714 // SEH __try is incompatible with C++ try. Borland appears to support this,
3715 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003716 if (!getLangOpts().Borland) {
3717 if (FSI->FirstCXXTryLoc.isValid()) {
3718 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3719 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3720 }
Reid Klecknere7175912015-02-02 22:15:31 +00003721 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003722
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003723 FSI->setHasSEHTry(TryLoc);
3724
3725 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3726 // track if they use SEH.
3727 DeclContext *DC = CurContext;
3728 while (DC && !DC->isFunctionOrMethod())
3729 DC = DC->getParent();
3730 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3731 if (FD)
3732 FD->setUsesSEHTry(true);
3733 else
3734 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003735
Reid Kleckner8819a402015-07-10 00:16:25 +00003736 // Reject __try on unsupported targets.
3737 if (!Context.getTargetInfo().isSEHTrySupported())
3738 Diag(TryLoc, diag::err_seh_try_unsupported);
3739
Reid Klecknere7175912015-02-02 22:15:31 +00003740 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003741}
3742
3743StmtResult
3744Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3745 Expr *FilterExpr,
3746 Stmt *Block) {
3747 assert(FilterExpr && Block);
3748
3749 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003750 return StmtError(Diag(FilterExpr->getExprLoc(),
3751 diag::err_filter_expression_integral)
3752 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003753 }
3754
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003755 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003756}
3757
Nico Weberd64657f2015-03-09 02:47:59 +00003758void Sema::ActOnStartSEHFinallyBlock() {
3759 CurrentSEHFinally.push_back(CurScope);
3760}
3761
Nico Weberce903292015-03-09 03:17:15 +00003762void Sema::ActOnAbortSEHFinallyBlock() {
3763 CurrentSEHFinally.pop_back();
3764}
3765
Nico Weberd64657f2015-03-09 02:47:59 +00003766StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003767 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003768 CurrentSEHFinally.pop_back();
3769 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003770}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003771
Nico Weberc7d05962014-07-06 22:32:59 +00003772StmtResult
3773Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003774 Scope *SEHTryParent = CurScope;
3775 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3776 SEHTryParent = SEHTryParent->getParent();
3777 if (!SEHTryParent)
3778 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003779 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003780
Nico Weber9b982072014-07-07 00:12:30 +00003781 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003782}
3783
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003784StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3785 bool IsIfExists,
3786 NestedNameSpecifierLoc QualifierLoc,
3787 DeclarationNameInfo NameInfo,
3788 Stmt *Nested)
3789{
3790 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003791 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003792 cast<CompoundStmt>(Nested));
3793}
3794
3795
Chad Rosier02a84392012-08-10 17:56:09 +00003796StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003797 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003798 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003799 UnqualifiedId &Name,
3800 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003801 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003802 SS.getWithLocInContext(Context),
3803 GetNameFromUnqualifiedId(Name),
3804 Nested);
3805}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003806
3807RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003808Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3809 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003810 DeclContext *DC = CurContext;
3811 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3812 DC = DC->getParent();
3813
Craig Topperc3ec1492014-05-26 06:22:03 +00003814 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003815 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003816 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3817 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003818 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003819 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003820
Alexey Bataev330de032014-10-29 12:21:55 +00003821 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003822 DC->addDecl(RD);
3823 RD->setImplicit();
3824 RD->startDefinition();
3825
Alexey Bataev9959db52014-05-06 10:08:46 +00003826 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003827 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003828 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003829 return RD;
3830}
3831
3832static void buildCapturedStmtCaptureList(
3833 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3834 SmallVectorImpl<Expr *> &CaptureInits,
3835 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3836
3837 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3838 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3839
3840 if (Cap->isThisCapture()) {
3841 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3842 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003843 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003844 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003845 } else if (Cap->isVLATypeCapture()) {
3846 Captures.push_back(
3847 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3848 CaptureInits.push_back(nullptr);
3849 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003850 }
3851
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003852 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003853 Cap->isReferenceCapture()
3854 ? CapturedStmt::VCK_ByRef
3855 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003856 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003857 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003858 }
3859}
3860
3861void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003862 CapturedRegionKind Kind,
3863 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003864 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003865 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003866
Alexey Bataev9959db52014-05-06 10:08:46 +00003867 // Build the context parameter
3868 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3869 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3870 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3871 ImplicitParamDecl *Param
3872 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3873 DC->addDecl(Param);
3874
3875 CD->setContextParam(0, Param);
3876
3877 // Enter the capturing scope for this captured region.
3878 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3879
3880 if (CurScope)
3881 PushDeclContext(CurScope, CD);
3882 else
3883 CurContext = CD;
3884
3885 PushExpressionEvaluationContext(PotentiallyEvaluated);
3886}
3887
3888void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3889 CapturedRegionKind Kind,
3890 ArrayRef<CapturedParamNameType> Params) {
3891 CapturedDecl *CD = nullptr;
3892 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3893
3894 // Build the context parameter
3895 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3896 bool ContextIsFound = false;
3897 unsigned ParamNum = 0;
3898 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3899 E = Params.end();
3900 I != E; ++I, ++ParamNum) {
3901 if (I->second.isNull()) {
3902 assert(!ContextIsFound &&
3903 "null type has been found already for '__context' parameter");
3904 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3905 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3906 ImplicitParamDecl *Param
3907 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3908 DC->addDecl(Param);
3909 CD->setContextParam(ParamNum, Param);
3910 ContextIsFound = true;
3911 } else {
3912 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3913 ImplicitParamDecl *Param
3914 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3915 DC->addDecl(Param);
3916 CD->setParam(ParamNum, Param);
3917 }
3918 }
3919 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003920 if (!ContextIsFound) {
3921 // Add __context implicitly if it is not specified.
3922 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3923 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3924 ImplicitParamDecl *Param =
3925 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3926 DC->addDecl(Param);
3927 CD->setContextParam(ParamNum, Param);
3928 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003929 // Enter the capturing scope for this captured region.
3930 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3931
3932 if (CurScope)
3933 PushDeclContext(CurScope, CD);
3934 else
3935 CurContext = CD;
3936
3937 PushExpressionEvaluationContext(PotentiallyEvaluated);
3938}
3939
Wei Pan17fbf6e2013-05-04 03:59:06 +00003940void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003941 DiscardCleanupsInEvaluationContext();
3942 PopExpressionEvaluationContext();
3943
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003944 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3945 RecordDecl *Record = RSI->TheRecordDecl;
3946 Record->setInvalidDecl();
3947
Aaron Ballman62e47c42014-03-10 13:43:55 +00003948 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003949 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3950 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003951
Wei Pan17fbf6e2013-05-04 03:59:06 +00003952 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003953 PopFunctionScopeInfo();
3954}
3955
3956StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3957 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3958
3959 SmallVector<CapturedStmt::Capture, 4> Captures;
3960 SmallVector<Expr *, 4> CaptureInits;
3961 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3962
3963 CapturedDecl *CD = RSI->TheCapturedDecl;
3964 RecordDecl *RD = RSI->TheRecordDecl;
3965
Wei Pan17fbf6e2013-05-04 03:59:06 +00003966 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3967 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003968 CaptureInits, CD, RD);
3969
3970 CD->setBody(Res->getCapturedStmt());
3971 RD->completeDefinition();
3972
Wei Pan17fbf6e2013-05-04 03:59:06 +00003973 DiscardCleanupsInEvaluationContext();
3974 PopExpressionEvaluationContext();
3975
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003976 PopDeclContext();
3977 PopFunctionScopeInfo();
3978
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003979 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003980}