blob: 07b70305c196cefb5bc2db00c1477eb654b0fa57 [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Richard Smith945f8d32013-01-14 22:39:08 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45 if (FE.isInvalid())
46 return StmtError();
47
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
50 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000141 switch (Op->getOperator()) {
142 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000143 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000144 case OO_EqualEqual:
145 case OO_ExclaimEqual:
146 IsRelational = false;
147 break;
148 case OO_Less:
149 case OO_Greater:
150 case OO_GreaterEqual:
151 case OO_LessEqual:
152 IsRelational = true;
153 break;
154 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else {
160 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162 }
163
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthe2669392011-08-17 09:34:37 +0000169 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000174 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000175 if (IsNotEqual)
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
178 else
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
181 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000182
183 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184}
185
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
189
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000190 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000191 if (!E)
192 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000193
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
197 return;
198
Nico Weber0e631632015-10-27 19:47:40 +0000199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000210 SourceLocation Loc;
211 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000213 return;
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattner6dc7e572012-08-31 22:39:21 +0000215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
218 // false positive.
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
220 return;
221
Nico Weber0e631632015-10-27 19:47:40 +0000222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228 return;
229 }
230
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
233 // cases now.
234 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000236 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000239
Chandler Carruthe2669392011-08-17 09:34:37 +0000240 if (DiagnoseUnusedComparison(*this, E))
241 return;
242
Eli Friedmanc11535c2012-05-24 00:47:05 +0000243 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000245 if (E->getType()->isVoidType())
246 return;
247
Chris Lattner1a6babf2009-10-13 04:53:48 +0000248 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
251 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000252 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 return;
258 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000259 if (ShouldSuppress)
260 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000261 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263 return;
264 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000265 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 } else if (ShouldSuppress)
271 return;
272
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
276 return;
277 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000279 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000282 return;
283 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
289 else
290 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000293 const Expr *E = FC->getSubExpr();
294 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
295 E = TE->getSubExpr();
296 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000297 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000298 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
299 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
300 if (!RD->getAttr<WarnUnusedAttr>())
301 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000302 }
John McCall2351cb92010-04-06 22:24:14 +0000303 // Diagnose "(void*) blah" as a typo for "(void) blah".
304 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
305 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
306 QualType T = TI->getType();
307
308 // We really do want to use the non-canonical type here.
309 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000310 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000311
312 Diag(Loc, diag::warn_unused_voidptr)
313 << FixItHint::CreateRemoval(TL.getStarLoc());
314 return;
315 }
316 }
317
Eli Friedmanc11535c2012-05-24 00:47:05 +0000318 if (E->isGLValue() && E->getType().isVolatileQualified()) {
319 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
320 return;
321 }
322
Craig Topperc3ec1492014-05-26 06:22:03 +0000323 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000324}
325
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000326void Sema::ActOnStartOfCompoundStmt() {
327 PushCompoundScope();
328}
329
330void Sema::ActOnFinishOfCompoundStmt() {
331 PopCompoundScope();
332}
333
334sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
335 return getCurFunction()->CompoundScopes.back();
336}
337
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000338StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
339 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
340 const unsigned NumElts = Elts.size();
341
Chris Lattnerd864daf2007-08-27 04:29:41 +0000342 // If we're in C89 mode, check that we don't have any decls after stmts. If
343 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000344 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000345 // Note that __extension__ can be around a decl.
346 unsigned i = 0;
347 // Skip over all declarations.
348 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
349 /*empty*/;
350
351 // We found the end of the list or a statement. Scan for another declstmt.
352 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
353 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattnerd864daf2007-08-27 04:29:41 +0000355 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000356 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000357 Diag(D->getLocation(), diag::ext_mixed_decls_code);
358 }
359 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000360 // Warn about unused expressions in statements.
361 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000362 // Ignore statements that are last in a statement expression.
363 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000364 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000366 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000367 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000368
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000369 // Check for suspicious empty body (null statement) in `for' and `while'
370 // statements. Don't do anything for template instantiations, this just adds
371 // noise.
372 if (NumElts != 0 && !CurrentInstantiationScope &&
373 getCurCompoundScope().HasEmptyLoopBodies) {
374 for (unsigned i = 0; i != NumElts - 1; ++i)
375 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
376 }
377
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000378 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000379}
380
John McCalldadc5752010-08-24 06:29:42 +0000381StmtResult
John McCallb268a282010-08-23 23:25:46 +0000382Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
383 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000384 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000385 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000386
John McCallaab3e412010-08-25 08:40:02 +0000387 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000388 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000389 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000390 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000391
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000392 ExprResult LHS =
393 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
394 if (!getLangOpts().CPlusPlus11)
395 return VerifyIntegerConstantExpression(E);
396 if (Expr *CondExpr =
397 getCurFunction()->SwitchStack.back()->getCond()) {
398 QualType CondType = CondExpr->getType();
399 llvm::APSInt TempVal;
400 return CheckConvertedConstantExpression(E, CondType, TempVal,
401 CCEK_CaseValue);
402 }
403 return ExprError();
404 });
405 if (LHS.isInvalid())
406 return StmtError();
407 LHSVal = LHS.get();
408
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000409 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000410 // C99 6.8.4.2p3: The expression shall be an integer constant.
411 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000412 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000413 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000414 if (!LHSVal)
415 return StmtError();
416 }
Richard Smithf8379a02012-01-18 23:55:52 +0000417
418 // GCC extension: The expression shall be an integer constant.
419
Richard Smithf4c51d92012-02-04 09:53:13 +0000420 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000421 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000422 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000423 }
424 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000425
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000426 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000427 getLangOpts().CPlusPlus11);
428 if (LHS.isInvalid())
429 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000430
Richard Smith5b555da2014-11-20 01:24:12 +0000431 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
432 getLangOpts().CPlusPlus11)
433 : ExprResult();
434 if (RHS.isInvalid())
435 return StmtError();
436
437 CaseStmt *CS = new (Context)
438 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000439 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000441}
442
Chris Lattner34a22092009-03-04 04:23:07 +0000443/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000444void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000445 DiagnoseUnusedExprResult(SubStmt);
446
Chris Lattner34a22092009-03-04 04:23:07 +0000447 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000448 CS->setSubStmt(SubStmt);
449}
450
John McCalldadc5752010-08-24 06:29:42 +0000451StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000452Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000453 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000454 DiagnoseUnusedExprResult(SubStmt);
455
John McCallaab3e412010-08-25 08:40:02 +0000456 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000457 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000458 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000459 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000460
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000461 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000462 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000463 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000464}
465
John McCalldadc5752010-08-24 06:29:42 +0000466StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000467Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
468 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000469 // If the label was multiply defined, reject it now.
470 if (TheDecl->getStmt()) {
471 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
472 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000473 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000474 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000475
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000476 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000477 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
478 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000479 if (!TheDecl->isGnuLocal()) {
480 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000481 if (!TheDecl->isMSAsmLabel()) {
482 // Don't update the location of MS ASM labels. These will result in
483 // a diagnostic, and changing the location here will mess that up.
484 TheDecl->setLocation(IdentLoc);
485 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000486 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000487 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000488}
489
Richard Smithc202b282012-04-14 00:33:13 +0000490StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000491 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000492 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000493 // Fill in the declaration and return it.
494 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000495 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000496}
497
Richard Trieufaca2d82016-02-18 23:58:40 +0000498namespace {
499class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
500 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
501 Sema &SemaRef;
502public:
503 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
504 void VisitBinaryOperator(BinaryOperator *E) {
505 if (E->getOpcode() == BO_Comma)
506 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
507 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
508 }
509};
510}
511
John McCalldadc5752010-08-24 06:29:42 +0000512StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000513Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
514 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000515 Stmt *thenStmt, SourceLocation ElseLoc,
516 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000517 if (Cond.isInvalid())
518 Cond = ConditionResult(
519 *this, nullptr,
520 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
521 Context.BoolTy, VK_RValue),
522 IfLoc),
523 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000524
Richard Smithb130fe72016-06-23 19:16:49 +0000525 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000526 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000527 CondExpr->getExprLoc()))
528 CommaVisitor(*this).Visit(CondExpr);
529
Reid Kleckneradefb762017-11-16 21:26:18 +0000530 if (elseStmt)
531 DiagnoseEmptyStmtBody(ElseLoc, elseStmt, diag::warn_empty_else_body);
532 else
Hans Wennborg95419752017-11-20 17:38:16 +0000533 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
534 diag::warn_empty_if_body);
Richard Smithb130fe72016-06-23 19:16:49 +0000535
Richard Smitha547eb22016-07-14 00:11:03 +0000536 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
537 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000538}
539
540StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000541 Stmt *InitStmt, ConditionResult Cond,
542 Stmt *thenStmt, SourceLocation ElseLoc,
543 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000544 if (Cond.isInvalid())
545 return StmtError();
546
Erik Pilkington5cd57172016-08-16 17:44:11 +0000547 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Richard Smithb130fe72016-06-23 19:16:49 +0000548 getCurFunction()->setHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000549
550 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000551 DiagnoseUnusedExprResult(elseStmt);
552
Richard Smitha547eb22016-07-14 00:11:03 +0000553 return new (Context)
554 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
555 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000556}
Steve Naroff86272ea2007-05-29 02:14:17 +0000557
Chris Lattner67998452007-08-23 18:29:20 +0000558namespace {
559 struct CaseCompareFunctor {
560 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
561 const llvm::APSInt &RHS) {
562 return LHS.first < RHS;
563 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000564 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
565 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
566 return LHS.first < RHS.first;
567 }
Chris Lattner67998452007-08-23 18:29:20 +0000568 bool operator()(const llvm::APSInt &LHS,
569 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
570 return LHS < RHS.first;
571 }
572 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000573}
Chris Lattner67998452007-08-23 18:29:20 +0000574
Chris Lattner4b2ff022007-09-21 18:15:22 +0000575/// CmpCaseVals - Comparison predicate for sorting case values.
576///
577static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
578 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
579 if (lhs.first < rhs.first)
580 return true;
581
582 if (lhs.first == rhs.first &&
583 lhs.second->getCaseLoc().getRawEncoding()
584 < rhs.second->getCaseLoc().getRawEncoding())
585 return true;
586 return false;
587}
588
Douglas Gregorbd6839732010-02-08 22:24:16 +0000589/// CmpEnumVals - Comparison predicate for sorting enumeration values.
590///
591static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
592 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
593{
594 return lhs.first < rhs.first;
595}
596
597/// EqEnumVals - Comparison preficate for uniqing enumeration values.
598///
599static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
600 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
601{
602 return lhs.first == rhs.first;
603}
604
Chris Lattnera96d4272009-10-16 16:45:22 +0000605/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
606/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000607static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
608 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
609 E = CleanUps->getSubExpr();
610 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
611 if (ImpCast->getCastKind() != CK_IntegralCast) break;
612 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000613 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000614 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000615}
616
Richard Smith03a4aa32016-06-23 19:02:52 +0000617ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000618 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
619 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000620
Douglas Gregore2b37442012-05-04 22:38:52 +0000621 public:
622 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000623 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
624 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000625
Craig Toppere14c0f82014-03-12 04:55:44 +0000626 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
627 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000628 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
629 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000630
Craig Toppere14c0f82014-03-12 04:55:44 +0000631 SemaDiagnosticBuilder diagnoseIncomplete(
632 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000633 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
634 << T << Cond->getSourceRange();
635 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000636
Craig Toppere14c0f82014-03-12 04:55:44 +0000637 SemaDiagnosticBuilder diagnoseExplicitConv(
638 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000639 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
640 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000641
Craig Toppere14c0f82014-03-12 04:55:44 +0000642 SemaDiagnosticBuilder noteExplicitConv(
643 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000644 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
645 << ConvTy->isEnumeralType() << ConvTy;
646 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000647
Craig Toppere14c0f82014-03-12 04:55:44 +0000648 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
649 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000650 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
651 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000652
Craig Toppere14c0f82014-03-12 04:55:44 +0000653 SemaDiagnosticBuilder noteAmbiguous(
654 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000655 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
656 << ConvTy->isEnumeralType() << ConvTy;
657 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000658
Craig Toppere14c0f82014-03-12 04:55:44 +0000659 SemaDiagnosticBuilder diagnoseConversion(
660 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000661 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000662 }
663 } SwitchDiagnoser(Cond);
664
Richard Smith03a4aa32016-06-23 19:02:52 +0000665 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000666 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000667 if (CondResult.isInvalid())
668 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
John McCall5939b162011-08-06 07:30:58 +0000670 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smith03a4aa32016-06-23 19:02:52 +0000671 return UsualUnaryConversions(CondResult.get());
672}
John McCall5939b162011-08-06 07:30:58 +0000673
Richard Smithc7a05a92016-06-29 21:17:59 +0000674StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
675 Stmt *InitStmt, ConditionResult Cond) {
Richard Smith03a4aa32016-06-23 19:02:52 +0000676 if (Cond.isInvalid())
Meador Ingef0af05c2015-06-25 22:06:40 +0000677 return StmtError();
John McCalla95172b2010-08-01 00:26:45 +0000678
John McCallaab3e412010-08-25 08:40:02 +0000679 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Richard Smitha547eb22016-07-14 00:11:03 +0000681 SwitchStmt *SS = new (Context)
682 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000683 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000684 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000685}
686
Gabor Greif16e02862010-10-01 22:05:14 +0000687static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000688 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000689 Val.setIsSigned(IsSigned);
690}
691
Richard Smith077d0832014-08-04 00:40:48 +0000692/// Check the specified case value is in range for the given unpromoted switch
693/// type.
694static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
695 unsigned UnpromotedWidth, bool UnpromotedSign) {
696 // If the case value was signed and negative and the switch expression is
697 // unsigned, don't bother to warn: this is implementation-defined behavior.
698 // FIXME: Introduce a second, default-ignored warning for this case?
699 if (UnpromotedWidth < Val.getBitWidth()) {
700 llvm::APSInt ConvVal(Val);
701 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
702 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
703 // FIXME: Use different diagnostics for overflow in conversion to promoted
704 // type versus "switch expression cannot have this value". Use proper
705 // IntRange checking rather than just looking at the unpromoted type here.
706 if (ConvVal != Val)
707 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
708 << ConvVal.toString(10);
709 }
710}
711
Alexis Hunt724f14e2014-11-28 00:53:20 +0000712typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
713
Dmitri Gribenko58683752013-12-05 22:52:07 +0000714/// Returns true if we should emit a diagnostic about this case expression not
715/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000716static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000717 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000718 const Expr *CaseExpr,
719 EnumValsTy::iterator &EI,
720 EnumValsTy::iterator &EIEnd,
721 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000722 if (!ED->isClosed())
723 return false;
724
Alexis Hunt724f14e2014-11-28 00:53:20 +0000725 if (const DeclRefExpr *DRE =
726 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000727 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000728 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000729 QualType EnumType = S.Context.getTypeDeclType(ED);
730 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
731 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000732 return false;
733 }
734 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000735
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000736 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000737 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000738
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000739 while (EI != EIEnd && EI->first < Val)
740 EI++;
741
742 if (EI != EIEnd && EI->first == Val)
743 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000744
Dmitri Gribenko58683752013-12-05 22:52:07 +0000745 return true;
746}
747
Gabor Horvath64c32412017-08-09 08:57:09 +0000748static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
749 const Expr *Case) {
750 QualType CondType = GetTypeBeforeIntegralPromotion(Cond);
751 QualType CaseType = Case->getType();
752
753 const EnumType *CondEnumType = CondType->getAs<EnumType>();
754 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
755 if (!CondEnumType || !CaseEnumType)
756 return;
757
Gabor Horvathb57e2642017-08-09 12:34:58 +0000758 // Ignore anonymous enums.
Richard Trieu285c9362017-09-09 00:25:05 +0000759 if (!CondEnumType->getDecl()->getIdentifier() &&
760 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000761 return;
Richard Trieu285c9362017-09-09 00:25:05 +0000762 if (!CaseEnumType->getDecl()->getIdentifier() &&
763 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
Gabor Horvathb57e2642017-08-09 12:34:58 +0000764 return;
765
Gabor Horvath64c32412017-08-09 08:57:09 +0000766 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
767 return;
768
Gabor Horvath0284a202017-08-09 20:56:43 +0000769 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000770 << CondType << CaseType << Cond->getSourceRange()
771 << Case->getSourceRange();
772}
773
John McCalldadc5752010-08-24 06:29:42 +0000774StmtResult
John McCallb268a282010-08-23 23:25:46 +0000775Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
776 Stmt *BodyStmt) {
777 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000778 assert(SS == getCurFunction()->SwitchStack.back() &&
779 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000780
David Majnemer418ad3f2014-12-15 07:46:12 +0000781 getCurFunction()->SwitchStack.pop_back();
782
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000783 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000784 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000785
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000786 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000787 if (!CondExpr) return StmtError();
788
789 QualType CondType = CondExpr->getType();
790
Gabor Horvath64c32412017-08-09 08:57:09 +0000791 const Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000792 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000793 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000794
Chris Lattnera96d4272009-10-16 16:45:22 +0000795 // C++ 6.4.2.p2:
796 // Integral promotions are performed (on the switch condition).
797 //
798 // A case value unrepresentable by the original switch condition
799 // type (before the promotion) doesn't make sense, even when it can
800 // be represented by the promoted type. Therefore we need to find
801 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000802 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000803 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000805 // appropriate type now, just return an error.
806 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000807 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000808
Chris Lattner4ebae652010-04-16 23:34:13 +0000809 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000810 // switch(bool_expr) {...} is often a programmer error, e.g.
811 // switch(n && mask) { ... } // Doh - should be "n & mask".
812 // One can always use an if statement instead of switch(bool_expr).
813 Diag(SwitchLoc, diag::warn_bool_switch_condition)
814 << CondExpr->getSourceRange();
815 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000816 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000817
Richard Smith077d0832014-08-04 00:40:48 +0000818 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000819 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000820 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000821 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000822 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
823 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
824
825 // Get the width and signedness that the condition might actually have, for
826 // warning purposes.
827 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
828 // type.
829 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000830 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000831 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000832 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000833
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000834 // Accumulate all of the case values in a vector so that we can sort them
835 // and detect duplicates. This vector contains the APInt for the case after
836 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000837 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000838 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000840 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000841 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
842 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000843
Craig Topperc3ec1492014-05-26 06:22:03 +0000844 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattner10cb5e52007-08-23 06:23:56 +0000846 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000848 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000849 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000850
Anders Carlsson51873c22007-07-22 07:07:56 +0000851 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000852 if (TheDefaultStmt) {
853 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000854 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000855
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000856 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000857 // we'll return a valid AST. This requires recursing down the AST and
858 // finding it, not something we are set up to do right now. For now,
859 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000860 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000861 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000862 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000863
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000864 } else {
865 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattnera65e1f32008-01-16 19:17:22 +0000867 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000868
869 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
870 HasDependentValue = true;
871 break;
872 }
Mike Stump11289f42009-09-09 15:08:12 +0000873
Gabor Horvath64c32412017-08-09 08:57:09 +0000874 checkEnumTypesInSwitchStmt(*this, CondExpr, Lo);
875
Richard Smithf8379a02012-01-18 23:55:52 +0000876 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000877
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000878 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000879 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
880 // constant expression of the promoted type of the switch condition.
881 ExprResult ConvLo =
882 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
883 if (ConvLo.isInvalid()) {
884 CaseListIsErroneous = true;
885 continue;
886 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000887 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000888 } else {
889 // We already verified that the expression has a i-c-e value (C99
890 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000891 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000892
893 // If the LHS is not the same type as the condition, insert an implicit
894 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000895 Lo = DefaultLvalueConversion(Lo).get();
896 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000897 }
898
Richard Smith077d0832014-08-04 00:40:48 +0000899 // Check the unconverted value is within the range of possible values of
900 // the switch expression.
901 checkCaseValue(*this, Lo->getLocStart(), LoVal,
902 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
903
904 // Convert the value to the same width/sign as the condition.
905 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000906
Chris Lattnera65e1f32008-01-16 19:17:22 +0000907 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000908
Chris Lattner10cb5e52007-08-23 06:23:56 +0000909 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000910 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000911 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000912 CS->getRHS()->isValueDependent()) {
913 HasDependentValue = true;
914 break;
915 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000916 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000917 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000918 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000919 }
920 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000921
922 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000923 // If we don't have a default statement, check whether the
924 // condition is constant.
925 llvm::APSInt ConstantCondValue;
926 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000927 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000928 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
929 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000930 assert(!HasConstantCond ||
931 (ConstantCondValue.getBitWidth() == CondWidth &&
932 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000933 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000934 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000935
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000936 // Sort all the scalar case values so we can easily detect duplicates.
937 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
938
939 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000940 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
941 if (ShouldCheckConstantCond &&
942 CaseVals[i].first == ConstantCondValue)
943 ShouldCheckConstantCond = false;
944
945 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000946 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000947 // First, determine if either case value has a name
948 StringRef PrevString, CurrString;
949 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
950 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
951 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
952 PrevString = DeclRef->getDecl()->getName();
953 }
954 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
955 CurrString = DeclRef->getDecl()->getName();
956 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000957 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000958 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000959
960 if (PrevString == CurrString)
961 Diag(CaseVals[i].second->getLHS()->getLocStart(),
962 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000963 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000964 else
965 Diag(CaseVals[i].second->getLHS()->getLocStart(),
966 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000967 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
968 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000969 CaseValStr;
970
John McCalld3dfbd62010-05-18 03:19:21 +0000971 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000972 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000973 // FIXME: We really want to remove the bogus case stmt from the
974 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000975 CaseListIsErroneous = true;
976 }
977 }
978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000980 // Detect duplicate case ranges, which usually don't exist at all in
981 // the first place.
982 if (!CaseRanges.empty()) {
983 // Sort all the case ranges by their low value so we can easily detect
984 // overlaps between ranges.
985 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 // Scan the ranges, computing the high values and removing empty ranges.
988 std::vector<llvm::APSInt> HiVals;
989 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000990 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000991 CaseStmt *CR = CaseRanges[i].second;
992 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000993 llvm::APSInt HiVal;
994
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000995 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000996 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
997 // constant expression of the promoted type of the switch condition.
998 ExprResult ConvHi =
999 CheckConvertedConstantExpression(Hi, CondType, HiVal,
1000 CCEK_CaseValue);
1001 if (ConvHi.isInvalid()) {
1002 CaseListIsErroneous = true;
1003 continue;
1004 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001005 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +00001006 } else {
1007 HiVal = Hi->EvaluateKnownConstInt(Context);
1008
1009 // If the RHS is not the same type as the condition, insert an
1010 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001011 Hi = DefaultLvalueConversion(Hi).get();
1012 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +00001013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Richard Smith077d0832014-08-04 00:40:48 +00001015 // Check the unconverted value is within the range of possible values of
1016 // the switch expression.
1017 checkCaseValue(*this, Hi->getLocStart(), HiVal,
1018 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1019
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001020 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001021 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001023 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001025 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001026 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001027 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1028 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +00001029 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001030 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001031 --i;
1032 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001033 continue;
1034 }
John McCalld3dfbd62010-05-18 03:19:21 +00001035
1036 if (ShouldCheckConstantCond &&
1037 LoVal <= ConstantCondValue &&
1038 ConstantCondValue <= HiVal)
1039 ShouldCheckConstantCond = false;
1040
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001041 HiVals.push_back(HiVal);
1042 }
Mike Stump11289f42009-09-09 15:08:12 +00001043
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001044 // Rescan the ranges, looking for overlap with singleton values and other
1045 // ranges. Since the range list is sorted, we only need to compare case
1046 // ranges with their neighbors.
1047 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1048 llvm::APSInt &CRLo = CaseRanges[i].first;
1049 llvm::APSInt &CRHi = HiVals[i];
1050 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001051
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001052 // Check to see whether the case range overlaps with any
1053 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001054 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001055 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001057 // Find the smallest value >= the lower bound. If I is in the
1058 // case range, then we have overlap.
1059 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1060 CaseVals.end(), CRLo,
1061 CaseCompareFunctor());
1062 if (I != CaseVals.end() && I->first < CRHi) {
1063 OverlapVal = I->first; // Found overlap with scalar.
1064 OverlapStmt = I->second;
1065 }
Mike Stump11289f42009-09-09 15:08:12 +00001066
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001067 // Find the smallest value bigger than the upper bound.
1068 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1069 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1070 OverlapVal = (I-1)->first; // Found overlap with scalar.
1071 OverlapStmt = (I-1)->second;
1072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001074 // Check to see if this case stmt overlaps with the subsequent
1075 // case range.
1076 if (i && CRLo <= HiVals[i-1]) {
1077 OverlapVal = HiVals[i-1]; // Found overlap with range.
1078 OverlapStmt = CaseRanges[i-1].second;
1079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001081 if (OverlapStmt) {
1082 // If we have a duplicate, report it.
1083 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1084 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001085 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001086 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001087 // FIXME: We really want to remove the bogus case stmt from the
1088 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001089 CaseListIsErroneous = true;
1090 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001091 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001092 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001093
John McCalld3dfbd62010-05-18 03:19:21 +00001094 // Complain if we have a constant condition and we didn't find a match.
1095 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1096 // TODO: it would be nice if we printed enums as enums, chars as
1097 // chars, etc.
1098 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1099 << ConstantCondValue.toString(10)
1100 << CondExpr->getSourceRange();
1101 }
1102
1103 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001104 // values. We only issue a warning if there is not 'default:', but
1105 // we still do the analysis to preserve this information in the AST
1106 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001107 //
Chris Lattner51679082010-09-16 17:09:42 +00001108 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001109
Douglas Gregorbd6839732010-02-08 22:24:16 +00001110 // If switch has default case, then ignore it.
Alex Lorenz660195f2016-12-08 14:46:05 +00001111 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1112 ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001113 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001114 EnumValsTy EnumVals;
1115
John McCalld3dfbd62010-05-18 03:19:21 +00001116 // Gather all enum values, set their type and sort them,
1117 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001118 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001119 llvm::APSInt Val = EDI->getInitVal();
1120 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001121 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001122 }
1123 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001124 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001125 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001126
1127 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001128 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001129 CI != CaseVals.end(); CI++) {
1130 Expr *CaseExpr = CI->second->getLHS();
1131 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1132 CI->first))
1133 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1134 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001135 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001136
David Blaikiee476f972012-01-22 02:31:55 +00001137 // See which of case ranges aren't in enum
1138 EI = EnumVals.begin();
1139 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001140 RI != CaseRanges.end(); RI++) {
1141 Expr *CaseExpr = RI->second->getLHS();
1142 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1143 RI->first))
1144 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1145 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001146
Chad Rosier02a84392012-08-10 17:56:09 +00001147 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001148 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1149 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001150
1151 CaseExpr = RI->second->getRHS();
1152 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1153 Hi))
1154 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1155 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
Ted Kremenekc42f3452010-09-09 00:05:53 +00001158 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001159 auto CI = CaseVals.begin();
1160 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001161 bool hasCasesNotInSwitch = false;
1162
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001163 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001164
Alexis Hunt724f14e2014-11-28 00:53:20 +00001165 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001166 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001167 while (CI != CaseVals.end() && CI->first < EI->first)
1168 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
Douglas Gregorbd6839732010-02-08 22:24:16 +00001170 if (CI != CaseVals.end() && CI->first == EI->first)
1171 continue;
1172
Ted Kremenekc42f3452010-09-09 00:05:53 +00001173 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001174 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001175 llvm::APSInt Hi =
1176 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001177 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001178 if (EI->first <= Hi)
1179 break;
1180 }
1181
Ted Kremenekc42f3452010-09-09 00:05:53 +00001182 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001183 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001184 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001185 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001188 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001189 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001190
Chris Lattner51679082010-09-16 17:09:42 +00001191 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001192 if (!UnhandledNames.empty()) {
1193 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1194 TheDefaultStmt ? diag::warn_def_missing_case
1195 : diag::warn_missing_case)
1196 << (int)UnhandledNames.size();
1197
1198 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1199 I != E; ++I)
1200 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001201 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001202
1203 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001204 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001205 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001206 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001207
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001208 if (BodyStmt)
1209 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1210 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001211
Mike Stump87c57ac2009-05-16 07:39:55 +00001212 // FIXME: If the case list was broken is some way, we don't have a good system
1213 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001214 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001215 return StmtError();
1216
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001217 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001218}
1219
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001220void
1221Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1222 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001223 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001224 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001225
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001226 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001227 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001228 SrcType->isIntegerType()) {
1229 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1230 SrcExpr->isIntegerConstantExpr(Context)) {
1231 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001232 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001233 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1234
1235 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001236 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001237 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001238
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001239 if (!ED->isClosed())
1240 return;
1241
Alexis Hunt724f14e2014-11-28 00:53:20 +00001242 if (ED->hasAttr<FlagEnumAttr>()) {
1243 if (!IsValueInFlagEnum(ED, RhsVal, true))
1244 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001245 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001246 } else {
1247 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1248 EnumValsTy;
1249 EnumValsTy EnumVals;
1250
1251 // Gather all enum values, set their type and sort them,
1252 // allowing easier comparison with rhs constant.
1253 for (auto *EDI : ED->enumerators()) {
1254 llvm::APSInt Val = EDI->getInitVal();
1255 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1256 EnumVals.push_back(std::make_pair(Val, EDI));
1257 }
1258 if (EnumVals.empty())
1259 return;
1260 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1261 EnumValsTy::iterator EIend =
1262 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1263
1264 // See which values aren't in the enum.
1265 EnumValsTy::const_iterator EI = EnumVals.begin();
1266 while (EI != EIend && EI->first < RhsVal)
1267 EI++;
1268 if (EI == EIend || EI->first != RhsVal) {
1269 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1270 << DstType.getUnqualifiedType();
1271 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001272 }
1273 }
1274 }
1275}
1276
Richard Smith03a4aa32016-06-23 19:02:52 +00001277StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1278 Stmt *Body) {
1279 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001280 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281
Richard Smith03a4aa32016-06-23 19:02:52 +00001282 auto CondVal = Cond.get();
1283 CheckBreakContinueBinding(CondVal.second);
1284
1285 if (CondVal.second &&
1286 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1287 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001288
John McCallb268a282010-08-23 23:25:46 +00001289 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001290
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001291 if (isa<NullStmt>(Body))
1292 getCurCompoundScope().setHasEmptyLoopBodies();
1293
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001294 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001295 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001296}
1297
John McCalldadc5752010-08-24 06:29:42 +00001298StmtResult
John McCallb268a282010-08-23 23:25:46 +00001299Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001300 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001301 Expr *Cond, SourceLocation CondRParen) {
1302 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001303
Serge Pavlov09f99242014-01-23 15:05:00 +00001304 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001305 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001306 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001307 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001308 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001309
Richard Smith945f8d32013-01-14 22:39:08 +00001310 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001311 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001312 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001313 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314
John McCallb268a282010-08-23 23:25:46 +00001315 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001316
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001317 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001318}
1319
Richard Trieu451a5db2012-04-30 18:01:30 +00001320namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001321 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1322 using DeclSetVector =
1323 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1324 llvm::SmallPtrSet<VarDecl *, 8>>;
1325
Richard Trieu451a5db2012-04-30 18:01:30 +00001326 // This visitor will traverse a conditional statement and store all
1327 // the evaluated decls into a vector. Simple is set to true if none
1328 // of the excluded constructs are used.
1329 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001330 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001331 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001332 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001333 public:
1334 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001335
Richard Trieu5fb874a2017-06-02 04:24:46 +00001336 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001337 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001338 Inherited(S.Context),
1339 Decls(Decls),
1340 Ranges(Ranges),
1341 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001344
Richard Trieu9d228802013-05-31 22:46:45 +00001345 // Replaces the method in EvaluatedExprVisitor.
1346 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001347 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001348 }
1349
1350 // Any Stmt not whitelisted will cause the condition to be marked complex.
1351 void VisitStmt(Stmt *S) {
1352 Simple = false;
1353 }
1354
1355 void VisitBinaryOperator(BinaryOperator *E) {
1356 Visit(E->getLHS());
1357 Visit(E->getRHS());
1358 }
1359
1360 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001361 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001362 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001363
Richard Trieu9d228802013-05-31 22:46:45 +00001364 void VisitUnaryOperator(UnaryOperator *E) {
1365 // Skip checking conditionals with derefernces.
1366 if (E->getOpcode() == UO_Deref)
1367 Simple = false;
1368 else
1369 Visit(E->getSubExpr());
1370 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001371
Richard Trieu9d228802013-05-31 22:46:45 +00001372 void VisitConditionalOperator(ConditionalOperator *E) {
1373 Visit(E->getCond());
1374 Visit(E->getTrueExpr());
1375 Visit(E->getFalseExpr());
1376 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void VisitParenExpr(ParenExpr *E) {
1379 Visit(E->getSubExpr());
1380 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001381
Richard Trieu9d228802013-05-31 22:46:45 +00001382 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1383 Visit(E->getOpaqueValue()->getSourceExpr());
1384 Visit(E->getFalseExpr());
1385 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001386
Richard Trieu9d228802013-05-31 22:46:45 +00001387 void VisitIntegerLiteral(IntegerLiteral *E) { }
1388 void VisitFloatingLiteral(FloatingLiteral *E) { }
1389 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1390 void VisitCharacterLiteral(CharacterLiteral *E) { }
1391 void VisitGNUNullExpr(GNUNullExpr *E) { }
1392 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001393
Richard Trieu9d228802013-05-31 22:46:45 +00001394 void VisitDeclRefExpr(DeclRefExpr *E) {
1395 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1396 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001397
Richard Trieu9d228802013-05-31 22:46:45 +00001398 Ranges.push_back(E->getSourceRange());
1399
1400 Decls.insert(VD);
1401 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001402
1403 }; // end class DeclExtractor
1404
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001405 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001406 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001407 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001408 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001409 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001410
Richard Trieu9d228802013-05-31 22:46:45 +00001411 public:
1412 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001413
Richard Trieu5fb874a2017-06-02 04:24:46 +00001414 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001415 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1416 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001417
Richard Trieu9d228802013-05-31 22:46:45 +00001418 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001419 }
1420
Richard Trieu9d228802013-05-31 22:46:45 +00001421 void VisitReturnStmt(ReturnStmt *S) {
1422 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001423 }
1424
Richard Trieu9d228802013-05-31 22:46:45 +00001425 void VisitBreakStmt(BreakStmt *S) {
1426 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001427 }
1428
Richard Trieu9d228802013-05-31 22:46:45 +00001429 void VisitGotoStmt(GotoStmt *S) {
1430 FoundDecl = true;
1431 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001432
Richard Trieu9d228802013-05-31 22:46:45 +00001433 void VisitCastExpr(CastExpr *E) {
1434 if (E->getCastKind() == CK_LValueToRValue)
1435 CheckLValueToRValueCast(E->getSubExpr());
1436 else
1437 Visit(E->getSubExpr());
1438 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001439
Richard Trieu9d228802013-05-31 22:46:45 +00001440 void CheckLValueToRValueCast(Expr *E) {
1441 E = E->IgnoreParenImpCasts();
1442
1443 if (isa<DeclRefExpr>(E)) {
1444 return;
1445 }
1446
1447 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1448 Visit(CO->getCond());
1449 CheckLValueToRValueCast(CO->getTrueExpr());
1450 CheckLValueToRValueCast(CO->getFalseExpr());
1451 return;
1452 }
1453
1454 if (BinaryConditionalOperator *BCO =
1455 dyn_cast<BinaryConditionalOperator>(E)) {
1456 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1457 CheckLValueToRValueCast(BCO->getFalseExpr());
1458 return;
1459 }
1460
1461 Visit(E);
1462 }
1463
1464 void VisitDeclRefExpr(DeclRefExpr *E) {
1465 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1466 if (Decls.count(VD))
1467 FoundDecl = true;
1468 }
1469
Steven Wu92910f62016-03-10 02:02:48 +00001470 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1471 // Only need to visit the semantics for POE.
1472 // SyntaticForm doesn't really use the Decal.
1473 for (auto *S : POE->semantics()) {
1474 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1475 // Look past the OVE into the expression it binds.
1476 Visit(OVE->getSourceExpr());
1477 else
1478 Visit(S);
1479 }
1480 }
1481
Richard Trieu9d228802013-05-31 22:46:45 +00001482 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001483
1484 }; // end class DeclMatcher
1485
1486 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1487 Expr *Third, Stmt *Body) {
1488 // Condition is empty
1489 if (!Second) return;
1490
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001491 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1492 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001493 return;
1494
1495 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001496 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001497 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001498 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001499 DE.Visit(Second);
1500
1501 // Don't analyze complex conditionals.
1502 if (!DE.isSimple()) return;
1503
1504 // No decls found.
1505 if (Decls.size() == 0) return;
1506
Richard Trieu0030f1d2012-05-04 03:01:54 +00001507 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001508 for (auto *VD : Decls)
1509 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1510 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001511
1512 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1513 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1514 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1515 return;
1516
1517 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001518 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001519 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001520 } else {
1521 PDiag << (unsigned)Decls.size();
1522 for (auto *VD : Decls)
1523 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001524 }
1525
Richard Trieu5fb874a2017-06-02 04:24:46 +00001526 for (auto Range : Ranges)
1527 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001528
1529 S.Diag(Ranges.begin()->getBegin(), PDiag);
1530 }
1531
Richard Trieu4e7c9622013-08-06 21:31:54 +00001532 // If Statement is an incemement or decrement, return true and sets the
1533 // variables Increment and DRE.
1534 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1535 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001536 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1537 if (!Cleanups->cleanupsHaveSideEffects())
1538 Statement = Cleanups->getSubExpr();
1539
Richard Trieu4e7c9622013-08-06 21:31:54 +00001540 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1541 switch (UO->getOpcode()) {
1542 default: return false;
1543 case UO_PostInc:
1544 case UO_PreInc:
1545 Increment = true;
1546 break;
1547 case UO_PostDec:
1548 case UO_PreDec:
1549 Increment = false;
1550 break;
1551 }
1552 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1553 return DRE;
1554 }
1555
1556 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1557 FunctionDecl *FD = Call->getDirectCallee();
1558 if (!FD || !FD->isOverloadedOperator()) return false;
1559 switch (FD->getOverloadedOperator()) {
1560 default: return false;
1561 case OO_PlusPlus:
1562 Increment = true;
1563 break;
1564 case OO_MinusMinus:
1565 Increment = false;
1566 break;
1567 }
1568 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1569 return DRE;
1570 }
1571
1572 return false;
1573 }
1574
Serge Pavlov09f99242014-01-23 15:05:00 +00001575 // A visitor to determine if a continue or break statement is a
1576 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001577 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001578 SourceLocation BreakLoc;
1579 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001580 bool InSwitch = false;
1581
Richard Trieu4e7c9622013-08-06 21:31:54 +00001582 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001583 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001584 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001585 Visit(Body);
1586 }
1587
Eli Friedmane91b2e62017-07-04 00:52:24 +00001588 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001589
Eli Friedmane91b2e62017-07-04 00:52:24 +00001590 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001591 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001592 }
1593
Eli Friedmane91b2e62017-07-04 00:52:24 +00001594 void VisitBreakStmt(const BreakStmt* E) {
1595 if (!InSwitch)
1596 BreakLoc = E->getBreakLoc();
1597 }
1598
1599 void VisitSwitchStmt(const SwitchStmt* S) {
1600 if (const Stmt *Init = S->getInit())
1601 Visit(Init);
1602 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1603 Visit(CondVar);
1604 if (const Stmt *Cond = S->getCond())
1605 Visit(Cond);
1606
1607 // Don't return break statements from the body of a switch.
1608 InSwitch = true;
1609 if (const Stmt *Body = S->getBody())
1610 Visit(Body);
1611 InSwitch = false;
1612 }
1613
1614 void VisitForStmt(const ForStmt *S) {
1615 // Only visit the init statement of a for loop; the body
1616 // has a different break/continue scope.
1617 if (const Stmt *Init = S->getInit())
1618 Visit(Init);
1619 }
1620
1621 void VisitWhileStmt(const WhileStmt *) {
1622 // Do nothing; the children of a while loop have a different
1623 // break/continue scope.
1624 }
1625
1626 void VisitDoStmt(const DoStmt *) {
1627 // Do nothing; the children of a while loop have a different
1628 // break/continue scope.
1629 }
1630
1631 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1632 // Only visit the initialization of a for loop; the body
1633 // has a different break/continue scope.
1634 if (const Stmt *Range = S->getRangeStmt())
1635 Visit(Range);
1636 if (const Stmt *Begin = S->getBeginStmt())
1637 Visit(Begin);
1638 if (const Stmt *End = S->getEndStmt())
1639 Visit(End);
1640 }
1641
1642 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1643 // Only visit the initialization of a for loop; the body
1644 // has a different break/continue scope.
1645 if (const Stmt *Element = S->getElement())
1646 Visit(Element);
1647 if (const Stmt *Collection = S->getCollection())
1648 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001649 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001650
Serge Pavlov09f99242014-01-23 15:05:00 +00001651 bool ContinueFound() { return ContinueLoc.isValid(); }
1652 bool BreakFound() { return BreakLoc.isValid(); }
1653 SourceLocation GetContinueLoc() { return ContinueLoc; }
1654 SourceLocation GetBreakLoc() { return BreakLoc; }
1655
1656 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001657
1658 // Emit a warning when a loop increment/decrement appears twice per loop
1659 // iteration. The conditions which trigger this warning are:
1660 // 1) The last statement in the loop body and the third expression in the
1661 // for loop are both increment or both decrement of the same variable
1662 // 2) No continue statements in the loop body.
1663 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1664 // Return when there is nothing to check.
1665 if (!Body || !Third) return;
1666
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001667 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1668 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001669 return;
1670
1671 // Get the last statement from the loop body.
1672 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1673 if (!CS || CS->body_empty()) return;
1674 Stmt *LastStmt = CS->body_back();
1675 if (!LastStmt) return;
1676
1677 bool LoopIncrement, LastIncrement;
1678 DeclRefExpr *LoopDRE, *LastDRE;
1679
1680 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1681 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1682
1683 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001684 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001685 if (LoopIncrement != LastIncrement ||
1686 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1687
Serge Pavlov09f99242014-01-23 15:05:00 +00001688 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001689
1690 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1691 << LastDRE->getDecl() << LastIncrement;
1692 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1693 << LoopIncrement;
1694 }
1695
Richard Trieu451a5db2012-04-30 18:01:30 +00001696} // end namespace
1697
Serge Pavlov09f99242014-01-23 15:05:00 +00001698
1699void Sema::CheckBreakContinueBinding(Expr *E) {
1700 if (!E || getLangOpts().CPlusPlus)
1701 return;
1702 BreakContinueFinder BCFinder(*this, E);
1703 Scope *BreakParent = CurScope->getBreakParent();
1704 if (BCFinder.BreakFound() && BreakParent) {
1705 if (BreakParent->getFlags() & Scope::SwitchScope) {
1706 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1707 } else {
1708 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1709 << "break";
1710 }
1711 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1712 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1713 << "continue";
1714 }
1715}
1716
Richard Smith03a4aa32016-06-23 19:02:52 +00001717StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1718 Stmt *First, ConditionResult Second,
1719 FullExprArg third, SourceLocation RParenLoc,
1720 Stmt *Body) {
1721 if (Second.isInvalid())
1722 return StmtError();
1723
David Blaikiebbafb8a2012-03-11 07:00:24 +00001724 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001725 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001726 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1727 // declare identifiers for objects having storage class 'auto' or
1728 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001729 for (auto *DI : DS->decls()) {
1730 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001731 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001732 VD = nullptr;
1733 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001734 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1735 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001736 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001737 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001738 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001739 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001740
Richard Smith03a4aa32016-06-23 19:02:52 +00001741 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001742 CheckBreakContinueBinding(third.get());
1743
Richard Smith03a4aa32016-06-23 19:02:52 +00001744 if (!Second.get().first)
1745 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1746 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001747 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001748
Richard Smith03a4aa32016-06-23 19:02:52 +00001749 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001750 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001751 Second.get().second->getExprLoc()))
1752 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001753
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001754 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755
Anders Carlsson1682af52009-08-01 01:39:59 +00001756 DiagnoseUnusedExprResult(First);
1757 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001758 DiagnoseUnusedExprResult(Body);
1759
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001760 if (isa<NullStmt>(Body))
1761 getCurCompoundScope().setHasEmptyLoopBodies();
1762
Richard Smith03a4aa32016-06-23 19:02:52 +00001763 return new (Context)
1764 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1765 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001766}
1767
John McCall34376a62010-12-04 03:47:34 +00001768/// In an Objective C collection iteration statement:
1769/// for (x in y)
1770/// x can be an arbitrary l-value expression. Bind it up as a
1771/// full-expression.
1772StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001773 // Reduce placeholder expressions here. Note that this rejects the
1774 // use of pseudo-object l-values in this position.
1775 ExprResult result = CheckPlaceholderExpr(E);
1776 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001777 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001778
Richard Smith945f8d32013-01-14 22:39:08 +00001779 ExprResult FullExpr = ActOnFinishFullExpr(E);
1780 if (FullExpr.isInvalid())
1781 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001782 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001783}
1784
John McCall53848232011-07-27 01:07:15 +00001785ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001786Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1787 if (!collection)
1788 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001789
Kaelyn Takata15867822014-11-21 18:48:04 +00001790 ExprResult result = CorrectDelayedTyposInExpr(collection);
1791 if (!result.isUsable())
1792 return ExprError();
1793 collection = result.get();
1794
John McCall53848232011-07-27 01:07:15 +00001795 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001796 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001797
1798 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001799 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001800 if (result.isInvalid())
1801 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001802 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001803
1804 // The operand needs to have object-pointer type.
1805 // TODO: should we do a contextual conversion?
1806 const ObjCObjectPointerType *pointerType =
1807 collection->getType()->getAs<ObjCObjectPointerType>();
1808 if (!pointerType)
1809 return Diag(forLoc, diag::err_collection_expr_type)
1810 << collection->getType() << collection->getSourceRange();
1811
1812 // Check that the operand provides
1813 // - countByEnumeratingWithState:objects:count:
1814 const ObjCObjectType *objectType = pointerType->getObjectType();
1815 ObjCInterfaceDecl *iface = objectType->getInterface();
1816
1817 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001818 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001819 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001820 (getLangOpts().ObjCAutoRefCount
1821 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1822 diag::err_arc_collection_forward, collection)
1823 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001824 // Otherwise, if we have any useful type information, check that
1825 // the type declares the appropriate method.
1826 } else if (iface || !objectType->qual_empty()) {
1827 IdentifierInfo *selectorIdents[] = {
1828 &Context.Idents.get("countByEnumeratingWithState"),
1829 &Context.Idents.get("objects"),
1830 &Context.Idents.get("count")
1831 };
1832 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1833
Craig Topperc3ec1492014-05-26 06:22:03 +00001834 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001835
1836 // If there's an interface, look in both the public and private APIs.
1837 if (iface) {
1838 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001839 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001840 }
1841
1842 // Also check protocol qualifiers.
1843 if (!method)
1844 method = LookupMethodInQualifiedType(selector, pointerType,
1845 /*instance*/ true);
1846
1847 // If we didn't find it anywhere, give up.
1848 if (!method) {
1849 Diag(forLoc, diag::warn_collection_expr_type)
1850 << collection->getType() << selector << collection->getSourceRange();
1851 }
1852
1853 // TODO: check for an incompatible signature?
1854 }
1855
1856 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001857 return collection;
John McCall53848232011-07-27 01:07:15 +00001858}
1859
John McCalldadc5752010-08-24 06:29:42 +00001860StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001861Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001862 Stmt *First, Expr *collection,
1863 SourceLocation RParenLoc) {
Akira Hatanaka39013772017-04-19 17:54:08 +00001864 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001865
1866 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001867 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001868
Fariborz Jahanian93977672008-01-10 20:33:58 +00001869 if (First) {
1870 QualType FirstType;
1871 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001872 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001873 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1874 diag::err_toomany_element_decls));
1875
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001876 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1877 if (!D || D->isInvalidDecl())
1878 return StmtError();
1879
John McCall31168b02011-06-15 23:02:42 +00001880 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001881 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1882 // declare identifiers for objects having storage class 'auto' or
1883 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001884 if (!D->hasLocalStorage())
1885 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001886 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001887
1888 // If the type contained 'auto', deduce the 'auto' to 'id'.
1889 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001890 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1891 VK_RValue);
1892 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001893 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1894 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001895 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001896 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001897 D->setInvalidDecl();
1898 return StmtError();
1899 }
1900
Richard Smith061f1e22013-04-30 21:23:01 +00001901 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001902
Richard Smith51ec0cf2017-02-21 01:17:38 +00001903 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001904 SourceLocation Loc =
1905 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001906 Diag(Loc, diag::warn_auto_var_is_id)
1907 << D->getDeclName();
1908 }
1909 }
1910
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001911 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001912 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001913 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001914 return StmtError(Diag(First->getLocStart(),
1915 diag::err_selector_element_not_lvalue)
1916 << First->getSourceRange());
1917
Mike Stump11289f42009-09-09 15:08:12 +00001918 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001919 if (FirstType.isConstQualified())
1920 Diag(ForLoc, diag::err_selector_element_const_type)
1921 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001922 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001923 if (!FirstType->isDependentType() &&
1924 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001925 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001926 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1927 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001928 }
Chad Rosier02a84392012-08-10 17:56:09 +00001929
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001930 if (CollectionExprResult.isInvalid())
1931 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001932
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001933 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001934 if (CollectionExprResult.isInvalid())
1935 return StmtError();
1936
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001937 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1938 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001939}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001940
Richard Smith02e85f32011-04-14 22:09:26 +00001941/// Finish building a variable declaration for a for-range statement.
1942/// \return true if an error occurs.
1943static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001944 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001945 if (Decl->getType()->isUndeducedType()) {
1946 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1947 if (!Res.isUsable()) {
1948 Decl->setInvalidDecl();
1949 return true;
1950 }
1951 Init = Res.get();
1952 }
1953
Richard Smith02e85f32011-04-14 22:09:26 +00001954 // Deduce the type for the iterator variable now rather than leaving it to
1955 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001956 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001957 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001958 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001959 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001960 SemaRef.Diag(Loc, DiagID) << Init->getType();
1961 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001962 Decl->setInvalidDecl();
1963 return true;
1964 }
Richard Smith061f1e22013-04-30 21:23:01 +00001965 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001966
John McCall31168b02011-06-15 23:02:42 +00001967 // In ARC, infer lifetime.
1968 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1969 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001970 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001971 SemaRef.inferObjCARCLifetime(Decl))
1972 Decl->setInvalidDecl();
1973
Richard Smith3beb7c62017-01-12 02:27:38 +00001974 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001975 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001976 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001977 return false;
1978}
1979
Sam Panzer0f384432012-08-21 00:52:01 +00001980namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001981// An enum to represent whether something is dealing with a call to begin()
1982// or a call to end() in a range-based for loop.
1983enum BeginEndFunction {
1984 BEF_begin,
1985 BEF_end
1986};
Sam Panzer0f384432012-08-21 00:52:01 +00001987
Richard Smith02e85f32011-04-14 22:09:26 +00001988/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001989/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001990/// nor from the diagnostics produced when analysing the implicit expressions
1991/// required in a for-range statement.
1992void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001993 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001994 CallExpr *CE = dyn_cast<CallExpr>(E);
1995 if (!CE)
1996 return;
1997 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1998 if (!D)
1999 return;
2000 SourceLocation Loc = D->getLocation();
2001
2002 std::string Description;
2003 bool IsTemplate = false;
2004 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2005 Description = SemaRef.getTemplateArgumentBindingsText(
2006 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2007 IsTemplate = true;
2008 }
2009
2010 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2011 << BEF << IsTemplate << Description << E->getType();
2012}
2013
Sam Panzer0f384432012-08-21 00:52:01 +00002014/// Build a variable declaration for a for-range statement.
2015VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2016 QualType Type, const char *Name) {
2017 DeclContext *DC = SemaRef.CurContext;
2018 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2019 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2020 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002021 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002022 Decl->setImplicit();
2023 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002024}
2025
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002026}
Richard Smith02e85f32011-04-14 22:09:26 +00002027
Fariborz Jahanian00213472012-07-06 19:04:04 +00002028static bool ObjCEnumerationCollection(Expr *Collection) {
2029 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002030 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002031}
2032
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002033/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002034///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002035/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002036/// A range-based for statement is equivalent to
2037///
2038/// {
2039/// auto && __range = range-init;
2040/// for ( auto __begin = begin-expr,
2041/// __end = end-expr;
2042/// __begin != __end;
2043/// ++__begin ) {
2044/// for-range-declaration = *__begin;
2045/// statement
2046/// }
2047/// }
2048///
2049/// The body of the loop is not available yet, since it cannot be analysed until
2050/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002051StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2052 SourceLocation CoawaitLoc, Stmt *First,
2053 SourceLocation ColonLoc, Expr *Range,
2054 SourceLocation RParenLoc,
2055 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002056 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002057 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002058
Richard Smith3249fed2013-08-21 01:40:36 +00002059 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002060 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002061
2062 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2063 assert(DS && "first part of for range not a decl stmt");
2064
2065 if (!DS->isSingleDecl()) {
2066 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
2067 return StmtError();
2068 }
Richard Smith02e85f32011-04-14 22:09:26 +00002069
Richard Smith3249fed2013-08-21 01:40:36 +00002070 Decl *LoopVar = DS->getSingleDecl();
2071 if (LoopVar->isInvalidDecl() || !Range ||
2072 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2073 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002074 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002075 }
Richard Smith02e85f32011-04-14 22:09:26 +00002076
Eric Fiselierb936a392017-06-14 03:24:55 +00002077 // Build the coroutine state immediately and not later during template
2078 // instantiation
2079 if (!CoawaitLoc.isInvalid()) {
2080 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2081 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002082 }
2083
Richard Smith02e85f32011-04-14 22:09:26 +00002084 // Build auto && __range = range-init
2085 SourceLocation RangeLoc = Range->getLocStart();
2086 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2087 Context.getAutoRRefDeductType(),
2088 "__range");
2089 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002090 diag::err_for_range_deduction_failure)) {
2091 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002092 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002093 }
Richard Smith02e85f32011-04-14 22:09:26 +00002094
2095 // Claim the type doesn't contain auto: we've already done the checking.
2096 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002097 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002098 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002099 if (RangeDecl.isInvalid()) {
2100 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002101 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002102 }
Richard Smith02e85f32011-04-14 22:09:26 +00002103
Richard Smithcfd53b42015-10-22 06:13:50 +00002104 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002105 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2106 /*Cond=*/nullptr, /*Inc=*/nullptr,
2107 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002108}
2109
2110/// \brief Create the initialization, compare, and increment steps for
2111/// the range-based for loop expression.
2112/// This function does not handle array-based for loops,
2113/// which are created in Sema::BuildCXXForRangeStmt.
2114///
2115/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2116/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2117/// CandidateSet and BEF are set and some non-success value is returned on
2118/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002119static Sema::ForRangeStatus
2120BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2121 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2122 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2123 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2124 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002125 DeclarationNameInfo BeginNameInfo(
2126 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2127 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2128 ColonLoc);
2129
2130 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2131 Sema::LookupMemberName);
2132 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2133
2134 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2135 // - if _RangeT is a class type, the unqualified-ids begin and end are
2136 // looked up in the scope of class _RangeT as if by class member access
2137 // lookup (3.4.5), and if either (or both) finds at least one
2138 // declaration, begin-expr and end-expr are __range.begin() and
2139 // __range.end(), respectively;
2140 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2141 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2142
2143 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2144 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002145 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002146
2147 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2148 << RangeLoc << BeginRange->getType() << *BEF;
2149 return Sema::FRS_DiagnosticIssued;
2150 }
2151 } else {
2152 // - otherwise, begin-expr and end-expr are begin(__range) and
2153 // end(__range), respectively, where begin and end are looked up with
2154 // argument-dependent lookup (3.4.2). For the purposes of this name
2155 // lookup, namespace std is an associated namespace.
2156
2157 }
2158
Richard Smith9f690bd2015-10-27 06:02:45 +00002159 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002160 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002161 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002162 BeginMemberLookup, CandidateSet,
2163 BeginRange, BeginExpr);
2164
Richard Smith9f690bd2015-10-27 06:02:45 +00002165 if (RangeStatus != Sema::FRS_Success) {
2166 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2167 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2168 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002169 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002170 }
Eric Fiselierb936a392017-06-14 03:24:55 +00002171 if (!CoawaitLoc.isInvalid()) {
2172 // FIXME: getCurScope() should not be used during template instantiation.
2173 // We should pick up the set of unqualified lookup results for operator
2174 // co_await during the initial parse.
2175 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2176 BeginExpr->get());
2177 if (BeginExpr->isInvalid())
2178 return Sema::FRS_DiagnosticIssued;
2179 }
Sam Panzer0f384432012-08-21 00:52:01 +00002180 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2181 diag::err_for_range_iter_deduction_failure)) {
2182 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2183 return Sema::FRS_DiagnosticIssued;
2184 }
2185
Richard Smith9f690bd2015-10-27 06:02:45 +00002186 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002187 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002188 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002189 EndMemberLookup, CandidateSet,
2190 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002191 if (RangeStatus != Sema::FRS_Success) {
2192 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2193 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2194 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002195 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002196 }
Sam Panzer0f384432012-08-21 00:52:01 +00002197 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2198 diag::err_for_range_iter_deduction_failure)) {
2199 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2200 return Sema::FRS_DiagnosticIssued;
2201 }
2202 return Sema::FRS_Success;
2203}
2204
2205/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002206/// If the attempt fails, this function will return a valid, null StmtResult
2207/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002208static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2209 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002210 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002211 Stmt *LoopVarDecl,
2212 SourceLocation ColonLoc,
2213 Expr *Range,
2214 SourceLocation RangeLoc,
2215 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002216 // Determine whether we can rebuild the for-range statement with a
2217 // dereferenced range expression.
2218 ExprResult AdjustedRange;
2219 {
2220 Sema::SFINAETrap Trap(SemaRef);
2221
2222 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2223 if (AdjustedRange.isInvalid())
2224 return StmtResult();
2225
Richard Smith9f690bd2015-10-27 06:02:45 +00002226 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2227 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2228 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002229 if (SR.isInvalid())
2230 return StmtResult();
2231 }
2232
2233 // The attempt to dereference worked well enough that it could produce a valid
2234 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2235 // case there are any other (non-fatal) problems with it.
2236 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2237 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002238 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2239 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002240 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002241}
2242
Richard Smith3249fed2013-08-21 01:40:36 +00002243namespace {
2244/// RAII object to automatically invalidate a declaration if an error occurs.
2245struct InvalidateOnErrorScope {
2246 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2247 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2248 ~InvalidateOnErrorScope() {
2249 if (Enabled && Trap.hasErrorOccurred())
2250 D->setInvalidDecl();
2251 }
2252
2253 DiagnosticErrorTrap Trap;
2254 Decl *D;
2255 bool Enabled;
2256};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002257}
Richard Smith3249fed2013-08-21 01:40:36 +00002258
Richard Smitha05b3b52012-09-20 21:52:32 +00002259/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002260StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002261Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002262 SourceLocation ColonLoc, Stmt *RangeDecl,
2263 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002264 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002265 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002266 // FIXME: This should not be used during template instantiation. We should
2267 // pick up the set of unqualified lookup results for the != and + operators
2268 // in the initial parse.
2269 //
2270 // Testcase (accepts-invalid):
2271 // template<typename T> void f() { for (auto x : T()) {} }
2272 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2273 // bool operator!=(N::X, N::X); void operator++(N::X);
2274 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002275 Scope *S = getCurScope();
2276
2277 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2278 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2279 QualType RangeVarType = RangeVar->getType();
2280
2281 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2282 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2283
Richard Smith3249fed2013-08-21 01:40:36 +00002284 // If we hit any errors, mark the loop variable as invalid if its type
2285 // contains 'auto'.
2286 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2287 LoopVar->getType()->isUndeducedType());
2288
Richard Smith01694c32016-03-20 10:33:40 +00002289 StmtResult BeginDeclStmt = Begin;
2290 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002291 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2292
Richard Smith27d807c2013-04-30 13:56:41 +00002293 if (RangeVarType->isDependentType()) {
2294 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002295 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002296
2297 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2298 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002299 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2300 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2301 for (auto *Binding : DD->bindings())
2302 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002303 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002304 }
Richard Smith01694c32016-03-20 10:33:40 +00002305 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002306 SourceLocation RangeLoc = RangeVar->getLocation();
2307
Ted Kremenekbed648e2011-10-10 22:36:28 +00002308 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2309
2310 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2311 VK_LValue, ColonLoc);
2312 if (BeginRangeRef.isInvalid())
2313 return StmtError();
2314
2315 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2316 VK_LValue, ColonLoc);
2317 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002318 return StmtError();
2319
2320 QualType AutoType = Context.getAutoDeductType();
2321 Expr *Range = RangeVar->getInit();
2322 if (!Range)
2323 return StmtError();
2324 QualType RangeType = Range->getType();
2325
2326 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002327 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002328 return StmtError();
2329
2330 // Build auto __begin = begin-expr, __end = end-expr.
2331 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2332 "__begin");
2333 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2334 "__end");
2335
2336 // Build begin-expr and end-expr and attach to __begin and __end variables.
2337 ExprResult BeginExpr, EndExpr;
2338 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2339 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2340 // __range + __bound, respectively, where __bound is the array bound. If
2341 // _RangeT is an array of unknown size or an array of incomplete type,
2342 // the program is ill-formed;
2343
2344 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002345 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002346 if (!CoawaitLoc.isInvalid()) {
2347 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2348 if (BeginExpr.isInvalid())
2349 return StmtError();
2350 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002351 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002352 diag::err_for_range_iter_deduction_failure)) {
2353 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2354 return StmtError();
2355 }
2356
2357 // Find the array bound.
2358 ExprResult BoundExpr;
2359 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002360 BoundExpr = IntegerLiteral::Create(
2361 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002362 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002363 dyn_cast<VariableArrayType>(UnqAT)) {
2364 // For a variably modified type we can't just use the expression within
2365 // the array bounds, since we don't want that to be re-evaluated here.
2366 // Rather, we need to determine what it was when the array was first
2367 // created - so we resort to using sizeof(vla)/sizeof(element).
2368 // For e.g.
2369 // void f(int b) {
2370 // int vla[b];
2371 // b = -1; <-- This should not affect the num of iterations below
2372 // for (int &c : vla) { .. }
2373 // }
2374
2375 // FIXME: This results in codegen generating IR that recalculates the
2376 // run-time number of elements (as opposed to just using the IR Value
2377 // that corresponds to the run-time value of each bound that was
2378 // generated when the array was created.) If this proves too embarassing
2379 // even for unoptimized IR, consider passing a magic-value/cookie to
2380 // codegen that then knows to simply use that initial llvm::Value (that
2381 // corresponds to the bound at time of array creation) within
2382 // getelementptr. But be prepared to pay the price of increasing a
2383 // customized form of coupling between the two components - which could
2384 // be hard to maintain as the codebase evolves.
2385
2386 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2387 EndVar->getLocation(), UETT_SizeOf,
2388 /*isType=*/true,
2389 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2390 VAT->desugar(), RangeLoc))
2391 .getAsOpaquePtr(),
2392 EndVar->getSourceRange());
2393 if (SizeOfVLAExprR.isInvalid())
2394 return StmtError();
2395
2396 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2397 EndVar->getLocation(), UETT_SizeOf,
2398 /*isType=*/true,
2399 CreateParsedType(VAT->desugar(),
2400 Context.getTrivialTypeSourceInfo(
2401 VAT->getElementType(), RangeLoc))
2402 .getAsOpaquePtr(),
2403 EndVar->getSourceRange());
2404 if (SizeOfEachElementExprR.isInvalid())
2405 return StmtError();
2406
2407 BoundExpr =
2408 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2409 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2410 if (BoundExpr.isInvalid())
2411 return StmtError();
2412
2413 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002414 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2415 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002416 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002417 }
2418
2419 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002420 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002421 BoundExpr.get());
2422 if (EndExpr.isInvalid())
2423 return StmtError();
2424 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2425 diag::err_for_range_iter_deduction_failure)) {
2426 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2427 return StmtError();
2428 }
2429 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002430 OverloadCandidateSet CandidateSet(RangeLoc,
2431 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002432 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002433 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2434 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2435 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2436 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002437
Richard Smitha05b3b52012-09-20 21:52:32 +00002438 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002439 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002440 // If the range is being built from an array parameter, emit a
2441 // a diagnostic that it is being treated as a pointer.
2442 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2443 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2444 QualType ArrayTy = PVD->getOriginalType();
2445 QualType PointerTy = PVD->getType();
2446 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2447 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2448 << RangeLoc << PVD << ArrayTy << PointerTy;
2449 Diag(PVD->getLocation(), diag::note_declared_at);
2450 return StmtError();
2451 }
2452 }
2453 }
2454
2455 // If building the range failed, try dereferencing the range expression
2456 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002457 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002458 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002459 LoopVarDecl, ColonLoc,
2460 Range, RangeLoc,
2461 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002462 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002463 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002464 }
2465
Sam Panzer0f384432012-08-21 00:52:01 +00002466 // Otherwise, emit diagnostics if we haven't already.
2467 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002468 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002469 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2470 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002471 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002472 }
2473 // Return an error if no fix was discovered.
2474 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002475 return StmtError();
2476 }
2477
Sam Panzer0f384432012-08-21 00:52:01 +00002478 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2479 "invalid range expression in for loop");
2480
2481 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002482 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002483 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2484 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002485 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2486 ? diag::warn_for_range_begin_end_types_differ
2487 : diag::ext_for_range_begin_end_types_differ)
2488 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002489 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2490 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2491 }
2492
Richard Smith01694c32016-03-20 10:33:40 +00002493 BeginDeclStmt =
2494 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2495 EndDeclStmt =
2496 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002497
Ted Kremenekbed648e2011-10-10 22:36:28 +00002498 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2499 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002500 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002501 if (BeginRef.isInvalid())
2502 return StmtError();
2503
Richard Smith02e85f32011-04-14 22:09:26 +00002504 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2505 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002506 if (EndRef.isInvalid())
2507 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002508
2509 // Build and check __begin != __end expression.
2510 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2511 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002512 if (!NotEqExpr.isInvalid())
2513 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2514 if (!NotEqExpr.isInvalid())
2515 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002516 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002517 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2518 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002519 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2520 if (!Context.hasSameType(BeginType, EndType))
2521 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2522 return StmtError();
2523 }
2524
2525 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002526 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2527 VK_LValue, ColonLoc);
2528 if (BeginRef.isInvalid())
2529 return StmtError();
2530
Richard Smith02e85f32011-04-14 22:09:26 +00002531 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002532 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002533 // FIXME: getCurScope() should not be used during template instantiation.
2534 // We should pick up the set of unqualified lookup results for operator
2535 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002536 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002537 if (!IncrExpr.isInvalid())
2538 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002539 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002540 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2541 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002542 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2543 return StmtError();
2544 }
2545
2546 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002547 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2548 VK_LValue, ColonLoc);
2549 if (BeginRef.isInvalid())
2550 return StmtError();
2551
Richard Smith02e85f32011-04-14 22:09:26 +00002552 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2553 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002554 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2555 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002556 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2557 return StmtError();
2558 }
2559
Richard Smitha05b3b52012-09-20 21:52:32 +00002560 // Attach *__begin as initializer for VD. Don't touch it if we're just
2561 // trying to determine whether this would be a valid range.
2562 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002563 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002564 if (LoopVar->isInvalidDecl())
2565 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2566 }
2567 }
2568
Richard Smitha05b3b52012-09-20 21:52:32 +00002569 // Don't bother to actually allocate the result if we're just trying to
2570 // determine whether it would be valid.
2571 if (Kind == BFRK_Check)
2572 return StmtResult();
2573
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002574 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002575 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2576 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002577 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2578 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002579}
2580
Chad Rosier02a84392012-08-10 17:56:09 +00002581/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002582/// statement.
2583StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2584 if (!S || !B)
2585 return StmtError();
2586 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002587
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002588 ForStmt->setBody(B);
2589 return S;
2590}
2591
Richard Trieu3e1d4832015-04-13 22:08:55 +00002592// Warn when the loop variable is a const reference that creates a copy.
2593// Suggest using the non-reference type for copies. If a copy can be prevented
2594// suggest the const reference type that would do so.
2595// For instance, given "for (const &Foo : Range)", suggest
2596// "for (const Foo : Range)" to denote a copy is made for the loop. If
2597// possible, also suggest "for (const &Bar : Range)" if this type prevents
2598// the copy altogether.
2599static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2600 const VarDecl *VD,
2601 QualType RangeInitType) {
2602 const Expr *InitExpr = VD->getInit();
2603 if (!InitExpr)
2604 return;
2605
2606 QualType VariableType = VD->getType();
2607
Tim Shen4a05bb82016-06-21 20:29:17 +00002608 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2609 if (!Cleanups->cleanupsHaveSideEffects())
2610 InitExpr = Cleanups->getSubExpr();
2611
Richard Trieu3e1d4832015-04-13 22:08:55 +00002612 const MaterializeTemporaryExpr *MTE =
2613 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2614
2615 // No copy made.
2616 if (!MTE)
2617 return;
2618
2619 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2620
2621 // Searching for either UnaryOperator for dereference of a pointer or
2622 // CXXOperatorCallExpr for handling iterators.
2623 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2624 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2625 E = CCE->getArg(0);
2626 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2627 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2628 E = ME->getBase();
2629 } else {
2630 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2631 E = MTE->GetTemporaryExpr();
2632 }
2633 E = E->IgnoreImpCasts();
2634 }
2635
2636 bool ReturnsReference = false;
2637 if (isa<UnaryOperator>(E)) {
2638 ReturnsReference = true;
2639 } else {
2640 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2641 const FunctionDecl *FD = Call->getDirectCallee();
2642 QualType ReturnType = FD->getReturnType();
2643 ReturnsReference = ReturnType->isReferenceType();
2644 }
2645
2646 if (ReturnsReference) {
2647 // Loop variable creates a temporary. Suggest either to go with
2648 // non-reference loop variable to indiciate a copy is made, or
2649 // the correct time to bind a const reference.
2650 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2651 << VD << VariableType << E->getType();
2652 QualType NonReferenceType = VariableType.getNonReferenceType();
2653 NonReferenceType.removeLocalConst();
2654 QualType NewReferenceType =
2655 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2656 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2657 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2658 } else {
2659 // The range always returns a copy, so a temporary is always created.
2660 // Suggest removing the reference from the loop variable.
2661 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2662 << VD << RangeInitType;
2663 QualType NonReferenceType = VariableType.getNonReferenceType();
2664 NonReferenceType.removeLocalConst();
2665 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2666 << NonReferenceType << VD->getSourceRange();
2667 }
2668}
2669
2670// Warns when the loop variable can be changed to a reference type to
2671// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2672// "for (const Foo &x : Range)" if this form does not make a copy.
2673static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2674 const VarDecl *VD) {
2675 const Expr *InitExpr = VD->getInit();
2676 if (!InitExpr)
2677 return;
2678
2679 QualType VariableType = VD->getType();
2680
2681 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2682 if (!CE->getConstructor()->isCopyConstructor())
2683 return;
2684 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2685 if (CE->getCastKind() != CK_LValueToRValue)
2686 return;
2687 } else {
2688 return;
2689 }
2690
2691 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2692 // should be emitted. Also, only ignore POD types with trivial copy
2693 // constructors.
2694 if (VariableType.isPODType(SemaRef.Context))
2695 return;
2696
2697 // Suggest changing from a const variable to a const reference variable
2698 // if doing so will prevent a copy.
2699 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2700 << VD << VariableType << InitExpr->getType();
2701 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2702 << SemaRef.Context.getLValueReferenceType(VariableType)
2703 << VD->getSourceRange();
2704}
2705
2706/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2707/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2708/// using "const foo x" to show that a copy is made
2709/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2710/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2711/// prevent the copy.
2712/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2713/// Suggest "const foo &x" to prevent the copy.
2714static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2715 const CXXForRangeStmt *ForStmt) {
2716 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2717 ForStmt->getLocStart()) &&
2718 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2719 ForStmt->getLocStart()) &&
2720 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2721 ForStmt->getLocStart())) {
2722 return;
2723 }
2724
2725 const VarDecl *VD = ForStmt->getLoopVariable();
2726 if (!VD)
2727 return;
2728
2729 QualType VariableType = VD->getType();
2730
2731 if (VariableType->isIncompleteType())
2732 return;
2733
2734 const Expr *InitExpr = VD->getInit();
2735 if (!InitExpr)
2736 return;
2737
2738 if (VariableType->isReferenceType()) {
2739 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2740 ForStmt->getRangeInit()->getType());
2741 } else if (VariableType.isConstQualified()) {
2742 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2743 }
2744}
2745
Richard Smith02e85f32011-04-14 22:09:26 +00002746/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2747/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2748/// body cannot be performed until after the type of the range variable is
2749/// determined.
2750StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2751 if (!S || !B)
2752 return StmtError();
2753
Fariborz Jahanian00213472012-07-06 19:04:04 +00002754 if (isa<ObjCForCollectionStmt>(S))
2755 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002756
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002757 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2758 ForStmt->setBody(B);
2759
2760 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2761 diag::warn_empty_range_based_for_body);
2762
Richard Trieu3e1d4832015-04-13 22:08:55 +00002763 DiagnoseForRangeVariableCopies(*this, ForStmt);
2764
Richard Smith02e85f32011-04-14 22:09:26 +00002765 return S;
2766}
2767
Chris Lattnercab02a62011-02-17 20:34:02 +00002768StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2769 SourceLocation LabelLoc,
2770 LabelDecl *TheDecl) {
2771 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002772 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002773 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002774}
Chris Lattner1c310502007-05-31 06:00:00 +00002775
John McCalldadc5752010-08-24 06:29:42 +00002776StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002777Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002778 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002779 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002780 if (!E->isTypeDependent()) {
2781 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002782 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002783 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002784 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002785 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2786 if (ExprRes.isInvalid())
2787 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002788 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002789 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002790 return StmtError();
2791 }
John McCalla95172b2010-08-01 00:26:45 +00002792
Richard Smith945f8d32013-01-14 22:39:08 +00002793 ExprResult ExprRes = ActOnFinishFullExpr(E);
2794 if (ExprRes.isInvalid())
2795 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002796 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002797
John McCallaab3e412010-08-25 08:40:02 +00002798 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002799
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002800 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002801}
2802
Nico Weberd64657f2015-03-09 02:47:59 +00002803static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2804 const Scope &DestScope) {
2805 if (!S.CurrentSEHFinally.empty() &&
2806 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2807 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2808 }
2809}
2810
John McCalldadc5752010-08-24 06:29:42 +00002811StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002812Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002813 Scope *S = CurScope->getContinueParent();
2814 if (!S) {
2815 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002816 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002817 }
Nico Weberd64657f2015-03-09 02:47:59 +00002818 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002819
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002820 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002821}
2822
John McCalldadc5752010-08-24 06:29:42 +00002823StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002824Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002825 Scope *S = CurScope->getBreakParent();
2826 if (!S) {
2827 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002828 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002829 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002830 if (S->isOpenMPLoopScope())
2831 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2832 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002833 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002834
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002835 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002836}
2837
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002839/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002840///
Douglas Gregor5d369002011-01-21 18:05:27 +00002841/// \param ReturnType If we're determining the copy elision candidate for
2842/// a return statement, this is the return type of the function. If we're
2843/// determining the copy elision candidate for a throw expression, this will
2844/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002845///
Douglas Gregor5d369002011-01-21 18:05:27 +00002846/// \param E The expression being returned from the function or block, or
2847/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002848///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002849/// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2850/// id-expressions that could be moved out of the function to be considered NRVO
2851/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2852/// determine whether we should try to move as part of a return or throw (which
2853/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002854///
2855/// \returns The NRVO candidate variable, if the return statement may use the
2856/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002857VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2858 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002859 if (!getLangOpts().CPlusPlus)
2860 return nullptr;
2861
2862 // - in a return statement in a function [where] ...
2863 // ... the expression is the name of a non-volatile automatic object ...
2864 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002865 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002866 return nullptr;
2867 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2868 if (!VD)
2869 return nullptr;
2870
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002871 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002872 return VD;
2873 return nullptr;
2874}
2875
2876bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002877 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002878 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002879 // - in a return statement in a function with ...
2880 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002881 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002882 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002883 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002884 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002885 // When considering moving this expression out, allow dissimilar types.
2886 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002887 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2888 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890
John McCall03318c12011-11-11 03:57:31 +00002891 // ...object (other than a function or catch-clause parameter)...
2892 if (VD->getKind() != Decl::Var &&
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002893 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002894 return false;
2895 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896
John McCall03318c12011-11-11 03:57:31 +00002897 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002898 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002899
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002900 // Return false if VD is a __block variable. We don't want to implicitly move
2901 // out of a __block variable during a return because we cannot assume the
2902 // variable will no longer be used.
2903 if (VD->hasAttr<BlocksAttr>()) return false;
2904
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002905 if (AllowParamOrMoveConstructible)
2906 return true;
2907
John McCall03318c12011-11-11 03:57:31 +00002908 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002909 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002910
John McCall03318c12011-11-11 03:57:31 +00002911 // Variables with higher required alignment than their type's ABI
2912 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002913 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002914 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002915 return false;
John McCall03318c12011-11-11 03:57:31 +00002916
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002917 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002918}
2919
Douglas Gregor626fbed2011-01-21 21:08:57 +00002920/// \brief Perform the initialization of a potentially-movable value, which
2921/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002922///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002923/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00002924/// returned lvalues as rvalues in certain cases (to prefer move construction),
2925/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002926ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002927Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2928 const VarDecl *NRVOCandidate,
2929 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002930 Expr *Value,
2931 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002932 // C++14 [class.copy]p32:
2933 // When the criteria for elision of a copy/move operation are met, but not for
2934 // an exception-declaration, and the object to be copied is designated by an
2935 // lvalue, or when the expression in a return statement is a (possibly
2936 // parenthesized) id-expression that names an object with automatic storage
2937 // duration declared in the body or parameter-declaration-clause of the
2938 // innermost enclosing function or lambda-expression, overload resolution to
2939 // select the constructor for the copy is first performed as if the object
2940 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002941 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002942
2943 if (AllowNRVO && !NRVOCandidate)
2944 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2945
2946 if (AllowNRVO && NRVOCandidate) {
2947 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2948 CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002949
Douglas Gregorf282a762011-01-21 19:38:21 +00002950 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002952 InitializationKind Kind = InitializationKind::CreateCopy(
2953 Value->getLocStart(), Value->getLocStart());
2954
2955 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002956 if (Seq) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002957 for (const InitializationSequence::Step &Step : Seq.steps()) {
2958 if (!(Step.Kind ==
2959 InitializationSequence::SK_ConstructorInitialization ||
2960 (Step.Kind == InitializationSequence::SK_UserConversion &&
2961 isa<CXXConstructorDecl>(Step.Function.Function))))
Douglas Gregorf282a762011-01-21 19:38:21 +00002962 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002964 CXXConstructorDecl *Constructor =
2965 cast<CXXConstructorDecl>(Step.Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966
Douglas Gregorf282a762011-01-21 19:38:21 +00002967 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002968 = Constructor->getParamDecl(0)->getType()
2969 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002971 // [...] If the first overload resolution fails or was not performed, or
2972 // if the type of the first parameter of the selected constructor is not
Nico Weber0a234042017-05-05 17:15:08 +00002973 // an rvalue reference to the object's type (possibly cv-qualified),
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002974 // overload resolution is performed again, considering the object as an
2975 // lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002977 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002978 NRVOCandidate->getType()))
Douglas Gregorf282a762011-01-21 19:38:21 +00002979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980
Douglas Gregorf282a762011-01-21 19:38:21 +00002981 // Promote "AsRvalue" to the heap, since we now need this
2982 // expression node to persist.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002983 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2984 Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985
Douglas Gregorf282a762011-01-21 19:38:21 +00002986 // Complete type-checking the initialization of the return type
2987 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002988 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002989 }
2990 }
2991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992
Douglas Gregorf282a762011-01-21 19:38:21 +00002993 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002995 // (again) now with the return value expression as written.
2996 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002997 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998
Douglas Gregorf282a762011-01-21 19:38:21 +00002999 return Res;
3000}
3001
Richard Smith4db51c22013-09-25 05:02:54 +00003002/// \brief Determine whether the declared return type of the specified function
3003/// contains 'auto'.
3004static bool hasDeducedReturnType(FunctionDecl *FD) {
3005 const FunctionProtoType *FPT =
3006 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003007 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003008}
3009
Eli Friedman34b49062012-01-26 03:00:14 +00003010/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3011/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003012///
John McCalldadc5752010-08-24 06:29:42 +00003013StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003014Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3015 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003016 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003017 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003018 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003019 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003020 bool HasDeducedReturnType =
3021 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003022
Faisal Valid143a0c2017-04-01 21:30:49 +00003023 if (ExprEvalContexts.back().Context ==
3024 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003025 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3026 if (RetValExp) {
3027 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3028 if (ER.isInvalid())
3029 return StmtError();
3030 RetValExp = ER.get();
3031 }
3032 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3033 }
3034
3035 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003036 // In C++1y, the return type may involve 'auto'.
3037 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3038 FunctionDecl *FD = CurLambda->CallOperator;
3039 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003040 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003041
3042 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3043 assert(AT && "lost auto type from lambda return type");
3044 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3045 FD->setInvalidDecl();
3046 return StmtError();
3047 }
Alp Toker314cc812014-01-25 16:55:45 +00003048 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003049 } else if (CurCap->HasImplicitReturnType) {
3050 // For blocks/lambdas with implicit return types, we check each return
3051 // statement individually, and deduce the common return type when the block
3052 // or lambda is completed.
3053 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003054 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003055 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3056 if (Result.isInvalid())
3057 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003058 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003059
Richard Smith5a0e50c2014-12-19 22:10:51 +00003060 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3061 // when deducing a return type for a lambda-expression (or by extension
3062 // for a block). These rules differ from the stated C++11 rules only in
3063 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003064 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003065 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003066 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003067 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003068 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003069 if (RetValExp) {
3070 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3071 // initializer list, because it is not an expression (even
3072 // though we represent it as one). We still deduce 'void'.
3073 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3074 << RetValExp->getSourceRange();
3075 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003076
Jordan Rosed39e5f12012-07-02 21:19:23 +00003077 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003078 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003079
3080 // Although we'll properly infer the type of the block once it's completed,
3081 // make sure we provide a return type now for better error recovery.
3082 if (CurCap->ReturnType.isNull())
3083 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003084 }
Eli Friedman34b49062012-01-26 03:00:14 +00003085 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003086
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003087 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003088 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3089 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3090 return StmtError();
3091 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003092 } else if (CapturedRegionScopeInfo *CurRegion =
3093 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3094 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3095 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003096 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003097 assert(CurLambda && "unknown kind of captured scope");
3098 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3099 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003100 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3101 return StmtError();
3102 }
3103 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003104
Steve Naroffc540d662008-09-03 18:15:37 +00003105 // Otherwise, verify that this result type matches the previous one. We are
3106 // pickier with blocks than for normal functions because we don't have GCC
3107 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003108 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003109 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003110 // Delay processing for now. TODO: there are lots of dependent
3111 // types we can conclusively prove aren't void.
3112 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003113 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003114 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003115 (RetValExp->isTypeDependent() ||
3116 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003117 if (!getLangOpts().CPlusPlus &&
3118 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003119 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003120 else {
3121 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003122 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003123 }
Steve Naroffc540d662008-09-03 18:15:37 +00003124 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003125 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003126 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3127 } else if (!RetValExp->isTypeDependent()) {
3128 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003129
John McCall5500ef22011-08-17 22:09:46 +00003130 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3131 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3132 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003133
John McCall5500ef22011-08-17 22:09:46 +00003134 // In C++ the return statement is handled via a copy initialization.
3135 // the C version of which boils down to CheckSingleAssignmentConstraints.
3136 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3137 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3138 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003139 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003140 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3141 FnRetType, RetValExp);
3142 if (Res.isInvalid()) {
3143 // FIXME: Cleanup temporaries here, anyway?
3144 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003145 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003146 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003147 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003148 } else {
3149 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00003150 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003151
John McCall75f92b52011-08-17 21:34:14 +00003152 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003153 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3154 if (ER.isInvalid())
3155 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003156 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003157 }
John McCall5500ef22011-08-17 22:09:46 +00003158 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3159 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003160
Jordan Rosed39e5f12012-07-02 21:19:23 +00003161 // If we need to check for the named return value optimization,
3162 // or if we need to infer the return type,
3163 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003164 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003165 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Richard Smith9f690bd2015-10-27 06:02:45 +00003167 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3168 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3169
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003170 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003171}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003172
Nico Weber72889432014-09-06 01:25:55 +00003173namespace {
3174/// \brief Marks all typedefs in all local classes in a type referenced.
3175///
3176/// In a function like
3177/// auto f() {
3178/// struct S { typedef int a; };
3179/// return S();
3180/// }
3181///
3182/// the local type escapes and could be referenced in some TUs but not in
3183/// others. Pretend that all local typedefs are always referenced, to not warn
3184/// on this. This isn't necessary if f has internal linkage, or the typedef
3185/// is private.
3186class LocalTypedefNameReferencer
3187 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3188public:
3189 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3190 bool VisitRecordType(const RecordType *RT);
3191private:
3192 Sema &S;
3193};
3194bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3195 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3196 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3197 R->isDependentType())
3198 return true;
3199 for (auto *TmpD : R->decls())
3200 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3201 if (T->getAccess() != AS_private || R->hasFriends())
3202 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3203 return true;
3204}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003205}
Nico Weber72889432014-09-06 01:25:55 +00003206
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003207TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003208 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003209 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3210 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003211 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003212}
3213
Richard Smith2a7d4812013-05-04 07:00:32 +00003214/// Deduce the return type for a function from a returned expression, per
3215/// C++1y [dcl.spec.auto]p6.
3216bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3217 SourceLocation ReturnLoc,
3218 Expr *&RetExpr,
3219 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003220 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003221 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003222
Richard Smithc58f38f2013-08-14 20:16:31 +00003223 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3224 // If the deduction is for a return statement and the initializer is
3225 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003226 Diag(RetExpr->getExprLoc(),
3227 getCurLambda() ? diag::err_lambda_return_init_list
3228 : diag::err_auto_fn_return_init_list)
3229 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003230 return true;
3231 }
3232
3233 if (FD->isDependentContext()) {
3234 // C++1y [dcl.spec.auto]p12:
3235 // Return type deduction [...] occurs when the definition is
3236 // instantiated even if the function body contains a return
3237 // statement with a non-type-dependent operand.
3238 assert(AT->isDeduced() && "should have deduced to dependent type");
3239 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003240 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003241
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003242 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003243 // Otherwise, [...] deduce a value for U using the rules of template
3244 // argument deduction.
3245 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3246
3247 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3248 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3249 << OrigResultType.getType() << RetExpr->getType();
3250
3251 if (DAR != DAR_Succeeded)
3252 return true;
Nico Weber72889432014-09-06 01:25:55 +00003253
3254 // If a local type is part of the returned type, mark its fields as
3255 // referenced.
3256 LocalTypedefNameReferencer Referencer(*this);
3257 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003258 } else {
3259 // In the case of a return with no operand, the initializer is considered
3260 // to be void().
3261 //
3262 // Deduction here can only succeed if the return type is exactly 'cv auto'
3263 // or 'decltype(auto)', so just check for that case directly.
3264 if (!OrigResultType.getType()->getAs<AutoType>()) {
3265 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3266 << OrigResultType.getType();
3267 return true;
3268 }
3269 // We always deduce U = void in this case.
3270 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3271 if (Deduced.isNull())
3272 return true;
3273 }
3274
3275 // If a function with a declared return type that contains a placeholder type
3276 // has multiple return statements, the return type is deduced for each return
3277 // statement. [...] if the type deduced is not the same in each deduction,
3278 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003279 QualType DeducedT = AT->getDeducedType();
3280 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003281 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003282 // It is possible that NewAT->getDeducedType() is null. When that happens,
3283 // we should not crash, instead we ignore this deduction.
3284 if (NewAT->getDeducedType().isNull())
3285 return false;
3286
Douglas Gregora602a152015-10-01 20:20:47 +00003287 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003288 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003289 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3290 NewAT->getDeducedType());
3291 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003292 const LambdaScopeInfo *LambdaSI = getCurLambda();
3293 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3294 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003295 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003296 << true /*IsLambda*/;
3297 } else {
3298 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3299 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003300 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003301 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003302 return true;
3303 }
3304 } else if (!FD->isInvalidDecl()) {
3305 // Update all declarations of the function to have the deduced return type.
3306 Context.adjustDeducedFunctionResultType(FD, Deduced);
3307 }
3308
3309 return false;
3310}
3311
John McCalldadc5752010-08-24 06:29:42 +00003312StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003313Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3314 Scope *CurScope) {
3315 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003316 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3317 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003318 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003319
3320 if (VarDecl *VD =
3321 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3322 CurScope->addNRVOCandidate(VD);
3323 } else {
3324 CurScope->setNoNRVO();
3325 }
3326
Nico Weberd64657f2015-03-09 02:47:59 +00003327 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3328
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003329 return R;
3330}
3331
3332StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003333 // Check for unexpanded parameter packs.
3334 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3335 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003336
Eli Friedman34b49062012-01-26 03:00:14 +00003337 if (isa<CapturingScopeInfo>(getCurFunction()))
3338 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003339
Chris Lattner79413952008-12-04 23:50:19 +00003340 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003341 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003342 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003343 bool isObjCMethod = false;
3344
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003345 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003346 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003347 if (FD->hasAttrs())
3348 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003349 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003350 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003351 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003352 if (FD->isMain() && RetValExp)
3353 if (isa<CXXBoolLiteralExpr>(RetValExp))
3354 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3355 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003356 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003357 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003358 isObjCMethod = true;
3359 if (MD->hasAttrs())
3360 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003361 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3362 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003363 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003364 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003365 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3366 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003367 }
3368 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003369 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003370
Richard Smithb130fe72016-06-23 19:16:49 +00003371 // C++1z: discarded return statements are not considered when deducing a
3372 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003373 if (ExprEvalContexts.back().Context ==
3374 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003375 FnRetType->getContainedAutoType()) {
3376 if (RetValExp) {
3377 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3378 if (ER.isInvalid())
3379 return StmtError();
3380 RetValExp = ER.get();
3381 }
3382 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3383 }
3384
Richard Smith2a7d4812013-05-04 07:00:32 +00003385 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3386 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003387 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003388 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3389 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003390 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003391 FD->setInvalidDecl();
3392 return StmtError();
3393 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003394 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003395 }
3396 }
3397 }
3398
Richard Smithc58f38f2013-08-14 20:16:31 +00003399 bool HasDependentReturnType = FnRetType->isDependentType();
3400
Craig Topperc3ec1492014-05-26 06:22:03 +00003401 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003402 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003403 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003404 if (isa<InitListExpr>(RetValExp)) {
3405 // We simply never allow init lists as the return value of void
3406 // functions. This is compatible because this was never allowed before,
3407 // so there's no legacy code to deal with.
3408 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3409 int FunctionKind = 0;
3410 if (isa<ObjCMethodDecl>(CurDecl))
3411 FunctionKind = 1;
3412 else if (isa<CXXConstructorDecl>(CurDecl))
3413 FunctionKind = 2;
3414 else if (isa<CXXDestructorDecl>(CurDecl))
3415 FunctionKind = 3;
3416
3417 Diag(ReturnLoc, diag::err_return_init_list)
3418 << CurDecl->getDeclName() << FunctionKind
3419 << RetValExp->getSourceRange();
3420
3421 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003422 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003423 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003424 // C99 6.8.6.4p1 (ext_ since GCC warns)
3425 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003426 if (RetValExp->getType()->isVoidType()) {
3427 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3428 if (isa<CXXConstructorDecl>(CurDecl) ||
3429 isa<CXXDestructorDecl>(CurDecl))
3430 D = diag::err_ctor_dtor_returns_void;
3431 else
3432 D = diag::ext_return_has_void_expr;
3433 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003434 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003435 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003436 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003437 if (Result.isInvalid())
3438 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003439 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003440 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003441 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003442 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003443 // return of void in constructor/destructor is illegal in C++.
3444 if (D == diag::err_ctor_dtor_returns_void) {
3445 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3446 Diag(ReturnLoc, D)
3447 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3448 << RetValExp->getSourceRange();
3449 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003450 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003451 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003452 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003453 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003454
3455 int FunctionKind = 0;
3456 if (isa<ObjCMethodDecl>(CurDecl))
3457 FunctionKind = 1;
3458 else if (isa<CXXConstructorDecl>(CurDecl))
3459 FunctionKind = 2;
3460 else if (isa<CXXDestructorDecl>(CurDecl))
3461 FunctionKind = 3;
3462
Nick Lewycky1be750a2011-06-01 07:44:31 +00003463 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003464 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003465 << RetValExp->getSourceRange();
3466 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003467 }
Mike Stump11289f42009-09-09 15:08:12 +00003468
Sebastian Redleef474c2012-02-22 10:50:08 +00003469 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003470 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3471 if (ER.isInvalid())
3472 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003473 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003474 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003476
Craig Topperc3ec1492014-05-26 06:22:03 +00003477 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003478 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003479 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003480
David Majnemer2887ad32014-12-13 08:12:56 +00003481 unsigned DiagID;
3482 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3483 // C++11 [stmt.return]p2
3484 DiagID = diag::err_constexpr_return_missing_expr;
3485 FD->setInvalidDecl();
3486 } else if (getLangOpts().C99) {
3487 // C99 6.8.6.4p1 (ext_ since GCC warns)
3488 DiagID = diag::ext_return_missing_expr;
3489 } else {
3490 // C90 6.6.6.4p4
3491 DiagID = diag::warn_return_missing_expr;
3492 }
3493
3494 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003495 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003496 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003497 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003498
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003499 Result = new (Context) ReturnStmt(ReturnLoc);
3500 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003501 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003502 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003503
3504 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3505
3506 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3507 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3508 // function return.
3509
3510 // In C++ the return statement is handled via a copy initialization,
3511 // the C version of which boils down to CheckSingleAssignmentConstraints.
3512 if (RetValExp)
3513 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003514 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003515 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003517 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003518 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003520 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003521 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003522 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003523 return StmtError();
3524 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003525 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003526
3527 // If we have a related result type, we need to implicitly
3528 // convert back to the formal result type. We can't pretend to
3529 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003530 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003531 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003532 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3533 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003534 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3535 if (Res.isInvalid()) {
3536 // FIXME: Clean up temporaries here anyway?
3537 return StmtError();
3538 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003539 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003540 }
3541
Artyom Skrobov9f213442014-01-24 11:10:39 +00003542 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3543 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545
John McCallacf0ee52010-10-08 02:01:28 +00003546 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003547 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3548 if (ER.isInvalid())
3549 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003550 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003551 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003552 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554
3555 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003556 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003557 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003558 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003559
Richard Smith9f690bd2015-10-27 06:02:45 +00003560 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3561 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3562
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003563 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003564}
3565
John McCalldadc5752010-08-24 06:29:42 +00003566StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003567Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003568 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003569 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003570 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003571 if (Var && Var->isInvalidDecl())
3572 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003574 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003575}
3576
John McCalldadc5752010-08-24 06:29:42 +00003577StmtResult
John McCallb268a282010-08-23 23:25:46 +00003578Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003579 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003580}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003581
John McCalldadc5752010-08-24 06:29:42 +00003582StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003584 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003585 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003586 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3587
John McCallaab3e412010-08-25 08:40:02 +00003588 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003589 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003590 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3591 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003592}
3593
John McCall0bd3e402012-05-08 21:41:25 +00003594StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003595 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003596 ExprResult Result = DefaultLvalueConversion(Throw);
3597 if (Result.isInvalid())
3598 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003599
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003600 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003601 if (Result.isInvalid())
3602 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003603 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003604
Douglas Gregor2900c162010-04-22 21:44:01 +00003605 QualType ThrowType = Throw->getType();
3606 // Make sure the expression type is an ObjC pointer or "void *".
3607 if (!ThrowType->isDependentType() &&
3608 !ThrowType->isObjCObjectPointerType()) {
3609 const PointerType *PT = ThrowType->getAs<PointerType>();
3610 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003611 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003612 << Throw->getType() << Throw->getSourceRange());
3613 }
3614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003616 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003617}
3618
John McCalldadc5752010-08-24 06:29:42 +00003619StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003620Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003621 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003622 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003623 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3624
John McCallb268a282010-08-23 23:25:46 +00003625 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003626 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003627 // in the context of an @catch clause).
3628 Scope *AtCatchParent = CurScope;
3629 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3630 AtCatchParent = AtCatchParent->getParent();
3631 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003632 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633 }
John McCallb268a282010-08-23 23:25:46 +00003634 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003635}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003636
John McCalld9bb7432011-07-27 21:50:02 +00003637ExprResult
3638Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3639 ExprResult result = DefaultLvalueConversion(operand);
3640 if (result.isInvalid())
3641 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003642 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003643
3644 // Make sure the expression type is an ObjC pointer or "void *".
3645 QualType type = operand->getType();
3646 if (!type->isDependentType() &&
3647 !type->isObjCObjectPointerType()) {
3648 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003649 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3650 if (getLangOpts().CPlusPlus) {
3651 if (RequireCompleteType(atLoc, type,
3652 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003653 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003654 << type << operand->getSourceRange();
3655
3656 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003657 if (result.isInvalid())
3658 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003659 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003660 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003661 << type << operand->getSourceRange();
3662
3663 operand = result.get();
3664 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003665 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003666 << type << operand->getSourceRange();
3667 }
3668 }
John McCalld9bb7432011-07-27 21:50:02 +00003669 }
3670
3671 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003672 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003673}
3674
John McCalldadc5752010-08-24 06:29:42 +00003675StmtResult
John McCallb268a282010-08-23 23:25:46 +00003676Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3677 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003678 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003679 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003680 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003681}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003682
3683/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3684/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003685StmtResult
John McCall48871652010-08-21 09:40:31 +00003686Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003687 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003688 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003689 return new (Context)
3690 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003691}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003692
John McCall31168b02011-06-15 23:02:42 +00003693StmtResult
3694Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3695 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003696 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003697}
3698
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003699namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003700class CatchHandlerType {
3701 QualType QT;
3702 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003703
Aaron Ballman8aee642902015-04-08 00:05:29 +00003704 // This is a special constructor to be used only with DenseMapInfo's
3705 // getEmptyKey() and getTombstoneKey() functions.
3706 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3707 enum Unique { ForDenseMap };
3708 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3709
Sebastian Redl63c4da02009-07-29 17:15:45 +00003710public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003711 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003712 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003713 /// level pointer and cv-qualifiers.
3714 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3715 if (QT->isPointerType())
3716 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003717
Aaron Ballman8aee642902015-04-08 00:05:29 +00003718 if (IsPointer || QT->isReferenceType())
3719 QT = QT->getPointeeType();
3720 QT = QT.getUnqualifiedType();
3721 }
3722
3723 /// Used when creating a CatchHandlerType from a base class type; pretends the
3724 /// type passed in had the pointer qualifier, does not need to get an
3725 /// unqualified type.
3726 CatchHandlerType(QualType QT, bool IsPointer)
3727 : QT(QT), IsPointer(IsPointer) {}
3728
3729 QualType underlying() const { return QT; }
3730 bool isPointer() const { return IsPointer; }
3731
3732 friend bool operator==(const CatchHandlerType &LHS,
3733 const CatchHandlerType &RHS) {
3734 // If the pointer qualification does not match, we can return early.
3735 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003736 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003737 // Otherwise, check the underlying type without cv-qualifiers.
3738 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003739 }
3740};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003741} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003742
Aaron Ballman8aee642902015-04-08 00:05:29 +00003743namespace llvm {
3744template <> struct DenseMapInfo<CatchHandlerType> {
3745 static CatchHandlerType getEmptyKey() {
3746 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3747 CatchHandlerType::ForDenseMap);
3748 }
3749
3750 static CatchHandlerType getTombstoneKey() {
3751 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3752 CatchHandlerType::ForDenseMap);
3753 }
3754
3755 static unsigned getHashValue(const CatchHandlerType &Base) {
3756 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3757 }
3758
3759 static bool isEqual(const CatchHandlerType &LHS,
3760 const CatchHandlerType &RHS) {
3761 return LHS == RHS;
3762 }
3763};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003764}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003765
3766namespace {
3767class CatchTypePublicBases {
3768 ASTContext &Ctx;
3769 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3770 const bool CheckAgainstPointer;
3771
3772 CXXCatchStmt *FoundHandler;
3773 CanQualType FoundHandlerType;
3774
3775public:
3776 CatchTypePublicBases(
3777 ASTContext &Ctx,
3778 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3779 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3780 FoundHandler(nullptr) {}
3781
3782 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3783 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3784
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003785 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003786 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003787 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003788 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003789 auto I = M.find(Check);
3790 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003791 FoundHandler = I->second;
3792 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003793 return true;
3794 }
3795 }
3796 return false;
3797 }
3798};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003799}
Dan Gohman28ade552010-07-26 21:25:24 +00003800
Sebastian Redl9b244a82008-12-22 21:35:02 +00003801/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3802/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003803StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3804 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003805 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003806 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003807 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003808 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003809
Justin Lebar2a8db342016-09-28 22:45:54 +00003810 // Exceptions aren't allowed in CUDA device code.
3811 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00003812 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3813 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00003814
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003815 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3816 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3817
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003818 sema::FunctionScopeInfo *FSI = getCurFunction();
3819
Reid Klecknere7175912015-02-02 22:15:31 +00003820 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003821 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003822 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003823 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003824 }
3825
Robert Wilhelmcafda822013-08-22 09:20:03 +00003826 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003827 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003828 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003829
Aaron Ballman8aee642902015-04-08 00:05:29 +00003830 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003831 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003832 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003833
Aaron Ballman8aee642902015-04-08 00:05:29 +00003834 // Diagnose when the handler is a catch-all handler, but it isn't the last
3835 // handler for the try block. [except.handle]p5. Also, skip exception
3836 // declarations that are invalid, since we can't usefully report on them.
3837 if (!H->getExceptionDecl()) {
3838 if (i < NumHandlers - 1)
3839 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003840 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003841 } else if (H->getExceptionDecl()->isInvalidDecl())
3842 continue;
3843
3844 // Walk the type hierarchy to diagnose when this type has already been
3845 // handled (duplication), or cannot be handled (derivation inversion). We
3846 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003847 CatchHandlerType HandlerCHT =
3848 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003849
3850 // We can ignore whether the type is a reference or a pointer; we need the
3851 // underlying declaration type in order to get at the underlying record
3852 // decl, if there is one.
3853 QualType Underlying = HandlerCHT.underlying();
3854 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3855 if (!RD->hasDefinition())
3856 continue;
3857 // Check that none of the public, unambiguous base classes are in the
3858 // map ([except.handle]p1). Give the base classes the same pointer
3859 // qualification as the original type we are basing off of. This allows
3860 // comparison against the handler type using the same top-level pointer
3861 // as the original type.
3862 CXXBasePaths Paths;
3863 Paths.setOrigin(RD);
3864 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003865 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003866 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3867 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3868 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3869 diag::warn_exception_caught_by_earlier_handler)
3870 << H->getCaughtType();
3871 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3872 diag::note_previous_exception_handler)
3873 << Problem->getCaughtType();
3874 }
3875 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003876 }
Mike Stump11289f42009-09-09 15:08:12 +00003877
Aaron Ballman8aee642902015-04-08 00:05:29 +00003878 // Add the type the list of ones we have handled; diagnose if we've already
3879 // handled it.
3880 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3881 if (!R.second) {
3882 const CXXCatchStmt *Problem = R.first->second;
3883 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3884 diag::warn_exception_caught_by_earlier_handler)
3885 << H->getCaughtType();
3886 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3887 diag::note_previous_exception_handler)
3888 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003889 }
3890 }
Mike Stump11289f42009-09-09 15:08:12 +00003891
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003892 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003893
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003894 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003895}
John Wiegley1c0675e2011-04-28 01:08:34 +00003896
Reid Klecknere7175912015-02-02 22:15:31 +00003897StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3898 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003899 assert(TryBlock && Handler);
3900
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003901 sema::FunctionScopeInfo *FSI = getCurFunction();
3902
Reid Klecknere7175912015-02-02 22:15:31 +00003903 // SEH __try is incompatible with C++ try. Borland appears to support this,
3904 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003905 if (!getLangOpts().Borland) {
3906 if (FSI->FirstCXXTryLoc.isValid()) {
3907 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3908 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3909 }
Reid Klecknere7175912015-02-02 22:15:31 +00003910 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003911
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003912 FSI->setHasSEHTry(TryLoc);
3913
3914 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3915 // track if they use SEH.
3916 DeclContext *DC = CurContext;
3917 while (DC && !DC->isFunctionOrMethod())
3918 DC = DC->getParent();
3919 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3920 if (FD)
3921 FD->setUsesSEHTry(true);
3922 else
3923 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003924
Reid Kleckner8819a402015-07-10 00:16:25 +00003925 // Reject __try on unsupported targets.
3926 if (!Context.getTargetInfo().isSEHTrySupported())
3927 Diag(TryLoc, diag::err_seh_try_unsupported);
3928
Reid Klecknere7175912015-02-02 22:15:31 +00003929 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003930}
3931
3932StmtResult
3933Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3934 Expr *FilterExpr,
3935 Stmt *Block) {
3936 assert(FilterExpr && Block);
3937
3938 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003939 return StmtError(Diag(FilterExpr->getExprLoc(),
3940 diag::err_filter_expression_integral)
3941 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003942 }
3943
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003944 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003945}
3946
Nico Weberd64657f2015-03-09 02:47:59 +00003947void Sema::ActOnStartSEHFinallyBlock() {
3948 CurrentSEHFinally.push_back(CurScope);
3949}
3950
Nico Weberce903292015-03-09 03:17:15 +00003951void Sema::ActOnAbortSEHFinallyBlock() {
3952 CurrentSEHFinally.pop_back();
3953}
3954
Nico Weberd64657f2015-03-09 02:47:59 +00003955StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003956 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003957 CurrentSEHFinally.pop_back();
3958 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003959}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003960
Nico Weberc7d05962014-07-06 22:32:59 +00003961StmtResult
3962Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003963 Scope *SEHTryParent = CurScope;
3964 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3965 SEHTryParent = SEHTryParent->getParent();
3966 if (!SEHTryParent)
3967 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003968 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003969
Nico Weber9b982072014-07-07 00:12:30 +00003970 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003971}
3972
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003973StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3974 bool IsIfExists,
3975 NestedNameSpecifierLoc QualifierLoc,
3976 DeclarationNameInfo NameInfo,
3977 Stmt *Nested)
3978{
3979 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003980 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003981 cast<CompoundStmt>(Nested));
3982}
3983
3984
Chad Rosier02a84392012-08-10 17:56:09 +00003985StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003986 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003987 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003988 UnqualifiedId &Name,
3989 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003990 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003991 SS.getWithLocInContext(Context),
3992 GetNameFromUnqualifiedId(Name),
3993 Nested);
3994}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003995
3996RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003997Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3998 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003999 DeclContext *DC = CurContext;
4000 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4001 DC = DC->getParent();
4002
Craig Topperc3ec1492014-05-26 06:22:03 +00004003 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004004 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004005 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4006 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004007 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004008 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004009
Alexey Bataev330de032014-10-29 12:21:55 +00004010 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004011 DC->addDecl(RD);
4012 RD->setImplicit();
4013 RD->startDefinition();
4014
Alexey Bataev9959db52014-05-06 10:08:46 +00004015 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004016 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004017 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004018 return RD;
4019}
4020
4021static void buildCapturedStmtCaptureList(
4022 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4023 SmallVectorImpl<Expr *> &CaptureInits,
4024 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
4025
4026 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
4027 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
4028
4029 if (Cap->isThisCapture()) {
4030 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
4031 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00004032 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004033 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00004034 } else if (Cap->isVLATypeCapture()) {
4035 Captures.push_back(
4036 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
4037 CaptureInits.push_back(nullptr);
4038 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004039 }
4040
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004041 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004042 Cap->isReferenceCapture()
4043 ? CapturedStmt::VCK_ByRef
4044 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004045 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00004046 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004047 }
4048}
4049
4050void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004051 CapturedRegionKind Kind,
4052 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004053 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004054 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004055
Alexey Bataev9959db52014-05-06 10:08:46 +00004056 // Build the context parameter
4057 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4058 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4059 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004060 auto *Param =
4061 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4062 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004063 DC->addDecl(Param);
4064
4065 CD->setContextParam(0, Param);
4066
4067 // Enter the capturing scope for this captured region.
4068 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4069
4070 if (CurScope)
4071 PushDeclContext(CurScope, CD);
4072 else
4073 CurContext = CD;
4074
Faisal Valid143a0c2017-04-01 21:30:49 +00004075 PushExpressionEvaluationContext(
4076 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004077}
4078
4079void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4080 CapturedRegionKind Kind,
4081 ArrayRef<CapturedParamNameType> Params) {
4082 CapturedDecl *CD = nullptr;
4083 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4084
4085 // Build the context parameter
4086 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4087 bool ContextIsFound = false;
4088 unsigned ParamNum = 0;
4089 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4090 E = Params.end();
4091 I != E; ++I, ++ParamNum) {
4092 if (I->second.isNull()) {
4093 assert(!ContextIsFound &&
4094 "null type has been found already for '__context' parameter");
4095 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4096 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004097 auto *Param =
4098 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4099 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004100 DC->addDecl(Param);
4101 CD->setContextParam(ParamNum, Param);
4102 ContextIsFound = true;
4103 } else {
4104 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004105 auto *Param =
4106 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4107 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004108 DC->addDecl(Param);
4109 CD->setParam(ParamNum, Param);
4110 }
4111 }
4112 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004113 if (!ContextIsFound) {
4114 // Add __context implicitly if it is not specified.
4115 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4116 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004117 auto *Param =
4118 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4119 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004120 DC->addDecl(Param);
4121 CD->setContextParam(ParamNum, Param);
4122 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004123 // Enter the capturing scope for this captured region.
4124 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4125
4126 if (CurScope)
4127 PushDeclContext(CurScope, CD);
4128 else
4129 CurContext = CD;
4130
Faisal Valid143a0c2017-04-01 21:30:49 +00004131 PushExpressionEvaluationContext(
4132 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004133}
4134
Wei Pan17fbf6e2013-05-04 03:59:06 +00004135void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004136 DiscardCleanupsInEvaluationContext();
4137 PopExpressionEvaluationContext();
4138
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004139 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4140 RecordDecl *Record = RSI->TheRecordDecl;
4141 Record->setInvalidDecl();
4142
Aaron Ballman62e47c42014-03-10 13:43:55 +00004143 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004144 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4145 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004146
Wei Pan17fbf6e2013-05-04 03:59:06 +00004147 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004148 PopFunctionScopeInfo();
4149}
4150
4151StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4152 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4153
4154 SmallVector<CapturedStmt::Capture, 4> Captures;
4155 SmallVector<Expr *, 4> CaptureInits;
4156 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4157
4158 CapturedDecl *CD = RSI->TheCapturedDecl;
4159 RecordDecl *RD = RSI->TheRecordDecl;
4160
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004161 CapturedStmt *Res = CapturedStmt::Create(
4162 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4163 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004164
4165 CD->setBody(Res->getCapturedStmt());
4166 RD->completeDefinition();
4167
Wei Pan17fbf6e2013-05-04 03:59:06 +00004168 DiscardCleanupsInEvaluationContext();
4169 PopExpressionEvaluationContext();
4170
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004171 PopDeclContext();
4172 PopFunctionScopeInfo();
4173
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004174 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004175}