blob: cc3c25cfb5a89834e92962ebc5a1e1e8c69d28a4 [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"
Richard Smith50e291e2018-01-02 23:52:42 +000017#include "clang/AST/ASTLambda.h"
John McCall03318c12011-11-11 03:57:31 +000018#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000024#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000028#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000035#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000036#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000037#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000039#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000040#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000041
Chris Lattneraf8d5812006-11-10 05:07:45 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000044
Richard Smith945f8d32013-01-14 22:39:08 +000045StmtResult Sema::ActOnExprStmt(ExprResult FE) {
46 if (FE.isInvalid())
47 return StmtError();
48
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
50 /*DiscardedValue*/ true);
51 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000052 return StmtError();
53
Chris Lattner903eb512008-07-25 23:18:17 +000054 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
55 // void expression for its side effects. Conversion to void allows any
56 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000057
Chris Lattner903eb512008-07-25 23:18:17 +000058 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000059 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000060}
61
62
John McCalleaef89b2013-03-22 02:10:40 +000063StmtResult Sema::ActOnExprStmtError() {
64 DiscardCleanupsInEvaluationContext();
65 return StmtError();
66}
67
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000068StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000069 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000070 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000071}
72
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000073StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
74 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000075 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattnercbafe8d2009-04-12 20:13:14 +000077 // If we have an invalid decl, just return an error.
78 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000079
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000080 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000081}
Chris Lattneraf8d5812006-11-10 05:07:45 +000082
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000083void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000084 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000085
Douglas Gregor2eb1c572013-04-08 20:52:24 +000086 // If we don't have a declaration, or we have an invalid declaration,
87 // just return.
88 if (DG.isNull() || !DG.isSingleDecl())
89 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000090
Douglas Gregor2eb1c572013-04-08 20:52:24 +000091 Decl *decl = DG.getSingleDecl();
92 if (!decl || decl->isInvalidDecl())
93 return;
94
95 // Only variable declarations are permitted.
96 VarDecl *var = dyn_cast<VarDecl>(decl);
97 if (!var) {
98 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
99 decl->setInvalidDecl();
100 return;
101 }
John McCall31168b02011-06-15 23:02:42 +0000102
John McCalld4631322011-06-17 06:42:21 +0000103 // foreach variables are never actually initialized in the way that
104 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000105 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000106
John McCalld4631322011-06-17 06:42:21 +0000107 // In ARC, we don't need to retain the iteration variable of a fast
108 // enumeration loop. Rather than actually trying to catch that
109 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000110 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000111 QualType type = var->getType();
112
113 // Only do this if we inferred the lifetime. Inferred lifetime
114 // will show up as a local qualifier because explicit lifetime
115 // should have shown up as an AttributedType instead.
116 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
117 // Add 'const' and mark the variable as pseudo-strong.
118 var->setType(type.withConst());
119 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000120 }
121 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000122}
123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000124/// Diagnose unused comparisons, both builtin and overloaded operators.
Richard Trieu99e1c952014-03-11 03:11:08 +0000125/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126///
127/// Adding a cast to void (or other expression wrappers) will prevent the
128/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000129static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130 SourceLocation Loc;
Richard Smithc70f1d62017-12-14 15:16:18 +0000131 bool CanAssign;
132 enum { Equality, Inequality, Relational, ThreeWay } Kind;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000133
134 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000135 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000136 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137
Richard Smithc70f1d62017-12-14 15:16:18 +0000138 if (Op->getOpcode() == BO_EQ)
139 Kind = Equality;
140 else if (Op->getOpcode() == BO_NE)
141 Kind = Inequality;
142 else if (Op->getOpcode() == BO_Cmp)
143 Kind = ThreeWay;
144 else {
145 assert(Op->isRelationalOp());
146 Kind = Relational;
147 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000148 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000149 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000151 switch (Op->getOperator()) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000152 case OO_EqualEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000153 Kind = Equality;
154 break;
Richard Trieu99e1c952014-03-11 03:11:08 +0000155 case OO_ExclaimEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000156 Kind = Inequality;
Richard Trieu99e1c952014-03-11 03:11:08 +0000157 break;
158 case OO_Less:
159 case OO_Greater:
160 case OO_GreaterEqual:
161 case OO_LessEqual:
Richard Smithc70f1d62017-12-14 15:16:18 +0000162 Kind = Relational;
Richard Trieu99e1c952014-03-11 03:11:08 +0000163 break;
Richard Smithc70f1d62017-12-14 15:16:18 +0000164 case OO_Spaceship:
165 Kind = ThreeWay;
166 break;
167 default:
168 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000170
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000173 } else {
174 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000175 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000176 }
177
178 // Suppress warnings when the operator, suspicious as it may be, comes from
179 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000180 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000181 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000182
Chandler Carruthe2669392011-08-17 09:34:37 +0000183 S.Diag(Loc, diag::warn_unused_comparison)
Richard Smithc70f1d62017-12-14 15:16:18 +0000184 << (unsigned)Kind << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000185
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000186 // If the LHS is a plausible entity to assign to, provide a fixit hint to
187 // correct common typos.
Richard Smithc70f1d62017-12-14 15:16:18 +0000188 if (CanAssign) {
189 if (Kind == Inequality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191 << FixItHint::CreateReplacement(Loc, "|=");
Richard Smithc70f1d62017-12-14 15:16:18 +0000192 else if (Kind == Equality)
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000193 S.Diag(Loc, diag::note_equality_comparison_to_assign)
194 << FixItHint::CreateReplacement(Loc, "=");
195 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000196
197 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000198}
199
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000200void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000201 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
202 return DiagnoseUnusedExprResult(Label->getSubStmt());
203
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000204 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000205 if (!E)
206 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000207
208 // If we are in an unevaluated expression context, then there can be no unused
209 // results because the results aren't expected to be used in the first place.
210 if (isUnevaluatedContext())
211 return;
212
Nico Weber0e631632015-10-27 19:47:40 +0000213 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000214 // In most cases, we don't want to warn if the expression is written in a
215 // macro body, or if the macro comes from a system header. If the offending
216 // expression is a call to a function with the warn_unused_result attribute,
217 // we warn no matter the location. Because of the order in which the various
218 // checks need to happen, we factor out the macro-related test here.
Fangrui Song6907ce22018-07-30 19:24:48 +0000219 bool ShouldSuppress =
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000220 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
221 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000222
Eli Friedmanc11535c2012-05-24 00:47:05 +0000223 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000224 SourceLocation Loc;
225 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000226 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner6dc7e572012-08-31 22:39:21 +0000229 // If this is a GNU statement expression expanded from a macro, it is probably
230 // unused because it is a function-like macro that can be used as either an
231 // expression or statement. Don't warn, because it is almost certainly a
232 // false positive.
233 if (isa<StmtExpr>(E) && Loc.isMacroID())
234 return;
235
Nico Weber0e631632015-10-27 19:47:40 +0000236 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
237 // That macro is frequently used to suppress "unused parameter" warnings,
238 // but its implementation makes clang's -Wunused-value fire. Prevent this.
239 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
240 SourceLocation SpellLoc = Loc;
241 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
242 return;
243 }
244
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000245 // Okay, we have an unused result. Depending on what the base expression is,
246 // we might want to make a more specific diagnostic. Check for one of these
247 // cases now.
248 unsigned DiagID = diag::warn_unused_expr;
Bill Wendling7c44da22018-10-31 03:48:47 +0000249 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000250 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000251 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
252 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000253
Chandler Carruthe2669392011-08-17 09:34:37 +0000254 if (DiagnoseUnusedComparison(*this, E))
255 return;
256
Eli Friedmanc11535c2012-05-24 00:47:05 +0000257 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000259 if (E->getType()->isVoidType())
260 return;
261
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000263 // a more specific message to make it clear what is happening. If the call
264 // is written in a macro body, only warn if it has the warn_unused_result
265 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000266 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000267 if (const Attr *A = isa<FunctionDecl>(FD)
268 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
269 : FD->getAttr<WarnUnusedResultAttr>()) {
270 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000271 return;
272 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000273 if (ShouldSuppress)
274 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000275 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000276 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
277 return;
278 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000279 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000280 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
281 return;
282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000284 } else if (ShouldSuppress)
285 return;
286
287 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000289 Diag(Loc, diag::err_arc_unused_init_message) << R1;
290 return;
291 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000292 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000293 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000294 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
295 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000296 return;
297 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000298 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000299 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
300 const Expr *Source = POE->getSyntacticForm();
301 if (isa<ObjCSubscriptRefExpr>(Source))
302 DiagID = diag::warn_unused_container_subscript_expr;
303 else
304 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000305 } else if (const CXXFunctionalCastExpr *FC
306 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000307 const Expr *E = FC->getSubExpr();
308 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
309 E = TE->getSubExpr();
310 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000311 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000312 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
313 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
314 if (!RD->getAttr<WarnUnusedAttr>())
315 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000316 }
John McCall2351cb92010-04-06 22:24:14 +0000317 // Diagnose "(void*) blah" as a typo for "(void) blah".
318 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
319 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
320 QualType T = TI->getType();
321
322 // We really do want to use the non-canonical type here.
323 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000324 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000325
326 Diag(Loc, diag::warn_unused_voidptr)
327 << FixItHint::CreateRemoval(TL.getStarLoc());
328 return;
329 }
330 }
331
Eli Friedmanc11535c2012-05-24 00:47:05 +0000332 if (E->isGLValue() && E->getType().isVolatileQualified()) {
333 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
334 return;
335 }
336
Craig Topperc3ec1492014-05-26 06:22:03 +0000337 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000338}
339
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000340void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
341 PushCompoundScope(IsStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000342}
343
344void Sema::ActOnFinishOfCompoundStmt() {
345 PopCompoundScope();
346}
347
348sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
349 return getCurFunction()->CompoundScopes.back();
350}
351
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000352StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
353 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
354 const unsigned NumElts = Elts.size();
355
Chris Lattnerd864daf2007-08-27 04:29:41 +0000356 // If we're in C89 mode, check that we don't have any decls after stmts. If
357 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000358 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000359 // Note that __extension__ can be around a decl.
360 unsigned i = 0;
361 // Skip over all declarations.
362 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
363 /*empty*/;
364
365 // We found the end of the list or a statement. Scan for another declstmt.
366 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
367 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnerd864daf2007-08-27 04:29:41 +0000369 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000370 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000371 Diag(D->getLocation(), diag::ext_mixed_decls_code);
372 }
373 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000374 // Warn about unused expressions in statements.
375 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000376 // Ignore statements that are last in a statement expression.
377 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000378 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000379
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000380 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000381 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000382
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000383 // Check for suspicious empty body (null statement) in `for' and `while'
384 // statements. Don't do anything for template instantiations, this just adds
385 // noise.
386 if (NumElts != 0 && !CurrentInstantiationScope &&
387 getCurCompoundScope().HasEmptyLoopBodies) {
388 for (unsigned i = 0; i != NumElts - 1; ++i)
389 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
390 }
391
Benjamin Kramer07420902017-12-24 16:24:20 +0000392 return CompoundStmt::Create(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000393}
394
Richard Smithef6c43d2018-07-26 18:41:30 +0000395ExprResult
396Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
397 if (!Val.get())
398 return Val;
399
400 if (DiagnoseUnexpandedParameterPack(Val.get()))
401 return ExprError();
402
403 // If we're not inside a switch, let the 'case' statement handling diagnose
404 // this. Just clean up after the expression as best we can.
405 if (!getCurFunction()->SwitchStack.empty()) {
406 Expr *CondExpr =
407 getCurFunction()->SwitchStack.back().getPointer()->getCond();
408 if (!CondExpr)
409 return ExprError();
410 QualType CondType = CondExpr->getType();
411
412 auto CheckAndFinish = [&](Expr *E) {
413 if (CondType->isDependentType() || E->isTypeDependent())
414 return ExprResult(E);
415
416 if (getLangOpts().CPlusPlus11) {
417 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
418 // constant expression of the promoted type of the switch condition.
419 llvm::APSInt TempVal;
420 return CheckConvertedConstantExpression(E, CondType, TempVal,
421 CCEK_CaseValue);
422 }
423
424 ExprResult ER = E;
425 if (!E->isValueDependent())
426 ER = VerifyIntegerConstantExpression(E);
427 if (!ER.isInvalid())
428 ER = DefaultLvalueConversion(ER.get());
429 if (!ER.isInvalid())
430 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
431 return ER;
432 };
433
434 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
435 if (Converted.get() == Val.get())
436 Converted = CheckAndFinish(Val.get());
437 if (Converted.isInvalid())
438 return ExprError();
439 Val = Converted;
440 }
441
442 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
443 getLangOpts().CPlusPlus11);
444}
445
John McCalldadc5752010-08-24 06:29:42 +0000446StmtResult
Richard Smithef6c43d2018-07-26 18:41:30 +0000447Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
448 SourceLocation DotDotDotLoc, ExprResult RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000449 SourceLocation ColonLoc) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000450 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
451 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
452 : RHSVal.isInvalid() || RHSVal.get()) &&
453 "missing RHS value");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000454
John McCallaab3e412010-08-25 08:40:02 +0000455 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000456 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000457 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000458 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000459
Richard Smithef6c43d2018-07-26 18:41:30 +0000460 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
461 getCurFunction()->SwitchStack.back().setInt(true);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000462 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000463 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000464
Bruno Ricci5b30571752018-10-28 12:30:53 +0000465 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
466 CaseLoc, DotDotDotLoc, ColonLoc);
Richard Smithef6c43d2018-07-26 18:41:30 +0000467 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000468 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000469}
470
Chris Lattner34a22092009-03-04 04:23:07 +0000471/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000472void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000473 DiagnoseUnusedExprResult(SubStmt);
474
Bruno Ricci5b30571752018-10-28 12:30:53 +0000475 auto *CS = static_cast<CaseStmt *>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000476 CS->setSubStmt(SubStmt);
477}
478
John McCalldadc5752010-08-24 06:29:42 +0000479StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000480Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000481 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000482 DiagnoseUnusedExprResult(SubStmt);
483
John McCallaab3e412010-08-25 08:40:02 +0000484 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000485 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000486 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000487 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000488
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000489 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Richard Smithef6c43d2018-07-26 18:41:30 +0000490 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000491 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000492}
493
John McCalldadc5752010-08-24 06:29:42 +0000494StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000495Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
496 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000497 // If the label was multiply defined, reject it now.
498 if (TheDecl->getStmt()) {
499 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
500 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000501 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000502 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000503
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000504 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000505 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
506 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000507 if (!TheDecl->isGnuLocal()) {
508 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000509 if (!TheDecl->isMSAsmLabel()) {
510 // Don't update the location of MS ASM labels. These will result in
511 // a diagnostic, and changing the location here will mess that up.
512 TheDecl->setLocation(IdentLoc);
513 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000514 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000515 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000516}
517
Richard Smithc202b282012-04-14 00:33:13 +0000518StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000519 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000520 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000521 // Fill in the declaration and return it.
522 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000523 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000524}
525
Richard Trieufaca2d82016-02-18 23:58:40 +0000526namespace {
527class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
528 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
529 Sema &SemaRef;
530public:
531 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
532 void VisitBinaryOperator(BinaryOperator *E) {
533 if (E->getOpcode() == BO_Comma)
534 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
535 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
536 }
537};
538}
539
John McCalldadc5752010-08-24 06:29:42 +0000540StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000541Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
542 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000543 Stmt *thenStmt, SourceLocation ElseLoc,
544 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000545 if (Cond.isInvalid())
546 Cond = ConditionResult(
547 *this, nullptr,
548 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
549 Context.BoolTy, VK_RValue),
550 IfLoc),
551 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000552
Richard Smithb130fe72016-06-23 19:16:49 +0000553 Expr *CondExpr = Cond.get().second;
Richard Trieuf3713802018-10-25 01:08:00 +0000554 // Only call the CommaVisitor when not C89 due to differences in scope flags.
555 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
556 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
Richard Smithb130fe72016-06-23 19:16:49 +0000557 CommaVisitor(*this).Visit(CondExpr);
558
Hans Wennborg59ad1502017-11-20 17:48:54 +0000559 if (!elseStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000560 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
Hans Wennborg95419752017-11-20 17:38:16 +0000561 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000562
Richard Smitha547eb22016-07-14 00:11:03 +0000563 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
564 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000565}
566
567StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000568 Stmt *InitStmt, ConditionResult Cond,
569 Stmt *thenStmt, SourceLocation ElseLoc,
570 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000571 if (Cond.isInvalid())
572 return StmtError();
573
Erik Pilkington5cd57172016-08-16 17:44:11 +0000574 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Reid Kleckner87a31802018-03-12 21:43:02 +0000575 setFunctionHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000576
577 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000578 DiagnoseUnusedExprResult(elseStmt);
579
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000580 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
581 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000582}
Steve Naroff86272ea2007-05-29 02:14:17 +0000583
Chris Lattner67998452007-08-23 18:29:20 +0000584namespace {
585 struct CaseCompareFunctor {
586 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
587 const llvm::APSInt &RHS) {
588 return LHS.first < RHS;
589 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000590 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
591 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
592 return LHS.first < RHS.first;
593 }
Chris Lattner67998452007-08-23 18:29:20 +0000594 bool operator()(const llvm::APSInt &LHS,
595 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
596 return LHS < RHS.first;
597 }
598 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000599}
Chris Lattner67998452007-08-23 18:29:20 +0000600
Chris Lattner4b2ff022007-09-21 18:15:22 +0000601/// CmpCaseVals - Comparison predicate for sorting case values.
602///
603static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
604 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
605 if (lhs.first < rhs.first)
606 return true;
607
608 if (lhs.first == rhs.first &&
609 lhs.second->getCaseLoc().getRawEncoding()
610 < rhs.second->getCaseLoc().getRawEncoding())
611 return true;
612 return false;
613}
614
Douglas Gregorbd6839732010-02-08 22:24:16 +0000615/// CmpEnumVals - Comparison predicate for sorting enumeration values.
616///
617static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
618 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
619{
620 return lhs.first < rhs.first;
621}
622
623/// EqEnumVals - Comparison preficate for uniqing enumeration values.
624///
625static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
626 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
627{
628 return lhs.first == rhs.first;
629}
630
Chris Lattnera96d4272009-10-16 16:45:22 +0000631/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
632/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000633static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000634 if (const auto *FE = dyn_cast<FullExpr>(E))
635 E = FE->getSubExpr();
Gabor Horvath64c32412017-08-09 08:57:09 +0000636 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
637 if (ImpCast->getCastKind() != CK_IntegralCast) break;
638 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000639 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000640 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000641}
642
Richard Smith03a4aa32016-06-23 19:02:52 +0000643ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000644 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
645 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000646
Douglas Gregore2b37442012-05-04 22:38:52 +0000647 public:
648 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000649 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
650 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000651
Craig Toppere14c0f82014-03-12 04:55:44 +0000652 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
653 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000654 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
655 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000656
Craig Toppere14c0f82014-03-12 04:55:44 +0000657 SemaDiagnosticBuilder diagnoseIncomplete(
658 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000659 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
660 << T << Cond->getSourceRange();
661 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000662
Craig Toppere14c0f82014-03-12 04:55:44 +0000663 SemaDiagnosticBuilder diagnoseExplicitConv(
664 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000665 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
666 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000667
Craig Toppere14c0f82014-03-12 04:55:44 +0000668 SemaDiagnosticBuilder noteExplicitConv(
669 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000670 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
671 << ConvTy->isEnumeralType() << ConvTy;
672 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000673
Craig Toppere14c0f82014-03-12 04:55:44 +0000674 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
675 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000676 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
677 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000678
Craig Toppere14c0f82014-03-12 04:55:44 +0000679 SemaDiagnosticBuilder noteAmbiguous(
680 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000681 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
682 << ConvTy->isEnumeralType() << ConvTy;
683 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000684
Craig Toppere14c0f82014-03-12 04:55:44 +0000685 SemaDiagnosticBuilder diagnoseConversion(
686 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000687 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000688 }
689 } SwitchDiagnoser(Cond);
690
Richard Smith03a4aa32016-06-23 19:02:52 +0000691 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000692 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000693 if (CondResult.isInvalid())
694 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Richard Smithef6c43d2018-07-26 18:41:30 +0000696 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
697 // failed and produced a diagnostic.
698 Cond = CondResult.get();
699 if (!Cond->isTypeDependent() &&
700 !Cond->getType()->isIntegralOrEnumerationType())
701 return ExprError();
702
John McCall5939b162011-08-06 07:30:58 +0000703 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smithef6c43d2018-07-26 18:41:30 +0000704 return UsualUnaryConversions(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +0000705}
John McCall5939b162011-08-06 07:30:58 +0000706
Richard Smithc7a05a92016-06-29 21:17:59 +0000707StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
708 Stmt *InitStmt, ConditionResult Cond) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000709 Expr *CondExpr = Cond.get().second;
710 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
711
712 if (CondExpr && !CondExpr->isTypeDependent()) {
713 // We have already converted the expression to an integral or enumeration
714 // type, when we parsed the switch condition. If we don't have an
715 // appropriate type now, enter the switch scope but remember that it's
716 // invalid.
717 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
718 "invalid condition type");
719 if (CondExpr->isKnownToHaveBooleanValue()) {
720 // switch(bool_expr) {...} is often a programmer error, e.g.
721 // switch(n && mask) { ... } // Doh - should be "n & mask".
722 // One can always use an if statement instead of switch(bool_expr).
723 Diag(SwitchLoc, diag::warn_bool_switch_condition)
724 << CondExpr->getSourceRange();
725 }
726 }
John McCalla95172b2010-08-01 00:26:45 +0000727
Reid Kleckner87a31802018-03-12 21:43:02 +0000728 setFunctionHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729
Bruno Riccie2806f82018-10-29 16:12:37 +0000730 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
Richard Smithef6c43d2018-07-26 18:41:30 +0000731 getCurFunction()->SwitchStack.push_back(
732 FunctionScopeInfo::SwitchInfo(SS, false));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000733 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000734}
735
Gabor Greif16e02862010-10-01 22:05:14 +0000736static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000737 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000738 Val.setIsSigned(IsSigned);
739}
740
Richard Smith077d0832014-08-04 00:40:48 +0000741/// Check the specified case value is in range for the given unpromoted switch
742/// type.
743static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
744 unsigned UnpromotedWidth, bool UnpromotedSign) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000745 // In C++11 onwards, this is checked by the language rules.
746 if (S.getLangOpts().CPlusPlus11)
747 return;
748
Richard Smith077d0832014-08-04 00:40:48 +0000749 // If the case value was signed and negative and the switch expression is
750 // unsigned, don't bother to warn: this is implementation-defined behavior.
751 // FIXME: Introduce a second, default-ignored warning for this case?
752 if (UnpromotedWidth < Val.getBitWidth()) {
753 llvm::APSInt ConvVal(Val);
754 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
755 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
756 // FIXME: Use different diagnostics for overflow in conversion to promoted
757 // type versus "switch expression cannot have this value". Use proper
758 // IntRange checking rather than just looking at the unpromoted type here.
759 if (ConvVal != Val)
760 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
761 << ConvVal.toString(10);
762 }
763}
764
Alexis Hunt724f14e2014-11-28 00:53:20 +0000765typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
766
Dmitri Gribenko58683752013-12-05 22:52:07 +0000767/// Returns true if we should emit a diagnostic about this case expression not
768/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000769static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000770 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000771 const Expr *CaseExpr,
772 EnumValsTy::iterator &EI,
773 EnumValsTy::iterator &EIEnd,
774 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000775 if (!ED->isClosed())
776 return false;
777
Alexis Hunt724f14e2014-11-28 00:53:20 +0000778 if (const DeclRefExpr *DRE =
779 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000780 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000781 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000782 QualType EnumType = S.Context.getTypeDeclType(ED);
783 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
784 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000785 return false;
786 }
787 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000788
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000789 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000790 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000791
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000792 while (EI != EIEnd && EI->first < Val)
793 EI++;
794
795 if (EI != EIEnd && EI->first == Val)
796 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000797
Dmitri Gribenko58683752013-12-05 22:52:07 +0000798 return true;
799}
800
Gabor Horvath64c32412017-08-09 08:57:09 +0000801static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
802 const Expr *Case) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000803 QualType CondType = Cond->getType();
Gabor Horvath64c32412017-08-09 08:57:09 +0000804 QualType CaseType = Case->getType();
805
806 const EnumType *CondEnumType = CondType->getAs<EnumType>();
807 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
808 if (!CondEnumType || !CaseEnumType)
809 return;
810
Gabor Horvathb57e2642017-08-09 12:34:58 +0000811 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000812 if (!CondEnumType->getDecl()->getIdentifier() &&
813 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000814 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000815 if (!CaseEnumType->getDecl()->getIdentifier() &&
816 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000817 return;
818
Gabor Horvath64c32412017-08-09 08:57:09 +0000819 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
820 return;
821
Gabor Horvath0284a202017-08-09 20:56:43 +0000822 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000823 << CondType << CaseType << Cond->getSourceRange()
824 << Case->getSourceRange();
825}
826
John McCalldadc5752010-08-24 06:29:42 +0000827StmtResult
John McCallb268a282010-08-23 23:25:46 +0000828Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
829 Stmt *BodyStmt) {
830 SwitchStmt *SS = cast<SwitchStmt>(Switch);
Richard Smithef6c43d2018-07-26 18:41:30 +0000831 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
832 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
John McCallaab3e412010-08-25 08:40:02 +0000833 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000834
David Majnemer418ad3f2014-12-15 07:46:12 +0000835 getCurFunction()->SwitchStack.pop_back();
836
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000837 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000838 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000839
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000840 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000841 if (!CondExpr) return StmtError();
842
843 QualType CondType = CondExpr->getType();
844
Chris Lattnera96d4272009-10-16 16:45:22 +0000845 // C++ 6.4.2.p2:
846 // Integral promotions are performed (on the switch condition).
847 //
848 // A case value unrepresentable by the original switch condition
849 // type (before the promotion) doesn't make sense, even when it can
850 // be represented by the promoted type. Therefore we need to find
851 // the pre-promotion type of the switch condition.
Richard Smithef6c43d2018-07-26 18:41:30 +0000852 const Expr *CondExprBeforePromotion = CondExpr;
853 QualType CondTypeBeforePromotion =
854 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000855
Richard Smith077d0832014-08-04 00:40:48 +0000856 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000857 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000858 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000859 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000860 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
861 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
862
863 // Get the width and signedness that the condition might actually have, for
864 // warning purposes.
865 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
866 // type.
867 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000868 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000869 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000870 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000872 // Accumulate all of the case values in a vector so that we can sort them
873 // and detect duplicates. This vector contains the APInt for the case after
874 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000875 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000876 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000878 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000879 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
880 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Craig Topperc3ec1492014-05-26 06:22:03 +0000882 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner10cb5e52007-08-23 06:23:56 +0000884 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000885
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000886 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000887 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000888
Anders Carlsson51873c22007-07-22 07:07:56 +0000889 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000890 if (TheDefaultStmt) {
891 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000892 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000893
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000894 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000895 // we'll return a valid AST. This requires recursing down the AST and
896 // finding it, not something we are set up to do right now. For now,
897 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000898 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000899 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000900 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000902 } else {
903 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000904
Chris Lattnera65e1f32008-01-16 19:17:22 +0000905 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000906
Richard Smithef6c43d2018-07-26 18:41:30 +0000907 if (Lo->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 HasDependentValue = true;
909 break;
910 }
Mike Stump11289f42009-09-09 15:08:12 +0000911
Richard Smithef6c43d2018-07-26 18:41:30 +0000912 // We already verified that the expression has a constant value;
913 // get that value (prior to conversions).
914 const Expr *LoBeforePromotion = Lo;
915 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
916 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000917
Richard Smith077d0832014-08-04 00:40:48 +0000918 // Check the unconverted value is within the range of possible values of
919 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000920 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
921 CondIsSignedBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000922
Richard Smithef6c43d2018-07-26 18:41:30 +0000923 // FIXME: This duplicates the check performed for warn_not_in_enum below.
924 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
925 LoBeforePromotion);
926
Richard Smith077d0832014-08-04 00:40:48 +0000927 // Convert the value to the same width/sign as the condition.
928 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000929
Chris Lattner10cb5e52007-08-23 06:23:56 +0000930 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000931 if (CS->getRHS()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000932 if (CS->getRHS()->isValueDependent()) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000933 HasDependentValue = true;
934 break;
935 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000936 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000937 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000938 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000939 }
940 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000941
942 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000943 // If we don't have a default statement, check whether the
944 // condition is constant.
945 llvm::APSInt ConstantCondValue;
946 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000947 if (!HasDependentValue && !TheDefaultStmt) {
Fangrui Song407659a2018-11-30 23:41:18 +0000948 Expr::EvalResult Result;
949 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
Richard Smith077d0832014-08-04 00:40:48 +0000950 Expr::SE_AllowSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +0000951 if (Result.Val.isInt())
952 ConstantCondValue = Result.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +0000953 assert(!HasConstantCond ||
954 (ConstantCondValue.getBitWidth() == CondWidth &&
955 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000956 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000957 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000958
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000959 // Sort all the scalar case values so we can easily detect duplicates.
960 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
961
962 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000963 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
964 if (ShouldCheckConstantCond &&
965 CaseVals[i].first == ConstantCondValue)
966 ShouldCheckConstantCond = false;
967
968 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000969 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000970 // First, determine if either case value has a name
971 StringRef PrevString, CurrString;
972 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
973 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
974 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
975 PrevString = DeclRef->getDecl()->getName();
976 }
977 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
978 CurrString = DeclRef->getDecl()->getName();
979 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000980 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000981 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000982
983 if (PrevString == CurrString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000984 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
985 diag::err_duplicate_case)
986 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000987 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000988 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
989 diag::err_duplicate_case_differing_expr)
990 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
991 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
992 << CaseValStr;
Douglas Gregor9841df62012-05-16 05:32:58 +0000993
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000994 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000996 // FIXME: We really want to remove the bogus case stmt from the
997 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000998 CaseListIsErroneous = true;
999 }
1000 }
1001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 // Detect duplicate case ranges, which usually don't exist at all in
1004 // the first place.
1005 if (!CaseRanges.empty()) {
1006 // Sort all the case ranges by their low value so we can easily detect
1007 // overlaps between ranges.
1008 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +00001009
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001010 // Scan the ranges, computing the high values and removing empty ranges.
1011 std::vector<llvm::APSInt> HiVals;
1012 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +00001013 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001014 CaseStmt *CR = CaseRanges[i].second;
1015 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +00001016
Richard Smithef6c43d2018-07-26 18:41:30 +00001017 const Expr *HiBeforePromotion = Hi;
1018 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1019 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001020
Richard Smith077d0832014-08-04 00:40:48 +00001021 // Check the unconverted value is within the range of possible values of
1022 // the switch expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001023 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
Richard Smith077d0832014-08-04 00:40:48 +00001024 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1025
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001026 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001027 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001030 if (LoVal > HiVal) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001031 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001032 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001033 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001034 --i;
1035 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001036 continue;
1037 }
John McCalld3dfbd62010-05-18 03:19:21 +00001038
1039 if (ShouldCheckConstantCond &&
1040 LoVal <= ConstantCondValue &&
1041 ConstantCondValue <= HiVal)
1042 ShouldCheckConstantCond = false;
1043
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001044 HiVals.push_back(HiVal);
1045 }
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001047 // Rescan the ranges, looking for overlap with singleton values and other
1048 // ranges. Since the range list is sorted, we only need to compare case
1049 // ranges with their neighbors.
1050 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1051 llvm::APSInt &CRLo = CaseRanges[i].first;
1052 llvm::APSInt &CRHi = HiVals[i];
1053 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001054
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001055 // Check to see whether the case range overlaps with any
1056 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001057 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001058 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001059
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001060 // Find the smallest value >= the lower bound. If I is in the
1061 // case range, then we have overlap.
1062 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1063 CaseVals.end(), CRLo,
1064 CaseCompareFunctor());
1065 if (I != CaseVals.end() && I->first < CRHi) {
1066 OverlapVal = I->first; // Found overlap with scalar.
1067 OverlapStmt = I->second;
1068 }
Mike Stump11289f42009-09-09 15:08:12 +00001069
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001070 // Find the smallest value bigger than the upper bound.
1071 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1072 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1073 OverlapVal = (I-1)->first; // Found overlap with scalar.
1074 OverlapStmt = (I-1)->second;
1075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001077 // Check to see if this case stmt overlaps with the subsequent
1078 // case range.
1079 if (i && CRLo <= HiVals[i-1]) {
1080 OverlapVal = HiVals[i-1]; // Found overlap with range.
1081 OverlapStmt = CaseRanges[i-1].second;
1082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001084 if (OverlapStmt) {
1085 // If we have a duplicate, report it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001086 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1087 << OverlapVal.toString(10);
1088 Diag(OverlapStmt->getLHS()->getBeginLoc(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001089 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001090 // FIXME: We really want to remove the bogus case stmt from the
1091 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001092 CaseListIsErroneous = true;
1093 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001094 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001095 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001096
John McCalld3dfbd62010-05-18 03:19:21 +00001097 // Complain if we have a constant condition and we didn't find a match.
Richard Smithef6c43d2018-07-26 18:41:30 +00001098 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1099 ShouldCheckConstantCond) {
John McCalld3dfbd62010-05-18 03:19:21 +00001100 // TODO: it would be nice if we printed enums as enums, chars as
1101 // chars, etc.
1102 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1103 << ConstantCondValue.toString(10)
1104 << CondExpr->getSourceRange();
1105 }
1106
1107 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001108 // values. We only issue a warning if there is not 'default:', but
1109 // we still do the analysis to preserve this information in the AST
1110 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001111 //
Chris Lattner51679082010-09-16 17:09:42 +00001112 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001113
Douglas Gregorbd6839732010-02-08 22:24:16 +00001114 // If switch has default case, then ignore it.
Richard Smithef6c43d2018-07-26 18:41:30 +00001115 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1116 ET && ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001117 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001118 EnumValsTy EnumVals;
1119
John McCalld3dfbd62010-05-18 03:19:21 +00001120 // Gather all enum values, set their type and sort them,
1121 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001122 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001123 llvm::APSInt Val = EDI->getInitVal();
1124 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001125 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001126 }
1127 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001128 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001129 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001130
1131 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001132 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001133 CI != CaseVals.end(); CI++) {
1134 Expr *CaseExpr = CI->second->getLHS();
1135 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1136 CI->first))
1137 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1138 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001139 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001140
David Blaikiee476f972012-01-22 02:31:55 +00001141 // See which of case ranges aren't in enum
1142 EI = EnumVals.begin();
1143 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001144 RI != CaseRanges.end(); RI++) {
1145 Expr *CaseExpr = RI->second->getLHS();
1146 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1147 RI->first))
1148 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1149 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001150
Chad Rosier02a84392012-08-10 17:56:09 +00001151 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001152 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1153 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001154
1155 CaseExpr = RI->second->getRHS();
1156 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1157 Hi))
1158 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1159 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001161
Ted Kremenekc42f3452010-09-09 00:05:53 +00001162 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001163 auto CI = CaseVals.begin();
1164 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001165 bool hasCasesNotInSwitch = false;
1166
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001167 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168
Erik Pilkington3e4e3b12018-09-05 19:13:27 +00001169 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1170 // Don't warn about omitted unavailable EnumConstantDecls.
1171 switch (EI->second->getAvailability()) {
1172 case AR_Deprecated:
1173 // Omitting a deprecated constant is ok; it should never materialize.
1174 case AR_Unavailable:
1175 continue;
1176
1177 case AR_NotYetIntroduced:
1178 // Partially available enum constants should be present. Note that we
1179 // suppress -Wunguarded-availability diagnostics for such uses.
1180 case AR_Available:
1181 break;
1182 }
1183
Chris Lattner51679082010-09-16 17:09:42 +00001184 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001185 while (CI != CaseVals.end() && CI->first < EI->first)
1186 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187
Douglas Gregorbd6839732010-02-08 22:24:16 +00001188 if (CI != CaseVals.end() && CI->first == EI->first)
1189 continue;
1190
Ted Kremenekc42f3452010-09-09 00:05:53 +00001191 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001192 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001193 llvm::APSInt Hi =
1194 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001195 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001196 if (EI->first <= Hi)
1197 break;
1198 }
1199
Ted Kremenekc42f3452010-09-09 00:05:53 +00001200 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001201 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001202 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001203 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001206 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001207 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001208
Chris Lattner51679082010-09-16 17:09:42 +00001209 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001210 if (!UnhandledNames.empty()) {
1211 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1212 TheDefaultStmt ? diag::warn_def_missing_case
1213 : diag::warn_missing_case)
1214 << (int)UnhandledNames.size();
1215
1216 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1217 I != E; ++I)
1218 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001219 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001220
1221 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001222 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001223 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001224 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001225
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001226 if (BodyStmt)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001227 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001228 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001229
Mike Stump87c57ac2009-05-16 07:39:55 +00001230 // FIXME: If the case list was broken is some way, we don't have a good system
1231 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001232 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001233 return StmtError();
1234
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001235 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001236}
1237
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001238void
1239Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1240 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001241 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001242 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001243
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001244 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001245 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001246 SrcType->isIntegerType()) {
1247 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1248 SrcExpr->isIntegerConstantExpr(Context)) {
1249 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001250 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001251 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1252
1253 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001254 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001255 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001256
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001257 if (!ED->isClosed())
1258 return;
1259
Alexis Hunt724f14e2014-11-28 00:53:20 +00001260 if (ED->hasAttr<FlagEnumAttr>()) {
1261 if (!IsValueInFlagEnum(ED, RhsVal, true))
1262 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001263 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001264 } else {
1265 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1266 EnumValsTy;
1267 EnumValsTy EnumVals;
1268
1269 // Gather all enum values, set their type and sort them,
1270 // allowing easier comparison with rhs constant.
1271 for (auto *EDI : ED->enumerators()) {
1272 llvm::APSInt Val = EDI->getInitVal();
1273 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1274 EnumVals.push_back(std::make_pair(Val, EDI));
1275 }
1276 if (EnumVals.empty())
1277 return;
1278 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1279 EnumValsTy::iterator EIend =
1280 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1281
1282 // See which values aren't in the enum.
1283 EnumValsTy::const_iterator EI = EnumVals.begin();
1284 while (EI != EIend && EI->first < RhsVal)
1285 EI++;
1286 if (EI == EIend || EI->first != RhsVal) {
1287 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1288 << DstType.getUnqualifiedType();
1289 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001290 }
1291 }
1292 }
1293}
1294
Richard Smith03a4aa32016-06-23 19:02:52 +00001295StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1296 Stmt *Body) {
1297 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001298 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
Richard Smith03a4aa32016-06-23 19:02:52 +00001300 auto CondVal = Cond.get();
1301 CheckBreakContinueBinding(CondVal.second);
1302
1303 if (CondVal.second &&
1304 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1305 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001306
John McCallb268a282010-08-23 23:25:46 +00001307 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001308
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001309 if (isa<NullStmt>(Body))
1310 getCurCompoundScope().setHasEmptyLoopBodies();
1311
Bruno Riccibacf7512018-10-30 13:42:41 +00001312 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1313 WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001314}
1315
John McCalldadc5752010-08-24 06:29:42 +00001316StmtResult
John McCallb268a282010-08-23 23:25:46 +00001317Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001318 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001319 Expr *Cond, SourceLocation CondRParen) {
1320 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001321
Serge Pavlov09f99242014-01-23 15:05:00 +00001322 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001323 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001324 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001325 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001326 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001327
Richard Smith945f8d32013-01-14 22:39:08 +00001328 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001329 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001330 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001331 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332
Richard Trieuf3713802018-10-25 01:08:00 +00001333 // Only call the CommaVisitor for C89 due to differences in scope flags.
1334 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1335 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1336 CommaVisitor(*this).Visit(Cond);
1337
John McCallb268a282010-08-23 23:25:46 +00001338 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001339
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001340 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001341}
1342
Richard Trieu451a5db2012-04-30 18:01:30 +00001343namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001344 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1345 using DeclSetVector =
1346 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1347 llvm::SmallPtrSet<VarDecl *, 8>>;
1348
Richard Trieu451a5db2012-04-30 18:01:30 +00001349 // This visitor will traverse a conditional statement and store all
1350 // the evaluated decls into a vector. Simple is set to true if none
1351 // of the excluded constructs are used.
1352 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001353 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001354 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001355 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001356 public:
1357 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001358
Richard Trieu5fb874a2017-06-02 04:24:46 +00001359 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001360 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001361 Inherited(S.Context),
1362 Decls(Decls),
1363 Ranges(Ranges),
1364 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001365
Richard Trieu9d228802013-05-31 22:46:45 +00001366 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001367
Richard Trieu9d228802013-05-31 22:46:45 +00001368 // Replaces the method in EvaluatedExprVisitor.
1369 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001370 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001371 }
1372
1373 // Any Stmt not whitelisted will cause the condition to be marked complex.
1374 void VisitStmt(Stmt *S) {
1375 Simple = false;
1376 }
1377
1378 void VisitBinaryOperator(BinaryOperator *E) {
1379 Visit(E->getLHS());
1380 Visit(E->getRHS());
1381 }
1382
1383 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001384 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001385 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001386
Richard Trieu9d228802013-05-31 22:46:45 +00001387 void VisitUnaryOperator(UnaryOperator *E) {
1388 // Skip checking conditionals with derefernces.
1389 if (E->getOpcode() == UO_Deref)
1390 Simple = false;
1391 else
1392 Visit(E->getSubExpr());
1393 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001394
Richard Trieu9d228802013-05-31 22:46:45 +00001395 void VisitConditionalOperator(ConditionalOperator *E) {
1396 Visit(E->getCond());
1397 Visit(E->getTrueExpr());
1398 Visit(E->getFalseExpr());
1399 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001400
Richard Trieu9d228802013-05-31 22:46:45 +00001401 void VisitParenExpr(ParenExpr *E) {
1402 Visit(E->getSubExpr());
1403 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001404
Richard Trieu9d228802013-05-31 22:46:45 +00001405 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1406 Visit(E->getOpaqueValue()->getSourceExpr());
1407 Visit(E->getFalseExpr());
1408 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001409
Richard Trieu9d228802013-05-31 22:46:45 +00001410 void VisitIntegerLiteral(IntegerLiteral *E) { }
1411 void VisitFloatingLiteral(FloatingLiteral *E) { }
1412 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1413 void VisitCharacterLiteral(CharacterLiteral *E) { }
1414 void VisitGNUNullExpr(GNUNullExpr *E) { }
1415 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001416
Richard Trieu9d228802013-05-31 22:46:45 +00001417 void VisitDeclRefExpr(DeclRefExpr *E) {
1418 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
Richard Trieu6b13e892018-10-20 02:15:58 +00001419 if (!VD) {
1420 // Don't allow unhandled Decl types.
1421 Simple = false;
1422 return;
1423 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001424
Richard Trieu9d228802013-05-31 22:46:45 +00001425 Ranges.push_back(E->getSourceRange());
1426
1427 Decls.insert(VD);
1428 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001429
1430 }; // end class DeclExtractor
1431
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001432 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001433 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001434 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001435 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001436 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001437
Richard Trieu9d228802013-05-31 22:46:45 +00001438 public:
1439 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001440
Richard Trieu5fb874a2017-06-02 04:24:46 +00001441 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001442 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1443 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001444
Richard Trieu9d228802013-05-31 22:46:45 +00001445 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001446 }
1447
Richard Trieu9d228802013-05-31 22:46:45 +00001448 void VisitReturnStmt(ReturnStmt *S) {
1449 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001450 }
1451
Richard Trieu9d228802013-05-31 22:46:45 +00001452 void VisitBreakStmt(BreakStmt *S) {
1453 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001454 }
1455
Richard Trieu9d228802013-05-31 22:46:45 +00001456 void VisitGotoStmt(GotoStmt *S) {
1457 FoundDecl = true;
1458 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001459
Richard Trieu9d228802013-05-31 22:46:45 +00001460 void VisitCastExpr(CastExpr *E) {
1461 if (E->getCastKind() == CK_LValueToRValue)
1462 CheckLValueToRValueCast(E->getSubExpr());
1463 else
1464 Visit(E->getSubExpr());
1465 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001466
Richard Trieu9d228802013-05-31 22:46:45 +00001467 void CheckLValueToRValueCast(Expr *E) {
1468 E = E->IgnoreParenImpCasts();
1469
1470 if (isa<DeclRefExpr>(E)) {
1471 return;
1472 }
1473
1474 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1475 Visit(CO->getCond());
1476 CheckLValueToRValueCast(CO->getTrueExpr());
1477 CheckLValueToRValueCast(CO->getFalseExpr());
1478 return;
1479 }
1480
1481 if (BinaryConditionalOperator *BCO =
1482 dyn_cast<BinaryConditionalOperator>(E)) {
1483 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1484 CheckLValueToRValueCast(BCO->getFalseExpr());
1485 return;
1486 }
1487
1488 Visit(E);
1489 }
1490
1491 void VisitDeclRefExpr(DeclRefExpr *E) {
1492 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1493 if (Decls.count(VD))
1494 FoundDecl = true;
1495 }
1496
Steven Wu92910f62016-03-10 02:02:48 +00001497 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1498 // Only need to visit the semantics for POE.
1499 // SyntaticForm doesn't really use the Decal.
1500 for (auto *S : POE->semantics()) {
1501 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1502 // Look past the OVE into the expression it binds.
1503 Visit(OVE->getSourceExpr());
1504 else
1505 Visit(S);
1506 }
1507 }
1508
Richard Trieu9d228802013-05-31 22:46:45 +00001509 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001510
1511 }; // end class DeclMatcher
1512
1513 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1514 Expr *Third, Stmt *Body) {
1515 // Condition is empty
1516 if (!Second) return;
1517
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001518 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001519 Second->getBeginLoc()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001520 return;
1521
1522 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001523 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001524 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001525 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001526 DE.Visit(Second);
1527
1528 // Don't analyze complex conditionals.
1529 if (!DE.isSimple()) return;
1530
1531 // No decls found.
1532 if (Decls.size() == 0) return;
1533
Richard Trieu0030f1d2012-05-04 03:01:54 +00001534 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001535 for (auto *VD : Decls)
1536 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1537 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001538
1539 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1540 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1541 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1542 return;
1543
1544 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001545 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001546 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001547 } else {
1548 PDiag << (unsigned)Decls.size();
1549 for (auto *VD : Decls)
1550 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001551 }
1552
Richard Trieu5fb874a2017-06-02 04:24:46 +00001553 for (auto Range : Ranges)
1554 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001555
1556 S.Diag(Ranges.begin()->getBegin(), PDiag);
1557 }
1558
Richard Trieu4e7c9622013-08-06 21:31:54 +00001559 // If Statement is an incemement or decrement, return true and sets the
1560 // variables Increment and DRE.
1561 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1562 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001563 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1564 if (!Cleanups->cleanupsHaveSideEffects())
1565 Statement = Cleanups->getSubExpr();
1566
Richard Trieu4e7c9622013-08-06 21:31:54 +00001567 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1568 switch (UO->getOpcode()) {
1569 default: return false;
1570 case UO_PostInc:
1571 case UO_PreInc:
1572 Increment = true;
1573 break;
1574 case UO_PostDec:
1575 case UO_PreDec:
1576 Increment = false;
1577 break;
1578 }
1579 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1580 return DRE;
1581 }
1582
1583 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1584 FunctionDecl *FD = Call->getDirectCallee();
1585 if (!FD || !FD->isOverloadedOperator()) return false;
1586 switch (FD->getOverloadedOperator()) {
1587 default: return false;
1588 case OO_PlusPlus:
1589 Increment = true;
1590 break;
1591 case OO_MinusMinus:
1592 Increment = false;
1593 break;
1594 }
1595 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1596 return DRE;
1597 }
1598
1599 return false;
1600 }
1601
Serge Pavlov09f99242014-01-23 15:05:00 +00001602 // A visitor to determine if a continue or break statement is a
1603 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001604 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001605 SourceLocation BreakLoc;
1606 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001607 bool InSwitch = false;
1608
Richard Trieu4e7c9622013-08-06 21:31:54 +00001609 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001610 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001611 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001612 Visit(Body);
1613 }
1614
Eli Friedmane91b2e62017-07-04 00:52:24 +00001615 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001616
Eli Friedmane91b2e62017-07-04 00:52:24 +00001617 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001618 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001619 }
1620
Eli Friedmane91b2e62017-07-04 00:52:24 +00001621 void VisitBreakStmt(const BreakStmt* E) {
1622 if (!InSwitch)
1623 BreakLoc = E->getBreakLoc();
1624 }
1625
1626 void VisitSwitchStmt(const SwitchStmt* S) {
1627 if (const Stmt *Init = S->getInit())
1628 Visit(Init);
1629 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1630 Visit(CondVar);
1631 if (const Stmt *Cond = S->getCond())
1632 Visit(Cond);
1633
1634 // Don't return break statements from the body of a switch.
1635 InSwitch = true;
1636 if (const Stmt *Body = S->getBody())
1637 Visit(Body);
1638 InSwitch = false;
1639 }
1640
1641 void VisitForStmt(const ForStmt *S) {
1642 // Only visit the init statement of a for loop; the body
1643 // has a different break/continue scope.
1644 if (const Stmt *Init = S->getInit())
1645 Visit(Init);
1646 }
1647
1648 void VisitWhileStmt(const WhileStmt *) {
1649 // Do nothing; the children of a while loop have a different
1650 // break/continue scope.
1651 }
1652
1653 void VisitDoStmt(const DoStmt *) {
1654 // Do nothing; the children of a while loop have a different
1655 // break/continue scope.
1656 }
1657
1658 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1659 // Only visit the initialization of a for loop; the body
1660 // has a different break/continue scope.
Richard Smith8baa5002018-09-28 18:44:09 +00001661 if (const Stmt *Init = S->getInit())
1662 Visit(Init);
Eli Friedmane91b2e62017-07-04 00:52:24 +00001663 if (const Stmt *Range = S->getRangeStmt())
1664 Visit(Range);
1665 if (const Stmt *Begin = S->getBeginStmt())
1666 Visit(Begin);
1667 if (const Stmt *End = S->getEndStmt())
1668 Visit(End);
1669 }
1670
1671 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1672 // Only visit the initialization of a for loop; the body
1673 // has a different break/continue scope.
1674 if (const Stmt *Element = S->getElement())
1675 Visit(Element);
1676 if (const Stmt *Collection = S->getCollection())
1677 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001678 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001679
Serge Pavlov09f99242014-01-23 15:05:00 +00001680 bool ContinueFound() { return ContinueLoc.isValid(); }
1681 bool BreakFound() { return BreakLoc.isValid(); }
1682 SourceLocation GetContinueLoc() { return ContinueLoc; }
1683 SourceLocation GetBreakLoc() { return BreakLoc; }
1684
1685 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001686
1687 // Emit a warning when a loop increment/decrement appears twice per loop
1688 // iteration. The conditions which trigger this warning are:
1689 // 1) The last statement in the loop body and the third expression in the
1690 // for loop are both increment or both decrement of the same variable
1691 // 2) No continue statements in the loop body.
1692 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1693 // Return when there is nothing to check.
1694 if (!Body || !Third) return;
1695
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001696 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001697 Third->getBeginLoc()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001698 return;
1699
1700 // Get the last statement from the loop body.
1701 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1702 if (!CS || CS->body_empty()) return;
1703 Stmt *LastStmt = CS->body_back();
1704 if (!LastStmt) return;
1705
1706 bool LoopIncrement, LastIncrement;
1707 DeclRefExpr *LoopDRE, *LastDRE;
1708
1709 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1710 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1711
1712 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001713 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001714 if (LoopIncrement != LastIncrement ||
1715 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1716
Serge Pavlov09f99242014-01-23 15:05:00 +00001717 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001718
1719 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1720 << LastDRE->getDecl() << LastIncrement;
1721 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1722 << LoopIncrement;
1723 }
1724
Richard Trieu451a5db2012-04-30 18:01:30 +00001725} // end namespace
1726
Serge Pavlov09f99242014-01-23 15:05:00 +00001727
1728void Sema::CheckBreakContinueBinding(Expr *E) {
1729 if (!E || getLangOpts().CPlusPlus)
1730 return;
1731 BreakContinueFinder BCFinder(*this, E);
1732 Scope *BreakParent = CurScope->getBreakParent();
1733 if (BCFinder.BreakFound() && BreakParent) {
1734 if (BreakParent->getFlags() & Scope::SwitchScope) {
1735 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1736 } else {
1737 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1738 << "break";
1739 }
1740 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1741 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1742 << "continue";
1743 }
1744}
1745
Richard Smith03a4aa32016-06-23 19:02:52 +00001746StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1747 Stmt *First, ConditionResult Second,
1748 FullExprArg third, SourceLocation RParenLoc,
1749 Stmt *Body) {
1750 if (Second.isInvalid())
1751 return StmtError();
1752
David Blaikiebbafb8a2012-03-11 07:00:24 +00001753 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001754 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001755 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1756 // declare identifiers for objects having storage class 'auto' or
1757 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001758 for (auto *DI : DS->decls()) {
1759 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001760 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001761 VD = nullptr;
1762 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001763 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1764 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001765 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001766 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001767 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001768 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001769
Richard Smith03a4aa32016-06-23 19:02:52 +00001770 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001771 CheckBreakContinueBinding(third.get());
1772
Richard Smith03a4aa32016-06-23 19:02:52 +00001773 if (!Second.get().first)
1774 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1775 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001776 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001777
Richard Smith03a4aa32016-06-23 19:02:52 +00001778 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001779 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001780 Second.get().second->getExprLoc()))
1781 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001782
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001783 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Anders Carlsson1682af52009-08-01 01:39:59 +00001785 DiagnoseUnusedExprResult(First);
1786 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001787 DiagnoseUnusedExprResult(Body);
1788
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001789 if (isa<NullStmt>(Body))
1790 getCurCompoundScope().setHasEmptyLoopBodies();
1791
Richard Smith03a4aa32016-06-23 19:02:52 +00001792 return new (Context)
1793 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1794 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001795}
1796
John McCall34376a62010-12-04 03:47:34 +00001797/// In an Objective C collection iteration statement:
1798/// for (x in y)
1799/// x can be an arbitrary l-value expression. Bind it up as a
1800/// full-expression.
1801StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001802 // Reduce placeholder expressions here. Note that this rejects the
1803 // use of pseudo-object l-values in this position.
1804 ExprResult result = CheckPlaceholderExpr(E);
1805 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001806 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001807
Richard Smith945f8d32013-01-14 22:39:08 +00001808 ExprResult FullExpr = ActOnFinishFullExpr(E);
1809 if (FullExpr.isInvalid())
1810 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001811 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001812}
1813
John McCall53848232011-07-27 01:07:15 +00001814ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001815Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1816 if (!collection)
1817 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001818
Kaelyn Takata15867822014-11-21 18:48:04 +00001819 ExprResult result = CorrectDelayedTyposInExpr(collection);
1820 if (!result.isUsable())
1821 return ExprError();
1822 collection = result.get();
1823
John McCall53848232011-07-27 01:07:15 +00001824 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001825 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001826
1827 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001828 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001829 if (result.isInvalid())
1830 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001831 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001832
1833 // The operand needs to have object-pointer type.
1834 // TODO: should we do a contextual conversion?
1835 const ObjCObjectPointerType *pointerType =
1836 collection->getType()->getAs<ObjCObjectPointerType>();
1837 if (!pointerType)
1838 return Diag(forLoc, diag::err_collection_expr_type)
1839 << collection->getType() << collection->getSourceRange();
1840
1841 // Check that the operand provides
1842 // - countByEnumeratingWithState:objects:count:
1843 const ObjCObjectType *objectType = pointerType->getObjectType();
1844 ObjCInterfaceDecl *iface = objectType->getInterface();
1845
1846 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001847 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001848 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001849 (getLangOpts().ObjCAutoRefCount
1850 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1851 diag::err_arc_collection_forward, collection)
1852 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001853 // Otherwise, if we have any useful type information, check that
1854 // the type declares the appropriate method.
1855 } else if (iface || !objectType->qual_empty()) {
1856 IdentifierInfo *selectorIdents[] = {
1857 &Context.Idents.get("countByEnumeratingWithState"),
1858 &Context.Idents.get("objects"),
1859 &Context.Idents.get("count")
1860 };
1861 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1862
Craig Topperc3ec1492014-05-26 06:22:03 +00001863 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001864
1865 // If there's an interface, look in both the public and private APIs.
1866 if (iface) {
1867 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001868 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001869 }
1870
1871 // Also check protocol qualifiers.
1872 if (!method)
1873 method = LookupMethodInQualifiedType(selector, pointerType,
1874 /*instance*/ true);
1875
1876 // If we didn't find it anywhere, give up.
1877 if (!method) {
1878 Diag(forLoc, diag::warn_collection_expr_type)
1879 << collection->getType() << selector << collection->getSourceRange();
1880 }
1881
1882 // TODO: check for an incompatible signature?
1883 }
1884
1885 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001886 return collection;
John McCall53848232011-07-27 01:07:15 +00001887}
1888
John McCalldadc5752010-08-24 06:29:42 +00001889StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001890Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001891 Stmt *First, Expr *collection,
1892 SourceLocation RParenLoc) {
Reid Kleckner87a31802018-03-12 21:43:02 +00001893 setFunctionHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001894
1895 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001896 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001897
Fariborz Jahanian93977672008-01-10 20:33:58 +00001898 if (First) {
1899 QualType FirstType;
1900 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001901 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001902 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1903 diag::err_toomany_element_decls));
1904
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001905 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1906 if (!D || D->isInvalidDecl())
1907 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001908
John McCall31168b02011-06-15 23:02:42 +00001909 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001910 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1911 // declare identifiers for objects having storage class 'auto' or
1912 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001913 if (!D->hasLocalStorage())
1914 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001915 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001916
1917 // If the type contained 'auto', deduce the 'auto' to 'id'.
1918 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001919 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1920 VK_RValue);
1921 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001922 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1923 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001924 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001925 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001926 D->setInvalidDecl();
1927 return StmtError();
1928 }
1929
Richard Smith061f1e22013-04-30 21:23:01 +00001930 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001931
Richard Smith51ec0cf2017-02-21 01:17:38 +00001932 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001933 SourceLocation Loc =
1934 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001935 Diag(Loc, diag::warn_auto_var_is_id)
1936 << D->getDeclName();
1937 }
1938 }
1939
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001940 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001941 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001942 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001943 return StmtError(
1944 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1945 << First->getSourceRange());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001946
Mike Stump11289f42009-09-09 15:08:12 +00001947 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001948 if (FirstType.isConstQualified())
1949 Diag(ForLoc, diag::err_selector_element_const_type)
1950 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001951 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001952 if (!FirstType->isDependentType() &&
1953 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001954 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001955 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1956 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001957 }
Chad Rosier02a84392012-08-10 17:56:09 +00001958
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001959 if (CollectionExprResult.isInvalid())
1960 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001961
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001962 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001963 if (CollectionExprResult.isInvalid())
1964 return StmtError();
1965
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001966 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1967 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001968}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001969
Richard Smith02e85f32011-04-14 22:09:26 +00001970/// Finish building a variable declaration for a for-range statement.
1971/// \return true if an error occurs.
1972static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001973 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001974 if (Decl->getType()->isUndeducedType()) {
1975 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1976 if (!Res.isUsable()) {
1977 Decl->setInvalidDecl();
1978 return true;
1979 }
1980 Init = Res.get();
1981 }
1982
Richard Smith02e85f32011-04-14 22:09:26 +00001983 // Deduce the type for the iterator variable now rather than leaving it to
1984 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001985 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001986 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001987 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001988 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001989 SemaRef.Diag(Loc, DiagID) << Init->getType();
1990 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001991 Decl->setInvalidDecl();
1992 return true;
1993 }
Richard Smith061f1e22013-04-30 21:23:01 +00001994 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001995
John McCall31168b02011-06-15 23:02:42 +00001996 // In ARC, infer lifetime.
1997 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1998 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001999 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002000 SemaRef.inferObjCARCLifetime(Decl))
2001 Decl->setInvalidDecl();
2002
Richard Smith3beb7c62017-01-12 02:27:38 +00002003 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002004 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00002005 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00002006 return false;
2007}
2008
Sam Panzer0f384432012-08-21 00:52:01 +00002009namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00002010// An enum to represent whether something is dealing with a call to begin()
2011// or a call to end() in a range-based for loop.
2012enum BeginEndFunction {
2013 BEF_begin,
2014 BEF_end
2015};
Sam Panzer0f384432012-08-21 00:52:01 +00002016
Richard Smith02e85f32011-04-14 22:09:26 +00002017/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00002018/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00002019/// nor from the diagnostics produced when analysing the implicit expressions
2020/// required in a for-range statement.
2021void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00002022 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00002023 CallExpr *CE = dyn_cast<CallExpr>(E);
2024 if (!CE)
2025 return;
2026 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2027 if (!D)
2028 return;
2029 SourceLocation Loc = D->getLocation();
2030
2031 std::string Description;
2032 bool IsTemplate = false;
2033 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2034 Description = SemaRef.getTemplateArgumentBindingsText(
2035 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2036 IsTemplate = true;
2037 }
2038
2039 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2040 << BEF << IsTemplate << Description << E->getType();
2041}
2042
Sam Panzer0f384432012-08-21 00:52:01 +00002043/// Build a variable declaration for a for-range statement.
2044VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
Matt Davisb8402ef2018-02-14 21:22:11 +00002045 QualType Type, StringRef Name) {
Sam Panzer0f384432012-08-21 00:52:01 +00002046 DeclContext *DC = SemaRef.CurContext;
2047 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2048 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2049 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002050 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002051 Decl->setImplicit();
2052 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002053}
2054
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002055}
Richard Smith02e85f32011-04-14 22:09:26 +00002056
Fariborz Jahanian00213472012-07-06 19:04:04 +00002057static bool ObjCEnumerationCollection(Expr *Collection) {
2058 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002059 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002060}
2061
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002062/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002063///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002064/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002065/// A range-based for statement is equivalent to
2066///
2067/// {
2068/// auto && __range = range-init;
2069/// for ( auto __begin = begin-expr,
2070/// __end = end-expr;
2071/// __begin != __end;
2072/// ++__begin ) {
2073/// for-range-declaration = *__begin;
2074/// statement
2075/// }
2076/// }
2077///
2078/// The body of the loop is not available yet, since it cannot be analysed until
2079/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002080StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002081 SourceLocation CoawaitLoc, Stmt *InitStmt,
2082 Stmt *First, SourceLocation ColonLoc,
2083 Expr *Range, SourceLocation RParenLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +00002084 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002085 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002086 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002087
Richard Smith8baa5002018-09-28 18:44:09 +00002088 if (Range && ObjCEnumerationCollection(Range)) {
2089 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2090 if (InitStmt)
2091 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2092 << InitStmt->getSourceRange();
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002093 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith8baa5002018-09-28 18:44:09 +00002094 }
Richard Smith02e85f32011-04-14 22:09:26 +00002095
2096 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2097 assert(DS && "first part of for range not a decl stmt");
2098
2099 if (!DS->isSingleDecl()) {
Stephen Kellya6e43582018-08-09 21:05:56 +00002100 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
Richard Smith02e85f32011-04-14 22:09:26 +00002101 return StmtError();
2102 }
Richard Smith02e85f32011-04-14 22:09:26 +00002103
Richard Smith3249fed2013-08-21 01:40:36 +00002104 Decl *LoopVar = DS->getSingleDecl();
2105 if (LoopVar->isInvalidDecl() || !Range ||
2106 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2107 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002108 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002109 }
Richard Smith02e85f32011-04-14 22:09:26 +00002110
Eric Fiselierb936a392017-06-14 03:24:55 +00002111 // Build the coroutine state immediately and not later during template
2112 // instantiation
2113 if (!CoawaitLoc.isInvalid()) {
2114 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2115 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002116 }
2117
Richard Smith02e85f32011-04-14 22:09:26 +00002118 // Build auto && __range = range-init
Matt Davisb8402ef2018-02-14 21:22:11 +00002119 // Divide by 2, since the variables are in the inner scope (loop body).
2120 const auto DepthStr = std::to_string(S->getDepth() / 2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002121 SourceLocation RangeLoc = Range->getBeginLoc();
Richard Smith02e85f32011-04-14 22:09:26 +00002122 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2123 Context.getAutoRRefDeductType(),
Matt Davisb8402ef2018-02-14 21:22:11 +00002124 std::string("__range") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002125 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002126 diag::err_for_range_deduction_failure)) {
2127 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002128 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002129 }
Richard Smith02e85f32011-04-14 22:09:26 +00002130
2131 // Claim the type doesn't contain auto: we've already done the checking.
2132 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002133 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002134 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002135 if (RangeDecl.isInvalid()) {
2136 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002137 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002138 }
Richard Smith02e85f32011-04-14 22:09:26 +00002139
Richard Smith8baa5002018-09-28 18:44:09 +00002140 return BuildCXXForRangeStmt(
2141 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2142 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2143 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002144}
2145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002146/// Create the initialization, compare, and increment steps for
Sam Panzer0f384432012-08-21 00:52:01 +00002147/// the range-based for loop expression.
2148/// This function does not handle array-based for loops,
2149/// which are created in Sema::BuildCXXForRangeStmt.
2150///
2151/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2152/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2153/// CandidateSet and BEF are set and some non-success value is returned on
2154/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002155static Sema::ForRangeStatus
2156BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2157 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2158 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2159 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2160 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002161 DeclarationNameInfo BeginNameInfo(
2162 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2163 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2164 ColonLoc);
2165
2166 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2167 Sema::LookupMemberName);
2168 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2169
Richard Smith236ffde2018-09-24 23:17:44 +00002170 auto BuildBegin = [&] {
2171 *BEF = BEF_begin;
2172 Sema::ForRangeStatus RangeStatus =
2173 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2174 BeginMemberLookup, CandidateSet,
2175 BeginRange, BeginExpr);
2176
2177 if (RangeStatus != Sema::FRS_Success) {
2178 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2179 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2180 << ColonLoc << BEF_begin << BeginRange->getType();
2181 return RangeStatus;
2182 }
2183 if (!CoawaitLoc.isInvalid()) {
2184 // FIXME: getCurScope() should not be used during template instantiation.
2185 // We should pick up the set of unqualified lookup results for operator
2186 // co_await during the initial parse.
2187 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2188 BeginExpr->get());
2189 if (BeginExpr->isInvalid())
2190 return Sema::FRS_DiagnosticIssued;
2191 }
2192 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2193 diag::err_for_range_iter_deduction_failure)) {
2194 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2195 return Sema::FRS_DiagnosticIssued;
2196 }
2197 return Sema::FRS_Success;
2198 };
2199
2200 auto BuildEnd = [&] {
2201 *BEF = BEF_end;
2202 Sema::ForRangeStatus RangeStatus =
2203 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2204 EndMemberLookup, CandidateSet,
2205 EndRange, EndExpr);
2206 if (RangeStatus != Sema::FRS_Success) {
2207 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2208 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2209 << ColonLoc << BEF_end << EndRange->getType();
2210 return RangeStatus;
2211 }
2212 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2213 diag::err_for_range_iter_deduction_failure)) {
2214 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2215 return Sema::FRS_DiagnosticIssued;
2216 }
2217 return Sema::FRS_Success;
2218 };
2219
Sam Panzer0f384432012-08-21 00:52:01 +00002220 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2221 // - if _RangeT is a class type, the unqualified-ids begin and end are
2222 // looked up in the scope of class _RangeT as if by class member access
2223 // lookup (3.4.5), and if either (or both) finds at least one
2224 // declaration, begin-expr and end-expr are __range.begin() and
2225 // __range.end(), respectively;
2226 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002227 if (BeginMemberLookup.isAmbiguous())
2228 return Sema::FRS_DiagnosticIssued;
2229
Sam Panzer0f384432012-08-21 00:52:01 +00002230 SemaRef.LookupQualifiedName(EndMemberLookup, D);
Richard Smith236ffde2018-09-24 23:17:44 +00002231 if (EndMemberLookup.isAmbiguous())
2232 return Sema::FRS_DiagnosticIssued;
Sam Panzer0f384432012-08-21 00:52:01 +00002233
2234 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
Richard Smith236ffde2018-09-24 23:17:44 +00002235 // Look up the non-member form of the member we didn't find, first.
2236 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2237 // a 'begin' but ignored it because there was no member 'end'"
2238 // diagnostic.
2239 auto BuildNonmember = [&](
2240 BeginEndFunction BEFFound, LookupResult &Found,
2241 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2242 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2243 LookupResult OldFound = std::move(Found);
2244 Found.clear();
Sam Panzer0f384432012-08-21 00:52:01 +00002245
Richard Smith236ffde2018-09-24 23:17:44 +00002246 if (Sema::ForRangeStatus Result = BuildNotFound())
2247 return Result;
2248
2249 switch (BuildFound()) {
2250 case Sema::FRS_Success:
2251 return Sema::FRS_Success;
2252
2253 case Sema::FRS_NoViableFunction:
2254 SemaRef.Diag(BeginRange->getBeginLoc(), diag::err_for_range_invalid)
2255 << BeginRange->getType() << BEFFound;
2256 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, BeginRange);
2257 LLVM_FALLTHROUGH;
2258
2259 case Sema::FRS_DiagnosticIssued:
2260 for (NamedDecl *D : OldFound) {
2261 SemaRef.Diag(D->getLocation(),
2262 diag::note_for_range_member_begin_end_ignored)
2263 << BeginRange->getType() << BEFFound;
2264 }
2265 return Sema::FRS_DiagnosticIssued;
2266 }
2267 llvm_unreachable("unexpected ForRangeStatus");
2268 };
2269 if (BeginMemberLookup.empty())
2270 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2271 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
Sam Panzer0f384432012-08-21 00:52:01 +00002272 }
2273 } else {
2274 // - otherwise, begin-expr and end-expr are begin(__range) and
2275 // end(__range), respectively, where begin and end are looked up with
2276 // argument-dependent lookup (3.4.2). For the purposes of this name
2277 // lookup, namespace std is an associated namespace.
Sam Panzer0f384432012-08-21 00:52:01 +00002278 }
2279
Richard Smith236ffde2018-09-24 23:17:44 +00002280 if (Sema::ForRangeStatus Result = BuildBegin())
2281 return Result;
2282 return BuildEnd();
Sam Panzer0f384432012-08-21 00:52:01 +00002283}
2284
2285/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002286/// If the attempt fails, this function will return a valid, null StmtResult
2287/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002288static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2289 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002290 SourceLocation CoawaitLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002291 Stmt *InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002292 Stmt *LoopVarDecl,
2293 SourceLocation ColonLoc,
2294 Expr *Range,
2295 SourceLocation RangeLoc,
2296 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002297 // Determine whether we can rebuild the for-range statement with a
2298 // dereferenced range expression.
2299 ExprResult AdjustedRange;
2300 {
2301 Sema::SFINAETrap Trap(SemaRef);
2302
2303 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2304 if (AdjustedRange.isInvalid())
2305 return StmtResult();
2306
Richard Smith9f690bd2015-10-27 06:02:45 +00002307 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002308 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2309 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002310 if (SR.isInvalid())
2311 return StmtResult();
2312 }
2313
2314 // The attempt to dereference worked well enough that it could produce a valid
2315 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2316 // case there are any other (non-fatal) problems with it.
2317 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2318 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith8baa5002018-09-28 18:44:09 +00002319 return SemaRef.ActOnCXXForRangeStmt(
2320 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2321 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002322}
2323
Richard Smith3249fed2013-08-21 01:40:36 +00002324namespace {
2325/// RAII object to automatically invalidate a declaration if an error occurs.
2326struct InvalidateOnErrorScope {
2327 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2328 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2329 ~InvalidateOnErrorScope() {
2330 if (Enabled && Trap.hasErrorOccurred())
2331 D->setInvalidDecl();
2332 }
2333
2334 DiagnosticErrorTrap Trap;
2335 Decl *D;
2336 bool Enabled;
2337};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002338}
Richard Smith3249fed2013-08-21 01:40:36 +00002339
Richard Smitha05b3b52012-09-20 21:52:32 +00002340/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith8baa5002018-09-28 18:44:09 +00002341StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2342 SourceLocation CoawaitLoc, Stmt *InitStmt,
2343 SourceLocation ColonLoc, Stmt *RangeDecl,
2344 Stmt *Begin, Stmt *End, Expr *Cond,
2345 Expr *Inc, Stmt *LoopVarDecl,
2346 SourceLocation RParenLoc,
2347 BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002348 // FIXME: This should not be used during template instantiation. We should
2349 // pick up the set of unqualified lookup results for the != and + operators
2350 // in the initial parse.
2351 //
2352 // Testcase (accepts-invalid):
2353 // template<typename T> void f() { for (auto x : T()) {} }
2354 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2355 // bool operator!=(N::X, N::X); void operator++(N::X);
2356 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002357 Scope *S = getCurScope();
2358
2359 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2360 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2361 QualType RangeVarType = RangeVar->getType();
2362
2363 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2364 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2365
Richard Smith3249fed2013-08-21 01:40:36 +00002366 // If we hit any errors, mark the loop variable as invalid if its type
2367 // contains 'auto'.
2368 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2369 LoopVar->getType()->isUndeducedType());
2370
Richard Smith01694c32016-03-20 10:33:40 +00002371 StmtResult BeginDeclStmt = Begin;
2372 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002373 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2374
Richard Smith27d807c2013-04-30 13:56:41 +00002375 if (RangeVarType->isDependentType()) {
2376 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002377 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002378
2379 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2380 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002381 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2382 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2383 for (auto *Binding : DD->bindings())
2384 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002385 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002386 }
Richard Smith01694c32016-03-20 10:33:40 +00002387 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002388 SourceLocation RangeLoc = RangeVar->getLocation();
2389
Ted Kremenekbed648e2011-10-10 22:36:28 +00002390 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2391
2392 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2393 VK_LValue, ColonLoc);
2394 if (BeginRangeRef.isInvalid())
2395 return StmtError();
2396
2397 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2398 VK_LValue, ColonLoc);
2399 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002400 return StmtError();
2401
2402 QualType AutoType = Context.getAutoDeductType();
2403 Expr *Range = RangeVar->getInit();
2404 if (!Range)
2405 return StmtError();
2406 QualType RangeType = Range->getType();
2407
2408 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002409 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002410 return StmtError();
2411
2412 // Build auto __begin = begin-expr, __end = end-expr.
Matt Davisb8402ef2018-02-14 21:22:11 +00002413 // Divide by 2, since the variables are in the inner scope (loop body).
2414 const auto DepthStr = std::to_string(S->getDepth() / 2);
Richard Smith02e85f32011-04-14 22:09:26 +00002415 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002416 std::string("__begin") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002417 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
Matt Davisb8402ef2018-02-14 21:22:11 +00002418 std::string("__end") + DepthStr);
Richard Smith02e85f32011-04-14 22:09:26 +00002419
2420 // Build begin-expr and end-expr and attach to __begin and __end variables.
2421 ExprResult BeginExpr, EndExpr;
2422 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2423 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2424 // __range + __bound, respectively, where __bound is the array bound. If
2425 // _RangeT is an array of unknown size or an array of incomplete type,
2426 // the program is ill-formed;
2427
2428 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002429 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002430 if (!CoawaitLoc.isInvalid()) {
2431 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2432 if (BeginExpr.isInvalid())
2433 return StmtError();
2434 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002435 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002436 diag::err_for_range_iter_deduction_failure)) {
2437 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2438 return StmtError();
2439 }
2440
2441 // Find the array bound.
2442 ExprResult BoundExpr;
2443 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002444 BoundExpr = IntegerLiteral::Create(
2445 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002446 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002447 dyn_cast<VariableArrayType>(UnqAT)) {
2448 // For a variably modified type we can't just use the expression within
2449 // the array bounds, since we don't want that to be re-evaluated here.
2450 // Rather, we need to determine what it was when the array was first
2451 // created - so we resort to using sizeof(vla)/sizeof(element).
2452 // For e.g.
Fangrui Song6907ce22018-07-30 19:24:48 +00002453 // void f(int b) {
Faisal Vali1ca2d962017-05-15 01:49:19 +00002454 // int vla[b];
2455 // b = -1; <-- This should not affect the num of iterations below
2456 // for (int &c : vla) { .. }
2457 // }
2458
2459 // FIXME: This results in codegen generating IR that recalculates the
2460 // run-time number of elements (as opposed to just using the IR Value
2461 // that corresponds to the run-time value of each bound that was
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002462 // generated when the array was created.) If this proves too embarrassing
Faisal Vali1ca2d962017-05-15 01:49:19 +00002463 // even for unoptimized IR, consider passing a magic-value/cookie to
2464 // codegen that then knows to simply use that initial llvm::Value (that
2465 // corresponds to the bound at time of array creation) within
2466 // getelementptr. But be prepared to pay the price of increasing a
2467 // customized form of coupling between the two components - which could
2468 // be hard to maintain as the codebase evolves.
2469
2470 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2471 EndVar->getLocation(), UETT_SizeOf,
2472 /*isType=*/true,
2473 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2474 VAT->desugar(), RangeLoc))
2475 .getAsOpaquePtr(),
2476 EndVar->getSourceRange());
2477 if (SizeOfVLAExprR.isInvalid())
2478 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002479
Faisal Vali1ca2d962017-05-15 01:49:19 +00002480 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2481 EndVar->getLocation(), UETT_SizeOf,
2482 /*isType=*/true,
2483 CreateParsedType(VAT->desugar(),
2484 Context.getTrivialTypeSourceInfo(
2485 VAT->getElementType(), RangeLoc))
2486 .getAsOpaquePtr(),
2487 EndVar->getSourceRange());
2488 if (SizeOfEachElementExprR.isInvalid())
2489 return StmtError();
2490
2491 BoundExpr =
2492 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2493 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2494 if (BoundExpr.isInvalid())
2495 return StmtError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002496
Faisal Vali1ca2d962017-05-15 01:49:19 +00002497 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002498 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2499 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002500 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002501 }
2502
2503 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002504 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002505 BoundExpr.get());
2506 if (EndExpr.isInvalid())
2507 return StmtError();
2508 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2509 diag::err_for_range_iter_deduction_failure)) {
2510 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2511 return StmtError();
2512 }
2513 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002514 OverloadCandidateSet CandidateSet(RangeLoc,
2515 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002516 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002517 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2518 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2519 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2520 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002521
Richard Smitha05b3b52012-09-20 21:52:32 +00002522 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002523 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002524 // If the range is being built from an array parameter, emit a
2525 // a diagnostic that it is being treated as a pointer.
2526 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2527 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2528 QualType ArrayTy = PVD->getOriginalType();
2529 QualType PointerTy = PVD->getType();
2530 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002531 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2532 << RangeLoc << PVD << ArrayTy << PointerTy;
Richard Trieu08254692013-10-11 22:16:04 +00002533 Diag(PVD->getLocation(), diag::note_declared_at);
2534 return StmtError();
2535 }
2536 }
2537 }
2538
2539 // If building the range failed, try dereferencing the range expression
2540 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002541 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smith8baa5002018-09-28 18:44:09 +00002542 CoawaitLoc, InitStmt,
Sam Panzer0f384432012-08-21 00:52:01 +00002543 LoopVarDecl, ColonLoc,
2544 Range, RangeLoc,
2545 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002546 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002547 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002548 }
2549
Sam Panzer0f384432012-08-21 00:52:01 +00002550 // Otherwise, emit diagnostics if we haven't already.
2551 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002552 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002553 Diag(Range->getBeginLoc(), diag::err_for_range_invalid)
Sam Panzer0f384432012-08-21 00:52:01 +00002554 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002555 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002556 }
2557 // Return an error if no fix was discovered.
2558 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002559 return StmtError();
2560 }
2561
Sam Panzer0f384432012-08-21 00:52:01 +00002562 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2563 "invalid range expression in for loop");
2564
2565 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002566 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002567 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2568 if (!Context.hasSameType(BeginType, EndType)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002569 Diag(RangeLoc, getLangOpts().CPlusPlus17
Richard Smith01694c32016-03-20 10:33:40 +00002570 ? diag::warn_for_range_begin_end_types_differ
2571 : diag::ext_for_range_begin_end_types_differ)
2572 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002573 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2574 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2575 }
2576
Richard Smith01694c32016-03-20 10:33:40 +00002577 BeginDeclStmt =
2578 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2579 EndDeclStmt =
2580 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002581
Ted Kremenekbed648e2011-10-10 22:36:28 +00002582 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2583 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002584 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002585 if (BeginRef.isInvalid())
2586 return StmtError();
2587
Richard Smith02e85f32011-04-14 22:09:26 +00002588 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2589 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002590 if (EndRef.isInvalid())
2591 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002592
2593 // Build and check __begin != __end expression.
2594 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2595 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002596 if (!NotEqExpr.isInvalid())
2597 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2598 if (!NotEqExpr.isInvalid())
2599 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002600 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002601 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2602 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002603 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2604 if (!Context.hasSameType(BeginType, EndType))
2605 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2606 return StmtError();
2607 }
2608
2609 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002610 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2611 VK_LValue, ColonLoc);
2612 if (BeginRef.isInvalid())
2613 return StmtError();
2614
Richard Smith02e85f32011-04-14 22:09:26 +00002615 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002616 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002617 // FIXME: getCurScope() should not be used during template instantiation.
2618 // We should pick up the set of unqualified lookup results for operator
2619 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002620 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002621 if (!IncrExpr.isInvalid())
2622 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002623 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002624 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2625 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002626 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2627 return StmtError();
2628 }
2629
2630 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002631 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2632 VK_LValue, ColonLoc);
2633 if (BeginRef.isInvalid())
2634 return StmtError();
2635
Richard Smith02e85f32011-04-14 22:09:26 +00002636 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2637 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002638 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2639 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002640 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2641 return StmtError();
2642 }
2643
Richard Smitha05b3b52012-09-20 21:52:32 +00002644 // Attach *__begin as initializer for VD. Don't touch it if we're just
2645 // trying to determine whether this would be a valid range.
2646 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002647 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002648 if (LoopVar->isInvalidDecl())
2649 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2650 }
2651 }
2652
Richard Smitha05b3b52012-09-20 21:52:32 +00002653 // Don't bother to actually allocate the result if we're just trying to
2654 // determine whether it would be valid.
2655 if (Kind == BFRK_Check)
2656 return StmtResult();
2657
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002658 return new (Context) CXXForRangeStmt(
Richard Smith8baa5002018-09-28 18:44:09 +00002659 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
Richard Smith01694c32016-03-20 10:33:40 +00002660 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002661 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2662 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002663}
2664
Chad Rosier02a84392012-08-10 17:56:09 +00002665/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002666/// statement.
2667StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2668 if (!S || !B)
2669 return StmtError();
2670 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002671
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002672 ForStmt->setBody(B);
2673 return S;
2674}
2675
Richard Trieu3e1d4832015-04-13 22:08:55 +00002676// Warn when the loop variable is a const reference that creates a copy.
2677// Suggest using the non-reference type for copies. If a copy can be prevented
2678// suggest the const reference type that would do so.
2679// For instance, given "for (const &Foo : Range)", suggest
2680// "for (const Foo : Range)" to denote a copy is made for the loop. If
2681// possible, also suggest "for (const &Bar : Range)" if this type prevents
2682// the copy altogether.
2683static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2684 const VarDecl *VD,
2685 QualType RangeInitType) {
2686 const Expr *InitExpr = VD->getInit();
2687 if (!InitExpr)
2688 return;
2689
2690 QualType VariableType = VD->getType();
2691
Tim Shen4a05bb82016-06-21 20:29:17 +00002692 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2693 if (!Cleanups->cleanupsHaveSideEffects())
2694 InitExpr = Cleanups->getSubExpr();
2695
Richard Trieu3e1d4832015-04-13 22:08:55 +00002696 const MaterializeTemporaryExpr *MTE =
2697 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2698
2699 // No copy made.
2700 if (!MTE)
2701 return;
2702
2703 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2704
2705 // Searching for either UnaryOperator for dereference of a pointer or
2706 // CXXOperatorCallExpr for handling iterators.
2707 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2708 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2709 E = CCE->getArg(0);
2710 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2711 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2712 E = ME->getBase();
2713 } else {
2714 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2715 E = MTE->GetTemporaryExpr();
2716 }
2717 E = E->IgnoreImpCasts();
2718 }
2719
2720 bool ReturnsReference = false;
2721 if (isa<UnaryOperator>(E)) {
2722 ReturnsReference = true;
2723 } else {
2724 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2725 const FunctionDecl *FD = Call->getDirectCallee();
2726 QualType ReturnType = FD->getReturnType();
2727 ReturnsReference = ReturnType->isReferenceType();
2728 }
2729
2730 if (ReturnsReference) {
2731 // Loop variable creates a temporary. Suggest either to go with
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002732 // non-reference loop variable to indicate a copy is made, or
Richard Trieu3e1d4832015-04-13 22:08:55 +00002733 // the correct time to bind a const reference.
2734 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2735 << VD << VariableType << E->getType();
2736 QualType NonReferenceType = VariableType.getNonReferenceType();
2737 NonReferenceType.removeLocalConst();
2738 QualType NewReferenceType =
2739 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002740 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002741 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2742 } else {
2743 // The range always returns a copy, so a temporary is always created.
2744 // Suggest removing the reference from the loop variable.
2745 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2746 << VD << RangeInitType;
2747 QualType NonReferenceType = VariableType.getNonReferenceType();
2748 NonReferenceType.removeLocalConst();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002749 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002750 << NonReferenceType << VD->getSourceRange();
2751 }
2752}
2753
2754// Warns when the loop variable can be changed to a reference type to
2755// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2756// "for (const Foo &x : Range)" if this form does not make a copy.
2757static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2758 const VarDecl *VD) {
2759 const Expr *InitExpr = VD->getInit();
2760 if (!InitExpr)
2761 return;
2762
2763 QualType VariableType = VD->getType();
2764
2765 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2766 if (!CE->getConstructor()->isCopyConstructor())
2767 return;
2768 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2769 if (CE->getCastKind() != CK_LValueToRValue)
2770 return;
2771 } else {
2772 return;
2773 }
2774
2775 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2776 // should be emitted. Also, only ignore POD types with trivial copy
2777 // constructors.
2778 if (VariableType.isPODType(SemaRef.Context))
2779 return;
2780
2781 // Suggest changing from a const variable to a const reference variable
2782 // if doing so will prevent a copy.
2783 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2784 << VD << VariableType << InitExpr->getType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002785 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
Richard Trieu3e1d4832015-04-13 22:08:55 +00002786 << SemaRef.Context.getLValueReferenceType(VariableType)
2787 << VD->getSourceRange();
2788}
2789
2790/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2791/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2792/// using "const foo x" to show that a copy is made
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002793/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
Richard Trieu3e1d4832015-04-13 22:08:55 +00002794/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2795/// prevent the copy.
2796/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2797/// Suggest "const foo &x" to prevent the copy.
2798static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2799 const CXXForRangeStmt *ForStmt) {
2800 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002801 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002802 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002803 ForStmt->getBeginLoc()) &&
Richard Trieu3e1d4832015-04-13 22:08:55 +00002804 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002805 ForStmt->getBeginLoc())) {
Richard Trieu3e1d4832015-04-13 22:08:55 +00002806 return;
2807 }
2808
2809 const VarDecl *VD = ForStmt->getLoopVariable();
2810 if (!VD)
2811 return;
2812
2813 QualType VariableType = VD->getType();
2814
2815 if (VariableType->isIncompleteType())
2816 return;
2817
2818 const Expr *InitExpr = VD->getInit();
2819 if (!InitExpr)
2820 return;
2821
2822 if (VariableType->isReferenceType()) {
2823 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2824 ForStmt->getRangeInit()->getType());
2825 } else if (VariableType.isConstQualified()) {
2826 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2827 }
2828}
2829
Richard Smith02e85f32011-04-14 22:09:26 +00002830/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2831/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2832/// body cannot be performed until after the type of the range variable is
2833/// determined.
2834StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2835 if (!S || !B)
2836 return StmtError();
2837
Fariborz Jahanian00213472012-07-06 19:04:04 +00002838 if (isa<ObjCForCollectionStmt>(S))
2839 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002840
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002841 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2842 ForStmt->setBody(B);
2843
2844 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2845 diag::warn_empty_range_based_for_body);
2846
Richard Trieu3e1d4832015-04-13 22:08:55 +00002847 DiagnoseForRangeVariableCopies(*this, ForStmt);
2848
Richard Smith02e85f32011-04-14 22:09:26 +00002849 return S;
2850}
2851
Chris Lattnercab02a62011-02-17 20:34:02 +00002852StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2853 SourceLocation LabelLoc,
2854 LabelDecl *TheDecl) {
Reid Kleckner87a31802018-03-12 21:43:02 +00002855 setFunctionHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002856 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002857 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002858}
Chris Lattner1c310502007-05-31 06:00:00 +00002859
John McCalldadc5752010-08-24 06:29:42 +00002860StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002861Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002862 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002863 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002864 if (!E->isTypeDependent()) {
2865 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002866 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002867 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002868 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002869 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2870 if (ExprRes.isInvalid())
2871 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002872 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002873 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002874 return StmtError();
2875 }
John McCalla95172b2010-08-01 00:26:45 +00002876
Richard Smith945f8d32013-01-14 22:39:08 +00002877 ExprResult ExprRes = ActOnFinishFullExpr(E);
2878 if (ExprRes.isInvalid())
2879 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002880 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002881
Reid Kleckner87a31802018-03-12 21:43:02 +00002882 setFunctionHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002883
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002884 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002885}
2886
Nico Weberd64657f2015-03-09 02:47:59 +00002887static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2888 const Scope &DestScope) {
2889 if (!S.CurrentSEHFinally.empty() &&
2890 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2891 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2892 }
2893}
2894
John McCalldadc5752010-08-24 06:29:42 +00002895StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002896Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002897 Scope *S = CurScope->getContinueParent();
2898 if (!S) {
2899 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002900 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002901 }
Nico Weberd64657f2015-03-09 02:47:59 +00002902 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002903
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002904 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002905}
2906
John McCalldadc5752010-08-24 06:29:42 +00002907StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002908Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002909 Scope *S = CurScope->getBreakParent();
2910 if (!S) {
2911 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002912 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002913 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002914 if (S->isOpenMPLoopScope())
2915 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2916 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002917 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002918
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002919 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002920}
2921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002922/// Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002923/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002924///
Douglas Gregor5d369002011-01-21 18:05:27 +00002925/// \param ReturnType If we're determining the copy elision candidate for
2926/// a return statement, this is the return type of the function. If we're
2927/// determining the copy elision candidate for a throw expression, this will
2928/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002929///
Douglas Gregor5d369002011-01-21 18:05:27 +00002930/// \param E The expression being returned from the function or block, or
2931/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002932///
Richard Trieu09c163b2018-03-15 03:00:55 +00002933/// \param CESK Whether we allow function parameters or
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002934/// id-expressions that could be moved out of the function to be considered NRVO
2935/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2936/// determine whether we should try to move as part of a return or throw (which
2937/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002938///
2939/// \returns The NRVO candidate variable, if the return statement may use the
2940/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002941VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
Richard Trieu09c163b2018-03-15 03:00:55 +00002942 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002943 // - in a return statement in a function [where] ...
2944 // ... the expression is the name of a non-volatile automatic object ...
2945 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002946 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002947 return nullptr;
2948 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2949 if (!VD)
2950 return nullptr;
2951
Richard Trieu09c163b2018-03-15 03:00:55 +00002952 if (isCopyElisionCandidate(ReturnType, VD, CESK))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002953 return VD;
2954 return nullptr;
2955}
2956
2957bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Richard Trieu09c163b2018-03-15 03:00:55 +00002958 CopyElisionSemanticsKind CESK) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002959 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002960 // - in a return statement in a function with ...
2961 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002962 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002963 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002964 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002965 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002966 // When considering moving this expression out, allow dissimilar types.
Richard Trieu09c163b2018-03-15 03:00:55 +00002967 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002968 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2969 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971
John McCall03318c12011-11-11 03:57:31 +00002972 // ...object (other than a function or catch-clause parameter)...
2973 if (VD->getKind() != Decl::Var &&
Richard Trieu09c163b2018-03-15 03:00:55 +00002974 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002975 return false;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00002976 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2977 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978
John McCall03318c12011-11-11 03:57:31 +00002979 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002980 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002981
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002982 // Return false if VD is a __block variable. We don't want to implicitly move
2983 // out of a __block variable during a return because we cannot assume the
2984 // variable will no longer be used.
2985 if (VD->hasAttr<BlocksAttr>()) return false;
2986
Richard Trieu09c163b2018-03-15 03:00:55 +00002987 if (CESK & CES_AllowDifferentTypes)
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002988 return true;
2989
John McCall03318c12011-11-11 03:57:31 +00002990 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002991 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002992
John McCall03318c12011-11-11 03:57:31 +00002993 // Variables with higher required alignment than their type's ABI
2994 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002995 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002996 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002997 return false;
John McCall03318c12011-11-11 03:57:31 +00002998
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002999 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003000}
3001
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003002/// Try to perform the initialization of a potentially-movable value,
Richard Trieu09c163b2018-03-15 03:00:55 +00003003/// which is the operand to a return or throw statement.
3004///
3005/// This routine implements C++14 [class.copy]p32, which attempts to treat
3006/// returned lvalues as rvalues in certain cases (to prefer move construction),
3007/// then falls back to treating them as lvalues if that failed.
3008///
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003009/// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
3010/// resolutions that find non-constructors, such as derived-to-base conversions
3011/// or `operator T()&&` member functions. If false, do consider such
3012/// conversion sequences.
3013///
Richard Trieu09c163b2018-03-15 03:00:55 +00003014/// \param Res We will fill this in if move-initialization was possible.
3015/// If move-initialization is not possible, such that we must fall back to
3016/// treating the operand as an lvalue, we will leave Res in its original
3017/// invalid state.
3018static void TryMoveInitialization(Sema& S,
3019 const InitializedEntity &Entity,
3020 const VarDecl *NRVOCandidate,
3021 QualType ResultType,
3022 Expr *&Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003023 bool ConvertingConstructorsOnly,
Richard Trieu09c163b2018-03-15 03:00:55 +00003024 ExprResult &Res) {
3025 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3026 CK_NoOp, Value, VK_XValue);
3027
3028 Expr *InitExpr = &AsRvalue;
3029
3030 InitializationKind Kind = InitializationKind::CreateCopy(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003031 Value->getBeginLoc(), Value->getBeginLoc());
Richard Trieu09c163b2018-03-15 03:00:55 +00003032
3033 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3034
3035 if (!Seq)
3036 return;
3037
3038 for (const InitializationSequence::Step &Step : Seq.steps()) {
3039 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3040 Step.Kind != InitializationSequence::SK_UserConversion)
3041 continue;
3042
3043 FunctionDecl *FD = Step.Function.Function;
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003044 if (ConvertingConstructorsOnly) {
3045 if (isa<CXXConstructorDecl>(FD)) {
3046 // C++14 [class.copy]p32:
3047 // [...] If the first overload resolution fails or was not performed,
3048 // or if the type of the first parameter of the selected constructor
3049 // is not an rvalue reference to the object's type (possibly
3050 // cv-qualified), overload resolution is performed again, considering
3051 // the object as an lvalue.
3052 const RValueReferenceType *RRefType =
3053 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3054 if (!RRefType)
3055 break;
3056 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3057 NRVOCandidate->getType()))
3058 break;
3059 } else {
3060 continue;
3061 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003062 } else {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003063 if (isa<CXXConstructorDecl>(FD)) {
3064 // Check that overload resolution selected a constructor taking an
3065 // rvalue reference. If it selected an lvalue reference, then we
3066 // didn't need to cast this thing to an rvalue in the first place.
3067 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3068 break;
3069 } else if (isa<CXXMethodDecl>(FD)) {
3070 // Check that overload resolution selected a conversion operator
3071 // taking an rvalue reference.
3072 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3073 break;
3074 } else {
3075 continue;
3076 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003077 }
3078
3079 // Promote "AsRvalue" to the heap, since we now need this
3080 // expression node to persist.
3081 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3082 Value, nullptr, VK_XValue);
3083
3084 // Complete type-checking the initialization of the return type
3085 // using the constructor we found.
3086 Res = Seq.Perform(S, Entity, Kind, Value);
3087 }
3088}
3089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003090/// Perform the initialization of a potentially-movable value, which
Douglas Gregor626fbed2011-01-21 21:08:57 +00003091/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00003092///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003093/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00003094/// returned lvalues as rvalues in certain cases (to prefer move construction),
3095/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00003097Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3098 const VarDecl *NRVOCandidate,
3099 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00003100 Expr *Value,
3101 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003102 // C++14 [class.copy]p32:
3103 // When the criteria for elision of a copy/move operation are met, but not for
3104 // an exception-declaration, and the object to be copied is designated by an
3105 // lvalue, or when the expression in a return statement is a (possibly
3106 // parenthesized) id-expression that names an object with automatic storage
3107 // duration declared in the body or parameter-declaration-clause of the
3108 // innermost enclosing function or lambda-expression, overload resolution to
3109 // select the constructor for the copy is first performed as if the object
3110 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00003111 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003112
Richard Trieu09c163b2018-03-15 03:00:55 +00003113 if (AllowNRVO) {
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003114 bool AffectedByCWG1579 = false;
3115
Richard Trieu09c163b2018-03-15 03:00:55 +00003116 if (!NRVOCandidate) {
3117 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003118 if (NRVOCandidate &&
3119 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3120 Value->getExprLoc())) {
3121 const VarDecl *NRVOCandidateInCXX11 =
3122 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3123 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3124 }
Richard Trieu09c163b2018-03-15 03:00:55 +00003125 }
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00003126
Richard Trieu09c163b2018-03-15 03:00:55 +00003127 if (NRVOCandidate) {
3128 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
Malcolm Parsons321f24e2018-04-12 14:48:48 +00003129 true, Res);
3130 }
3131
3132 if (!Res.isInvalid() && AffectedByCWG1579) {
3133 QualType QT = NRVOCandidate->getType();
3134 if (QT.getNonReferenceType()
3135 .getUnqualifiedType()
3136 .isTriviallyCopyableType(Context)) {
3137 // Adding 'std::move' around a trivially copyable variable is probably
3138 // pointless. Don't suggest it.
3139 } else {
3140 // Common cases for this are returning unique_ptr<Derived> from a
3141 // function of return type unique_ptr<Base>, or returning T from a
3142 // function of return type Expected<T>. This is totally fine in a
3143 // post-CWG1579 world, but was not fine before.
3144 assert(!ResultType.isNull());
3145 SmallString<32> Str;
3146 Str += "std::move(";
3147 Str += NRVOCandidate->getDeclName().getAsString();
3148 Str += ")";
3149 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3150 << Value->getSourceRange()
3151 << NRVOCandidate->getDeclName() << ResultType << QT;
3152 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3153 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3154 }
3155 } else if (Res.isInvalid() &&
3156 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3157 Value->getExprLoc())) {
3158 const VarDecl *FakeNRVOCandidate =
3159 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3160 if (FakeNRVOCandidate) {
3161 QualType QT = FakeNRVOCandidate->getType();
3162 if (QT->isLValueReferenceType()) {
3163 // Adding 'std::move' around an lvalue reference variable's name is
3164 // dangerous. Don't suggest it.
3165 } else if (QT.getNonReferenceType()
3166 .getUnqualifiedType()
3167 .isTriviallyCopyableType(Context)) {
3168 // Adding 'std::move' around a trivially copyable variable is probably
3169 // pointless. Don't suggest it.
3170 } else {
3171 ExprResult FakeRes = ExprError();
3172 Expr *FakeValue = Value;
3173 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3174 FakeValue, false, FakeRes);
3175 if (!FakeRes.isInvalid()) {
3176 bool IsThrow =
3177 (Entity.getKind() == InitializedEntity::EK_Exception);
3178 SmallString<32> Str;
3179 Str += "std::move(";
3180 Str += FakeNRVOCandidate->getDeclName().getAsString();
3181 Str += ")";
3182 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3183 << Value->getSourceRange()
3184 << FakeNRVOCandidate->getDeclName() << IsThrow;
3185 Diag(Value->getExprLoc(), diag::note_add_std_move)
3186 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3187 }
3188 }
3189 }
Douglas Gregorf282a762011-01-21 19:38:21 +00003190 }
3191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
Douglas Gregorf282a762011-01-21 19:38:21 +00003193 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00003195 // (again) now with the return value expression as written.
3196 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00003197 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198
Douglas Gregorf282a762011-01-21 19:38:21 +00003199 return Res;
3200}
3201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003202/// Determine whether the declared return type of the specified function
Richard Smith4db51c22013-09-25 05:02:54 +00003203/// contains 'auto'.
3204static bool hasDeducedReturnType(FunctionDecl *FD) {
3205 const FunctionProtoType *FPT =
3206 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003207 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003208}
3209
Eli Friedman34b49062012-01-26 03:00:14 +00003210/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3211/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003212///
John McCalldadc5752010-08-24 06:29:42 +00003213StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003214Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3215 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003216 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003217 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003218 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003219 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003220 bool HasDeducedReturnType =
3221 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003222
Faisal Valid143a0c2017-04-01 21:30:49 +00003223 if (ExprEvalContexts.back().Context ==
3224 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003225 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3226 if (RetValExp) {
3227 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3228 if (ER.isInvalid())
3229 return StmtError();
3230 RetValExp = ER.get();
3231 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003232 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3233 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003234 }
3235
3236 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003237 // In C++1y, the return type may involve 'auto'.
3238 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3239 FunctionDecl *FD = CurLambda->CallOperator;
3240 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003241 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003242
3243 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3244 assert(AT && "lost auto type from lambda return type");
3245 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3246 FD->setInvalidDecl();
3247 return StmtError();
3248 }
Alp Toker314cc812014-01-25 16:55:45 +00003249 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003250 } else if (CurCap->HasImplicitReturnType) {
3251 // For blocks/lambdas with implicit return types, we check each return
3252 // statement individually, and deduce the common return type when the block
3253 // or lambda is completed.
3254 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003255 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003256 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3257 if (Result.isInvalid())
3258 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003259 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003260
Richard Smith5a0e50c2014-12-19 22:10:51 +00003261 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3262 // when deducing a return type for a lambda-expression (or by extension
3263 // for a block). These rules differ from the stated C++11 rules only in
3264 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003265 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003266 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003267 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003268 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003269 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003270 if (RetValExp) {
3271 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3272 // initializer list, because it is not an expression (even
3273 // though we represent it as one). We still deduce 'void'.
3274 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3275 << RetValExp->getSourceRange();
3276 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003277
Jordan Rosed39e5f12012-07-02 21:19:23 +00003278 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003279 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003280
3281 // Although we'll properly infer the type of the block once it's completed,
3282 // make sure we provide a return type now for better error recovery.
3283 if (CurCap->ReturnType.isNull())
3284 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003285 }
Eli Friedman34b49062012-01-26 03:00:14 +00003286 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003287
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003288 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003289 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3290 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3291 return StmtError();
3292 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003293 } else if (CapturedRegionScopeInfo *CurRegion =
3294 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3295 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3296 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003297 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003298 assert(CurLambda && "unknown kind of captured scope");
3299 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3300 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003301 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3302 return StmtError();
3303 }
3304 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003305
Steve Naroffc540d662008-09-03 18:15:37 +00003306 // Otherwise, verify that this result type matches the previous one. We are
3307 // pickier with blocks than for normal functions because we don't have GCC
3308 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003309 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003310 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003311 // Delay processing for now. TODO: there are lots of dependent
3312 // types we can conclusively prove aren't void.
3313 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003314 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003315 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003316 (RetValExp->isTypeDependent() ||
3317 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003318 if (!getLangOpts().CPlusPlus &&
3319 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003320 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003321 else {
3322 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003324 }
Steve Naroffc540d662008-09-03 18:15:37 +00003325 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003326 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003327 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3328 } else if (!RetValExp->isTypeDependent()) {
3329 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003330
John McCall5500ef22011-08-17 22:09:46 +00003331 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3332 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3333 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003334
John McCall5500ef22011-08-17 22:09:46 +00003335 // In C++ the return statement is handled via a copy initialization.
3336 // the C version of which boils down to CheckSingleAssignmentConstraints.
Richard Trieu09c163b2018-03-15 03:00:55 +00003337 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
John McCall5500ef22011-08-17 22:09:46 +00003338 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3339 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003340 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003341 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3342 FnRetType, RetValExp);
3343 if (Res.isInvalid()) {
3344 // FIXME: Cleanup temporaries here, anyway?
3345 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003346 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003347 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003348 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003349 } else {
Richard Trieu09c163b2018-03-15 03:00:55 +00003350 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Steve Naroffc540d662008-09-03 18:15:37 +00003351 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003352
John McCall75f92b52011-08-17 21:34:14 +00003353 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003354 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3355 if (ER.isInvalid())
3356 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003357 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003358 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003359 auto *Result =
3360 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003361
Jordan Rosed39e5f12012-07-02 21:19:23 +00003362 // If we need to check for the named return value optimization,
3363 // or if we need to infer the return type,
3364 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003365 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003366 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
Richard Smith9f690bd2015-10-27 06:02:45 +00003368 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3369 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3370
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003371 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003372}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003373
Nico Weber72889432014-09-06 01:25:55 +00003374namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003375/// Marks all typedefs in all local classes in a type referenced.
Nico Weber72889432014-09-06 01:25:55 +00003376///
3377/// In a function like
3378/// auto f() {
3379/// struct S { typedef int a; };
3380/// return S();
3381/// }
3382///
3383/// the local type escapes and could be referenced in some TUs but not in
3384/// others. Pretend that all local typedefs are always referenced, to not warn
3385/// on this. This isn't necessary if f has internal linkage, or the typedef
3386/// is private.
3387class LocalTypedefNameReferencer
3388 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3389public:
3390 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3391 bool VisitRecordType(const RecordType *RT);
3392private:
3393 Sema &S;
3394};
3395bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3396 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3397 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3398 R->isDependentType())
3399 return true;
3400 for (auto *TmpD : R->decls())
3401 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3402 if (T->getAccess() != AS_private || R->hasFriends())
3403 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3404 return true;
3405}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003406}
Nico Weber72889432014-09-06 01:25:55 +00003407
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003408TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003409 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003410 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3411 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003412 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003413}
3414
Richard Smith2a7d4812013-05-04 07:00:32 +00003415/// Deduce the return type for a function from a returned expression, per
3416/// C++1y [dcl.spec.auto]p6.
3417bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3418 SourceLocation ReturnLoc,
3419 Expr *&RetExpr,
3420 AutoType *AT) {
Richard Smith50e291e2018-01-02 23:52:42 +00003421 // If this is the conversion function for a lambda, we choose to deduce it
3422 // type from the corresponding call operator, not from the synthesized return
3423 // statement within it. See Sema::DeduceReturnType.
3424 if (isLambdaConversionOperator(FD))
3425 return false;
3426
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003427 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003428 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003429
Richard Smithc58f38f2013-08-14 20:16:31 +00003430 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3431 // If the deduction is for a return statement and the initializer is
3432 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003433 Diag(RetExpr->getExprLoc(),
3434 getCurLambda() ? diag::err_lambda_return_init_list
3435 : diag::err_auto_fn_return_init_list)
3436 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003437 return true;
3438 }
3439
3440 if (FD->isDependentContext()) {
3441 // C++1y [dcl.spec.auto]p12:
3442 // Return type deduction [...] occurs when the definition is
3443 // instantiated even if the function body contains a return
3444 // statement with a non-type-dependent operand.
3445 assert(AT->isDeduced() && "should have deduced to dependent type");
3446 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003447 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003448
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003449 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003450 // Otherwise, [...] deduce a value for U using the rules of template
3451 // argument deduction.
3452 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3453
3454 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3455 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3456 << OrigResultType.getType() << RetExpr->getType();
3457
3458 if (DAR != DAR_Succeeded)
3459 return true;
Nico Weber72889432014-09-06 01:25:55 +00003460
3461 // If a local type is part of the returned type, mark its fields as
3462 // referenced.
3463 LocalTypedefNameReferencer Referencer(*this);
3464 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003465 } else {
3466 // In the case of a return with no operand, the initializer is considered
3467 // to be void().
3468 //
3469 // Deduction here can only succeed if the return type is exactly 'cv auto'
3470 // or 'decltype(auto)', so just check for that case directly.
3471 if (!OrigResultType.getType()->getAs<AutoType>()) {
3472 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3473 << OrigResultType.getType();
3474 return true;
3475 }
3476 // We always deduce U = void in this case.
3477 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3478 if (Deduced.isNull())
3479 return true;
3480 }
3481
3482 // If a function with a declared return type that contains a placeholder type
3483 // has multiple return statements, the return type is deduced for each return
3484 // statement. [...] if the type deduced is not the same in each deduction,
3485 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003486 QualType DeducedT = AT->getDeducedType();
3487 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003488 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003489 // It is possible that NewAT->getDeducedType() is null. When that happens,
3490 // we should not crash, instead we ignore this deduction.
3491 if (NewAT->getDeducedType().isNull())
3492 return false;
3493
Douglas Gregora602a152015-10-01 20:20:47 +00003494 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003495 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003496 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3497 NewAT->getDeducedType());
3498 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003499 const LambdaScopeInfo *LambdaSI = getCurLambda();
3500 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3501 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003502 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003503 << true /*IsLambda*/;
3504 } else {
3505 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3506 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003507 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003508 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003509 return true;
3510 }
3511 } else if (!FD->isInvalidDecl()) {
3512 // Update all declarations of the function to have the deduced return type.
3513 Context.adjustDeducedFunctionResultType(FD, Deduced);
3514 }
3515
3516 return false;
3517}
3518
John McCalldadc5752010-08-24 06:29:42 +00003519StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003520Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3521 Scope *CurScope) {
3522 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003523 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3524 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003525 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003526
Taiju Tsuiki3be68e12018-06-19 05:35:30 +00003527 if (VarDecl *VD =
3528 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3529 CurScope->addNRVOCandidate(VD);
3530 } else {
3531 CurScope->setNoNRVO();
3532 }
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003533
Nico Weberd64657f2015-03-09 02:47:59 +00003534 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3535
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003536 return R;
3537}
3538
3539StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003540 // Check for unexpanded parameter packs.
3541 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3542 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003543
Eli Friedman34b49062012-01-26 03:00:14 +00003544 if (isa<CapturingScopeInfo>(getCurFunction()))
3545 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003546
Chris Lattner79413952008-12-04 23:50:19 +00003547 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003548 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003549 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003550 bool isObjCMethod = false;
3551
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003552 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003553 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003554 if (FD->hasAttrs())
3555 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003556 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003557 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003558 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003559 if (FD->isMain() && RetValExp)
3560 if (isa<CXXBoolLiteralExpr>(RetValExp))
3561 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3562 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003563 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003564 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003565 isObjCMethod = true;
3566 if (MD->hasAttrs())
3567 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003568 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3569 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003570 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003571 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003572 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3573 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003574 }
3575 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003576 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003577
Richard Smithb130fe72016-06-23 19:16:49 +00003578 // C++1z: discarded return statements are not considered when deducing a
3579 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003580 if (ExprEvalContexts.back().Context ==
3581 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003582 FnRetType->getContainedAutoType()) {
3583 if (RetValExp) {
3584 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3585 if (ER.isInvalid())
3586 return StmtError();
3587 RetValExp = ER.get();
3588 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003589 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3590 /* NRVOCandidate=*/nullptr);
Richard Smithb130fe72016-06-23 19:16:49 +00003591 }
3592
Richard Smith2a7d4812013-05-04 07:00:32 +00003593 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3594 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003595 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003596 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3597 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003598 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003599 FD->setInvalidDecl();
3600 return StmtError();
3601 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003602 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003603 }
3604 }
3605 }
3606
Richard Smithc58f38f2013-08-14 20:16:31 +00003607 bool HasDependentReturnType = FnRetType->isDependentType();
3608
Craig Topperc3ec1492014-05-26 06:22:03 +00003609 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003610 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003611 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003612 if (isa<InitListExpr>(RetValExp)) {
3613 // We simply never allow init lists as the return value of void
3614 // functions. This is compatible because this was never allowed before,
3615 // so there's no legacy code to deal with.
3616 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3617 int FunctionKind = 0;
3618 if (isa<ObjCMethodDecl>(CurDecl))
3619 FunctionKind = 1;
3620 else if (isa<CXXConstructorDecl>(CurDecl))
3621 FunctionKind = 2;
3622 else if (isa<CXXDestructorDecl>(CurDecl))
3623 FunctionKind = 3;
3624
3625 Diag(ReturnLoc, diag::err_return_init_list)
3626 << CurDecl->getDeclName() << FunctionKind
3627 << RetValExp->getSourceRange();
3628
3629 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003630 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003631 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003632 // C99 6.8.6.4p1 (ext_ since GCC warns)
3633 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003634 if (RetValExp->getType()->isVoidType()) {
3635 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3636 if (isa<CXXConstructorDecl>(CurDecl) ||
3637 isa<CXXDestructorDecl>(CurDecl))
3638 D = diag::err_ctor_dtor_returns_void;
3639 else
3640 D = diag::ext_return_has_void_expr;
3641 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003642 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003643 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003644 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003645 if (Result.isInvalid())
3646 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003647 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003648 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003649 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003650 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003651 // return of void in constructor/destructor is illegal in C++.
3652 if (D == diag::err_ctor_dtor_returns_void) {
3653 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3654 Diag(ReturnLoc, D)
3655 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3656 << RetValExp->getSourceRange();
3657 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003658 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003659 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003660 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003661 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003662
3663 int FunctionKind = 0;
3664 if (isa<ObjCMethodDecl>(CurDecl))
3665 FunctionKind = 1;
3666 else if (isa<CXXConstructorDecl>(CurDecl))
3667 FunctionKind = 2;
3668 else if (isa<CXXDestructorDecl>(CurDecl))
3669 FunctionKind = 3;
3670
Nick Lewycky1be750a2011-06-01 07:44:31 +00003671 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003672 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003673 << RetValExp->getSourceRange();
3674 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003675 }
Mike Stump11289f42009-09-09 15:08:12 +00003676
Sebastian Redleef474c2012-02-22 10:50:08 +00003677 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003678 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3679 if (ER.isInvalid())
3680 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003681 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003682 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684
Bruno Ricci023b1d12018-10-30 14:40:49 +00003685 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3686 /* NRVOCandidate=*/nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003687 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003688 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003689
David Majnemer2887ad32014-12-13 08:12:56 +00003690 unsigned DiagID;
3691 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3692 // C++11 [stmt.return]p2
3693 DiagID = diag::err_constexpr_return_missing_expr;
3694 FD->setInvalidDecl();
3695 } else if (getLangOpts().C99) {
3696 // C99 6.8.6.4p1 (ext_ since GCC warns)
3697 DiagID = diag::ext_return_missing_expr;
3698 } else {
3699 // C90 6.6.6.4p4
3700 DiagID = diag::warn_return_missing_expr;
3701 }
3702
3703 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003704 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003705 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003706 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003707
Bruno Ricci023b1d12018-10-30 14:40:49 +00003708 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3709 /* NRVOCandidate=*/nullptr);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003710 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003711 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003712 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003713
3714 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3715
3716 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3717 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3718 // function return.
3719
3720 // In C++ the return statement is handled via a copy initialization,
3721 // the C version of which boils down to CheckSingleAssignmentConstraints.
3722 if (RetValExp)
Richard Trieu09c163b2018-03-15 03:00:55 +00003723 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
Richard Smith2a7d4812013-05-04 07:00:32 +00003724 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003725 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003727 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003728 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003730 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003731 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003732 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003733 return StmtError();
3734 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003735 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003736
3737 // If we have a related result type, we need to implicitly
3738 // convert back to the formal result type. We can't pretend to
3739 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003740 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003741 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003742 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3743 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003744 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3745 if (Res.isInvalid()) {
3746 // FIXME: Clean up temporaries here anyway?
3747 return StmtError();
3748 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003749 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003750 }
3751
Artyom Skrobov9f213442014-01-24 11:10:39 +00003752 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3753 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
John McCallacf0ee52010-10-08 02:01:28 +00003756 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003757 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3758 if (ER.isInvalid())
3759 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003760 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003761 }
Bruno Ricci023b1d12018-10-30 14:40:49 +00003762 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
3765 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003766 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003767 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003768 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003769
Richard Smith9f690bd2015-10-27 06:02:45 +00003770 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3771 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3772
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003773 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003774}
3775
John McCalldadc5752010-08-24 06:29:42 +00003776StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003777Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003778 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003779 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003780 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003781 if (Var && Var->isInvalidDecl())
3782 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003784 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003785}
3786
John McCalldadc5752010-08-24 06:29:42 +00003787StmtResult
John McCallb268a282010-08-23 23:25:46 +00003788Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003789 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003790}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003791
John McCalldadc5752010-08-24 06:29:42 +00003792StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003794 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003795 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003796 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3797
Reid Kleckner87a31802018-03-12 21:43:02 +00003798 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003799 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003800 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3801 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003802}
3803
John McCall0bd3e402012-05-08 21:41:25 +00003804StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003805 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003806 ExprResult Result = DefaultLvalueConversion(Throw);
3807 if (Result.isInvalid())
3808 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003809
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003810 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003811 if (Result.isInvalid())
3812 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003813 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003814
Douglas Gregor2900c162010-04-22 21:44:01 +00003815 QualType ThrowType = Throw->getType();
3816 // Make sure the expression type is an ObjC pointer or "void *".
3817 if (!ThrowType->isDependentType() &&
3818 !ThrowType->isObjCObjectPointerType()) {
3819 const PointerType *PT = ThrowType->getAs<PointerType>();
3820 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003821 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003822 << Throw->getType() << Throw->getSourceRange());
3823 }
3824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003826 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003827}
3828
John McCalldadc5752010-08-24 06:29:42 +00003829StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003831 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003832 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003833 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3834
John McCallb268a282010-08-23 23:25:46 +00003835 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003836 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003837 // in the context of an @catch clause).
3838 Scope *AtCatchParent = CurScope;
3839 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3840 AtCatchParent = AtCatchParent->getParent();
3841 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003842 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843 }
John McCallb268a282010-08-23 23:25:46 +00003844 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003845}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003846
John McCalld9bb7432011-07-27 21:50:02 +00003847ExprResult
3848Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3849 ExprResult result = DefaultLvalueConversion(operand);
3850 if (result.isInvalid())
3851 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003852 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003853
3854 // Make sure the expression type is an ObjC pointer or "void *".
3855 QualType type = operand->getType();
3856 if (!type->isDependentType() &&
3857 !type->isObjCObjectPointerType()) {
3858 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003859 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3860 if (getLangOpts().CPlusPlus) {
3861 if (RequireCompleteType(atLoc, type,
3862 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003863 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003864 << type << operand->getSourceRange();
3865
3866 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003867 if (result.isInvalid())
3868 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003869 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003870 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003871 << type << operand->getSourceRange();
3872
3873 operand = result.get();
3874 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003875 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003876 << type << operand->getSourceRange();
3877 }
3878 }
John McCalld9bb7432011-07-27 21:50:02 +00003879 }
3880
3881 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003882 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003883}
3884
John McCalldadc5752010-08-24 06:29:42 +00003885StmtResult
John McCallb268a282010-08-23 23:25:46 +00003886Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3887 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003888 // We can't jump into or indirect-jump out of a @synchronized block.
Reid Kleckner87a31802018-03-12 21:43:02 +00003889 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003890 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003891}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003892
3893/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3894/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003895StmtResult
John McCall48871652010-08-21 09:40:31 +00003896Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003897 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003898 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003899 return new (Context)
3900 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003901}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003902
John McCall31168b02011-06-15 23:02:42 +00003903StmtResult
3904Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
Reid Kleckner87a31802018-03-12 21:43:02 +00003905 setFunctionHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003906 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003907}
3908
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003909namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003910class CatchHandlerType {
3911 QualType QT;
3912 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003913
Aaron Ballman8aee642902015-04-08 00:05:29 +00003914 // This is a special constructor to be used only with DenseMapInfo's
3915 // getEmptyKey() and getTombstoneKey() functions.
3916 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3917 enum Unique { ForDenseMap };
3918 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3919
Sebastian Redl63c4da02009-07-29 17:15:45 +00003920public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003921 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003922 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003923 /// level pointer and cv-qualifiers.
3924 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3925 if (QT->isPointerType())
3926 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003927
Aaron Ballman8aee642902015-04-08 00:05:29 +00003928 if (IsPointer || QT->isReferenceType())
3929 QT = QT->getPointeeType();
3930 QT = QT.getUnqualifiedType();
3931 }
3932
3933 /// Used when creating a CatchHandlerType from a base class type; pretends the
3934 /// type passed in had the pointer qualifier, does not need to get an
3935 /// unqualified type.
3936 CatchHandlerType(QualType QT, bool IsPointer)
3937 : QT(QT), IsPointer(IsPointer) {}
3938
3939 QualType underlying() const { return QT; }
3940 bool isPointer() const { return IsPointer; }
3941
3942 friend bool operator==(const CatchHandlerType &LHS,
3943 const CatchHandlerType &RHS) {
3944 // If the pointer qualification does not match, we can return early.
3945 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003946 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003947 // Otherwise, check the underlying type without cv-qualifiers.
3948 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003949 }
3950};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003951} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003952
Aaron Ballman8aee642902015-04-08 00:05:29 +00003953namespace llvm {
3954template <> struct DenseMapInfo<CatchHandlerType> {
3955 static CatchHandlerType getEmptyKey() {
3956 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3957 CatchHandlerType::ForDenseMap);
3958 }
3959
3960 static CatchHandlerType getTombstoneKey() {
3961 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3962 CatchHandlerType::ForDenseMap);
3963 }
3964
3965 static unsigned getHashValue(const CatchHandlerType &Base) {
3966 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3967 }
3968
3969 static bool isEqual(const CatchHandlerType &LHS,
3970 const CatchHandlerType &RHS) {
3971 return LHS == RHS;
3972 }
3973};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003974}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003975
3976namespace {
3977class CatchTypePublicBases {
3978 ASTContext &Ctx;
3979 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3980 const bool CheckAgainstPointer;
3981
3982 CXXCatchStmt *FoundHandler;
3983 CanQualType FoundHandlerType;
3984
3985public:
3986 CatchTypePublicBases(
3987 ASTContext &Ctx,
3988 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3989 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3990 FoundHandler(nullptr) {}
3991
3992 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3993 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3994
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003995 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003996 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003997 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003998 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003999 auto I = M.find(Check);
4000 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004001 FoundHandler = I->second;
4002 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00004003 return true;
4004 }
4005 }
4006 return false;
4007 }
4008};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004009}
Dan Gohman28ade552010-07-26 21:25:24 +00004010
Sebastian Redl9b244a82008-12-22 21:35:02 +00004011/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4012/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00004013StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4014 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00004015 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004016 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +00004017 !getSourceManager().isInSystemHeader(TryLoc) &&
4018 (!getLangOpts().OpenMPIsDevice ||
4019 !getLangOpts().OpenMPHostCXXExceptions ||
4020 isInOpenMPTargetExecutionDirective() ||
4021 isInOpenMPDeclareTargetContext()))
Aaron Ballman8aee642902015-04-08 00:05:29 +00004022 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00004023
Justin Lebar2a8db342016-09-28 22:45:54 +00004024 // Exceptions aren't allowed in CUDA device code.
4025 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00004026 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4027 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00004028
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004029 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4030 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4031
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004032 sema::FunctionScopeInfo *FSI = getCurFunction();
4033
Reid Klecknere7175912015-02-02 22:15:31 +00004034 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004035 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00004036 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004037 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00004038 }
4039
Robert Wilhelmcafda822013-08-22 09:20:03 +00004040 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00004041 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00004042 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00004043
Aaron Ballman8aee642902015-04-08 00:05:29 +00004044 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004045 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004046 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004047
Aaron Ballman8aee642902015-04-08 00:05:29 +00004048 // Diagnose when the handler is a catch-all handler, but it isn't the last
4049 // handler for the try block. [except.handle]p5. Also, skip exception
4050 // declarations that are invalid, since we can't usefully report on them.
4051 if (!H->getExceptionDecl()) {
4052 if (i < NumHandlers - 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004053 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00004054 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00004055 } else if (H->getExceptionDecl()->isInvalidDecl())
4056 continue;
4057
4058 // Walk the type hierarchy to diagnose when this type has already been
4059 // handled (duplication), or cannot be handled (derivation inversion). We
4060 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00004061 CatchHandlerType HandlerCHT =
4062 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00004063
4064 // We can ignore whether the type is a reference or a pointer; we need the
4065 // underlying declaration type in order to get at the underlying record
4066 // decl, if there is one.
4067 QualType Underlying = HandlerCHT.underlying();
4068 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4069 if (!RD->hasDefinition())
4070 continue;
4071 // Check that none of the public, unambiguous base classes are in the
4072 // map ([except.handle]p1). Give the base classes the same pointer
4073 // qualification as the original type we are basing off of. This allows
4074 // comparison against the handler type using the same top-level pointer
4075 // as the original type.
4076 CXXBasePaths Paths;
4077 Paths.setOrigin(RD);
4078 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00004079 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00004080 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4081 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4082 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4083 diag::warn_exception_caught_by_earlier_handler)
4084 << H->getCaughtType();
4085 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4086 diag::note_previous_exception_handler)
4087 << Problem->getCaughtType();
4088 }
4089 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00004090 }
Mike Stump11289f42009-09-09 15:08:12 +00004091
Aaron Ballman8aee642902015-04-08 00:05:29 +00004092 // Add the type the list of ones we have handled; diagnose if we've already
4093 // handled it.
4094 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4095 if (!R.second) {
4096 const CXXCatchStmt *Problem = R.first->second;
4097 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4098 diag::warn_exception_caught_by_earlier_handler)
4099 << H->getCaughtType();
4100 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4101 diag::note_previous_exception_handler)
4102 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00004103 }
4104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004106 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00004107
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004108 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00004109}
John Wiegley1c0675e2011-04-28 01:08:34 +00004110
Reid Klecknere7175912015-02-02 22:15:31 +00004111StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4112 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004113 assert(TryBlock && Handler);
4114
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004115 sema::FunctionScopeInfo *FSI = getCurFunction();
4116
Reid Klecknere7175912015-02-02 22:15:31 +00004117 // SEH __try is incompatible with C++ try. Borland appears to support this,
4118 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004119 if (!getLangOpts().Borland) {
4120 if (FSI->FirstCXXTryLoc.isValid()) {
4121 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4122 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4123 }
Reid Klecknere7175912015-02-02 22:15:31 +00004124 }
John Wiegley1c0675e2011-04-28 01:08:34 +00004125
Reid Klecknerdeeddec2015-02-05 18:56:03 +00004126 FSI->setHasSEHTry(TryLoc);
4127
4128 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4129 // track if they use SEH.
4130 DeclContext *DC = CurContext;
4131 while (DC && !DC->isFunctionOrMethod())
4132 DC = DC->getParent();
4133 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4134 if (FD)
4135 FD->setUsesSEHTry(true);
4136 else
4137 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00004138
Reid Kleckner8819a402015-07-10 00:16:25 +00004139 // Reject __try on unsupported targets.
4140 if (!Context.getTargetInfo().isSEHTrySupported())
4141 Diag(TryLoc, diag::err_seh_try_unsupported);
4142
Reid Klecknere7175912015-02-02 22:15:31 +00004143 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00004144}
4145
4146StmtResult
4147Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4148 Expr *FilterExpr,
4149 Stmt *Block) {
4150 assert(FilterExpr && Block);
4151
4152 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00004153 return StmtError(Diag(FilterExpr->getExprLoc(),
4154 diag::err_filter_expression_integral)
4155 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00004156 }
4157
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004158 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004159}
4160
Nico Weberd64657f2015-03-09 02:47:59 +00004161void Sema::ActOnStartSEHFinallyBlock() {
4162 CurrentSEHFinally.push_back(CurScope);
4163}
4164
Nico Weberce903292015-03-09 03:17:15 +00004165void Sema::ActOnAbortSEHFinallyBlock() {
4166 CurrentSEHFinally.pop_back();
4167}
4168
Nico Weberd64657f2015-03-09 02:47:59 +00004169StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00004170 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00004171 CurrentSEHFinally.pop_back();
4172 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00004173}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004174
Nico Weberc7d05962014-07-06 22:32:59 +00004175StmtResult
4176Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00004177 Scope *SEHTryParent = CurScope;
4178 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4179 SEHTryParent = SEHTryParent->getParent();
4180 if (!SEHTryParent)
4181 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00004182 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00004183
Nico Weber9b982072014-07-07 00:12:30 +00004184 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00004185}
4186
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004187StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4188 bool IsIfExists,
4189 NestedNameSpecifierLoc QualifierLoc,
4190 DeclarationNameInfo NameInfo,
4191 Stmt *Nested)
4192{
4193 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004194 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004195 cast<CompoundStmt>(Nested));
4196}
4197
4198
Chad Rosier02a84392012-08-10 17:56:09 +00004199StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004200 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00004201 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004202 UnqualifiedId &Name,
4203 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00004204 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004205 SS.getWithLocInContext(Context),
4206 GetNameFromUnqualifiedId(Name),
4207 Nested);
4208}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004209
4210RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00004211Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4212 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004213 DeclContext *DC = CurContext;
4214 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4215 DC = DC->getParent();
4216
Craig Topperc3ec1492014-05-26 06:22:03 +00004217 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004218 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004219 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4220 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004221 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004222 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004223
Alexey Bataev330de032014-10-29 12:21:55 +00004224 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004225 DC->addDecl(RD);
4226 RD->setImplicit();
4227 RD->startDefinition();
4228
Alexey Bataev9959db52014-05-06 10:08:46 +00004229 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004230 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004231 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004232 return RD;
4233}
4234
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004235static void
4236buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4237 SmallVectorImpl<Expr *> &CaptureInits,
4238 ArrayRef<sema::Capture> Candidates) {
4239 for (const sema::Capture &Cap : Candidates) {
4240 if (Cap.isThisCapture()) {
4241 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004242 CapturedStmt::VCK_This));
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004243 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004244 continue;
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004245 } else if (Cap.isVLATypeCapture()) {
Alexey Bataev330de032014-10-29 12:21:55 +00004246 Captures.push_back(
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004247 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
Alexey Bataev330de032014-10-29 12:21:55 +00004248 CaptureInits.push_back(nullptr);
4249 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004250 }
4251
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004252 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4253 Cap.isReferenceCapture()
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004254 ? CapturedStmt::VCK_ByRef
4255 : CapturedStmt::VCK_ByCopy,
Reid Kleckner04f9bca2018-03-07 22:48:35 +00004256 Cap.getVariable()));
4257 CaptureInits.push_back(Cap.getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004258 }
4259}
4260
4261void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004262 CapturedRegionKind Kind,
4263 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004264 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004265 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004266
Alexey Bataev9959db52014-05-06 10:08:46 +00004267 // Build the context parameter
4268 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4269 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4270 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004271 auto *Param =
4272 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4273 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004274 DC->addDecl(Param);
4275
4276 CD->setContextParam(0, Param);
4277
4278 // Enter the capturing scope for this captured region.
4279 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4280
4281 if (CurScope)
4282 PushDeclContext(CurScope, CD);
4283 else
4284 CurContext = CD;
4285
Faisal Valid143a0c2017-04-01 21:30:49 +00004286 PushExpressionEvaluationContext(
4287 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004288}
4289
4290void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4291 CapturedRegionKind Kind,
4292 ArrayRef<CapturedParamNameType> Params) {
4293 CapturedDecl *CD = nullptr;
4294 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4295
4296 // Build the context parameter
4297 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4298 bool ContextIsFound = false;
4299 unsigned ParamNum = 0;
4300 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4301 E = Params.end();
4302 I != E; ++I, ++ParamNum) {
4303 if (I->second.isNull()) {
4304 assert(!ContextIsFound &&
4305 "null type has been found already for '__context' parameter");
4306 IdentifierInfo *ParamName = &Context.Idents.get("__context");
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004307 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4308 .withConst()
4309 .withRestrict();
Alexey Bataev56223232017-06-09 13:40:18 +00004310 auto *Param =
4311 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4312 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004313 DC->addDecl(Param);
4314 CD->setContextParam(ParamNum, Param);
4315 ContextIsFound = true;
4316 } else {
4317 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004318 auto *Param =
4319 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4320 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004321 DC->addDecl(Param);
4322 CD->setParam(ParamNum, Param);
4323 }
4324 }
4325 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004326 if (!ContextIsFound) {
4327 // Add __context implicitly if it is not specified.
4328 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4329 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004330 auto *Param =
4331 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4332 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004333 DC->addDecl(Param);
4334 CD->setContextParam(ParamNum, Param);
4335 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004336 // Enter the capturing scope for this captured region.
4337 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4338
4339 if (CurScope)
4340 PushDeclContext(CurScope, CD);
4341 else
4342 CurContext = CD;
4343
Faisal Valid143a0c2017-04-01 21:30:49 +00004344 PushExpressionEvaluationContext(
4345 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004346}
4347
Wei Pan17fbf6e2013-05-04 03:59:06 +00004348void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004349 DiscardCleanupsInEvaluationContext();
4350 PopExpressionEvaluationContext();
4351
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004352 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4353 RecordDecl *Record = RSI->TheRecordDecl;
4354 Record->setInvalidDecl();
4355
Aaron Ballman62e47c42014-03-10 13:43:55 +00004356 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004357 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00004358 SourceLocation(), SourceLocation(), ParsedAttributesView());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004359
Wei Pan17fbf6e2013-05-04 03:59:06 +00004360 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004361 PopFunctionScopeInfo();
4362}
4363
4364StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4365 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4366
4367 SmallVector<CapturedStmt::Capture, 4> Captures;
4368 SmallVector<Expr *, 4> CaptureInits;
4369 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4370
4371 CapturedDecl *CD = RSI->TheCapturedDecl;
4372 RecordDecl *RD = RSI->TheRecordDecl;
4373
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004374 CapturedStmt *Res = CapturedStmt::Create(
4375 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4376 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004377
4378 CD->setBody(Res->getCapturedStmt());
4379 RD->completeDefinition();
4380
Wei Pan17fbf6e2013-05-04 03:59:06 +00004381 DiscardCleanupsInEvaluationContext();
4382 PopExpressionEvaluationContext();
4383
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004384 PopDeclContext();
4385 PopFunctionScopeInfo();
4386
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004387 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004388}