blob: 8e8104e581b274f1b0ecf5b71e40ee0e592b9f58 [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Richard Smith945f8d32013-01-14 22:39:08 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45 if (FE.isInvalid())
46 return StmtError();
47
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
50 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000141 switch (Op->getOperator()) {
142 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000143 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000144 case OO_EqualEqual:
145 case OO_ExclaimEqual:
146 IsRelational = false;
147 break;
148 case OO_Less:
149 case OO_Greater:
150 case OO_GreaterEqual:
151 case OO_LessEqual:
152 IsRelational = true;
153 break;
154 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else {
160 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162 }
163
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthe2669392011-08-17 09:34:37 +0000169 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000174 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000175 if (IsNotEqual)
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
178 else
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
181 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000182
183 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184}
185
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
189
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000190 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000191 if (!E)
192 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000193
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
197 return;
198
Nico Weber0e631632015-10-27 19:47:40 +0000199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000210 SourceLocation Loc;
211 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000213 return;
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattner6dc7e572012-08-31 22:39:21 +0000215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
218 // false positive.
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
220 return;
221
Nico Weber0e631632015-10-27 19:47:40 +0000222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228 return;
229 }
230
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
233 // cases now.
234 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000236 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000239
Chandler Carruthe2669392011-08-17 09:34:37 +0000240 if (DiagnoseUnusedComparison(*this, E))
241 return;
242
Eli Friedmanc11535c2012-05-24 00:47:05 +0000243 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000245 if (E->getType()->isVoidType())
246 return;
247
Chris Lattner1a6babf2009-10-13 04:53:48 +0000248 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
251 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000252 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 return;
258 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000259 if (ShouldSuppress)
260 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000261 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263 return;
264 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000265 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 } else if (ShouldSuppress)
271 return;
272
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
276 return;
277 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000279 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000282 return;
283 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
289 else
290 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
293 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
294 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
295 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000296 }
John McCall2351cb92010-04-06 22:24:14 +0000297 // Diagnose "(void*) blah" as a typo for "(void) blah".
298 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
299 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
300 QualType T = TI->getType();
301
302 // We really do want to use the non-canonical type here.
303 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000304 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000305
306 Diag(Loc, diag::warn_unused_voidptr)
307 << FixItHint::CreateRemoval(TL.getStarLoc());
308 return;
309 }
310 }
311
Eli Friedmanc11535c2012-05-24 00:47:05 +0000312 if (E->isGLValue() && E->getType().isVolatileQualified()) {
313 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
314 return;
315 }
316
Craig Topperc3ec1492014-05-26 06:22:03 +0000317 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000318}
319
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000320void Sema::ActOnStartOfCompoundStmt() {
321 PushCompoundScope();
322}
323
324void Sema::ActOnFinishOfCompoundStmt() {
325 PopCompoundScope();
326}
327
328sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
329 return getCurFunction()->CompoundScopes.back();
330}
331
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000332StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
333 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
334 const unsigned NumElts = Elts.size();
335
Chris Lattnerd864daf2007-08-27 04:29:41 +0000336 // If we're in C89 mode, check that we don't have any decls after stmts. If
337 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 // Note that __extension__ can be around a decl.
340 unsigned i = 0;
341 // Skip over all declarations.
342 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
343 /*empty*/;
344
345 // We found the end of the list or a statement. Scan for another declstmt.
346 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
347 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000348
Chris Lattnerd864daf2007-08-27 04:29:41 +0000349 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000350 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000351 Diag(D->getLocation(), diag::ext_mixed_decls_code);
352 }
353 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000354 // Warn about unused expressions in statements.
355 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000356 // Ignore statements that are last in a statement expression.
357 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000358 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000360 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000361 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000362
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000363 // Check for suspicious empty body (null statement) in `for' and `while'
364 // statements. Don't do anything for template instantiations, this just adds
365 // noise.
366 if (NumElts != 0 && !CurrentInstantiationScope &&
367 getCurCompoundScope().HasEmptyLoopBodies) {
368 for (unsigned i = 0; i != NumElts - 1; ++i)
369 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
370 }
371
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000372 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000373}
374
John McCalldadc5752010-08-24 06:29:42 +0000375StmtResult
John McCallb268a282010-08-23 23:25:46 +0000376Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
377 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000378 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000379 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000380
John McCallaab3e412010-08-25 08:40:02 +0000381 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000382 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000383 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000384 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000385
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000386 ExprResult LHS =
387 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
388 if (!getLangOpts().CPlusPlus11)
389 return VerifyIntegerConstantExpression(E);
390 if (Expr *CondExpr =
391 getCurFunction()->SwitchStack.back()->getCond()) {
392 QualType CondType = CondExpr->getType();
393 llvm::APSInt TempVal;
394 return CheckConvertedConstantExpression(E, CondType, TempVal,
395 CCEK_CaseValue);
396 }
397 return ExprError();
398 });
399 if (LHS.isInvalid())
400 return StmtError();
401 LHSVal = LHS.get();
402
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000403 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000404 // C99 6.8.4.2p3: The expression shall be an integer constant.
405 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000406 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000407 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000408 if (!LHSVal)
409 return StmtError();
410 }
Richard Smithf8379a02012-01-18 23:55:52 +0000411
412 // GCC extension: The expression shall be an integer constant.
413
Richard Smithf4c51d92012-02-04 09:53:13 +0000414 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000415 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000416 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000417 }
418 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000419
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000420 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000421 getLangOpts().CPlusPlus11);
422 if (LHS.isInvalid())
423 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000424
Richard Smith5b555da2014-11-20 01:24:12 +0000425 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
426 getLangOpts().CPlusPlus11)
427 : ExprResult();
428 if (RHS.isInvalid())
429 return StmtError();
430
431 CaseStmt *CS = new (Context)
432 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000433 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000434 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000435}
436
Chris Lattner34a22092009-03-04 04:23:07 +0000437/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000438void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000439 DiagnoseUnusedExprResult(SubStmt);
440
Chris Lattner34a22092009-03-04 04:23:07 +0000441 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000442 CS->setSubStmt(SubStmt);
443}
444
John McCalldadc5752010-08-24 06:29:42 +0000445StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000446Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000447 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000448 DiagnoseUnusedExprResult(SubStmt);
449
John McCallaab3e412010-08-25 08:40:02 +0000450 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000451 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000452 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000453 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000454
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000455 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000456 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000458}
459
John McCalldadc5752010-08-24 06:29:42 +0000460StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000461Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
462 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000463 // If the label was multiply defined, reject it now.
464 if (TheDecl->getStmt()) {
465 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
466 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000467 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000468 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000469
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000470 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000471 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
472 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000473 if (!TheDecl->isGnuLocal()) {
474 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000475 if (!TheDecl->isMSAsmLabel()) {
476 // Don't update the location of MS ASM labels. These will result in
477 // a diagnostic, and changing the location here will mess that up.
478 TheDecl->setLocation(IdentLoc);
479 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000480 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000481 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000482}
483
Richard Smithc202b282012-04-14 00:33:13 +0000484StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000485 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000486 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000487 // Fill in the declaration and return it.
488 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000489 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000490}
491
Richard Trieufaca2d82016-02-18 23:58:40 +0000492namespace {
493class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
494 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
495 Sema &SemaRef;
496public:
497 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
498 void VisitBinaryOperator(BinaryOperator *E) {
499 if (E->getOpcode() == BO_Comma)
500 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
501 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
502 }
503};
504}
505
John McCalldadc5752010-08-24 06:29:42 +0000506StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000507Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
508 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000509 Stmt *thenStmt, SourceLocation ElseLoc,
510 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000511 if (Cond.isInvalid())
512 Cond = ConditionResult(
513 *this, nullptr,
514 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
515 Context.BoolTy, VK_RValue),
516 IfLoc),
517 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000518
Richard Smithb130fe72016-06-23 19:16:49 +0000519 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000520 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000521 CondExpr->getExprLoc()))
522 CommaVisitor(*this).Visit(CondExpr);
523
524 if (!elseStmt)
525 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
526 diag::warn_empty_if_body);
527
Richard Smitha547eb22016-07-14 00:11:03 +0000528 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
529 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000530}
531
532StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000533 Stmt *InitStmt, ConditionResult Cond,
534 Stmt *thenStmt, SourceLocation ElseLoc,
535 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000536 if (Cond.isInvalid())
537 return StmtError();
538
539 if (IsConstexpr)
540 getCurFunction()->setHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000541
542 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000543 DiagnoseUnusedExprResult(elseStmt);
544
Richard Smitha547eb22016-07-14 00:11:03 +0000545 return new (Context)
546 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
547 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000548}
Steve Naroff86272ea2007-05-29 02:14:17 +0000549
Chris Lattner67998452007-08-23 18:29:20 +0000550namespace {
551 struct CaseCompareFunctor {
552 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
553 const llvm::APSInt &RHS) {
554 return LHS.first < RHS;
555 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000556 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
557 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
558 return LHS.first < RHS.first;
559 }
Chris Lattner67998452007-08-23 18:29:20 +0000560 bool operator()(const llvm::APSInt &LHS,
561 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
562 return LHS < RHS.first;
563 }
564 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000565}
Chris Lattner67998452007-08-23 18:29:20 +0000566
Chris Lattner4b2ff022007-09-21 18:15:22 +0000567/// CmpCaseVals - Comparison predicate for sorting case values.
568///
569static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
570 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
571 if (lhs.first < rhs.first)
572 return true;
573
574 if (lhs.first == rhs.first &&
575 lhs.second->getCaseLoc().getRawEncoding()
576 < rhs.second->getCaseLoc().getRawEncoding())
577 return true;
578 return false;
579}
580
Douglas Gregorbd6839732010-02-08 22:24:16 +0000581/// CmpEnumVals - Comparison predicate for sorting enumeration values.
582///
583static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
584 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
585{
586 return lhs.first < rhs.first;
587}
588
589/// EqEnumVals - Comparison preficate for uniqing enumeration values.
590///
591static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
592 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
593{
594 return lhs.first == rhs.first;
595}
596
Chris Lattnera96d4272009-10-16 16:45:22 +0000597/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
598/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000599static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
600 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
601 expr = cleanups->getSubExpr();
602 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
603 if (impcast->getCastKind() != CK_IntegralCast) break;
604 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000605 }
606 return expr->getType();
607}
608
Richard Smith03a4aa32016-06-23 19:02:52 +0000609ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000610 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
611 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000612
Douglas Gregore2b37442012-05-04 22:38:52 +0000613 public:
614 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000615 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
616 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000617
Craig Toppere14c0f82014-03-12 04:55:44 +0000618 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
619 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000620 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
621 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000622
Craig Toppere14c0f82014-03-12 04:55:44 +0000623 SemaDiagnosticBuilder diagnoseIncomplete(
624 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000625 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
626 << T << Cond->getSourceRange();
627 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Craig Toppere14c0f82014-03-12 04:55:44 +0000629 SemaDiagnosticBuilder diagnoseExplicitConv(
630 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000631 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
632 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000633
Craig Toppere14c0f82014-03-12 04:55:44 +0000634 SemaDiagnosticBuilder noteExplicitConv(
635 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000636 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
637 << ConvTy->isEnumeralType() << ConvTy;
638 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000639
Craig Toppere14c0f82014-03-12 04:55:44 +0000640 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
641 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000642 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
643 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000644
Craig Toppere14c0f82014-03-12 04:55:44 +0000645 SemaDiagnosticBuilder noteAmbiguous(
646 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000647 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
648 << ConvTy->isEnumeralType() << ConvTy;
649 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000650
Craig Toppere14c0f82014-03-12 04:55:44 +0000651 SemaDiagnosticBuilder diagnoseConversion(
652 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000653 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000654 }
655 } SwitchDiagnoser(Cond);
656
Richard Smith03a4aa32016-06-23 19:02:52 +0000657 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000658 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000659 if (CondResult.isInvalid())
660 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
John McCall5939b162011-08-06 07:30:58 +0000662 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smith03a4aa32016-06-23 19:02:52 +0000663 return UsualUnaryConversions(CondResult.get());
664}
John McCall5939b162011-08-06 07:30:58 +0000665
Richard Smithc7a05a92016-06-29 21:17:59 +0000666StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
667 Stmt *InitStmt, ConditionResult Cond) {
Richard Smith03a4aa32016-06-23 19:02:52 +0000668 if (Cond.isInvalid())
Meador Ingef0af05c2015-06-25 22:06:40 +0000669 return StmtError();
John McCalla95172b2010-08-01 00:26:45 +0000670
John McCallaab3e412010-08-25 08:40:02 +0000671 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Richard Smitha547eb22016-07-14 00:11:03 +0000673 SwitchStmt *SS = new (Context)
674 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000675 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000676 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000677}
678
Gabor Greif16e02862010-10-01 22:05:14 +0000679static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000680 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000681 Val.setIsSigned(IsSigned);
682}
683
Richard Smith077d0832014-08-04 00:40:48 +0000684/// Check the specified case value is in range for the given unpromoted switch
685/// type.
686static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
687 unsigned UnpromotedWidth, bool UnpromotedSign) {
688 // If the case value was signed and negative and the switch expression is
689 // unsigned, don't bother to warn: this is implementation-defined behavior.
690 // FIXME: Introduce a second, default-ignored warning for this case?
691 if (UnpromotedWidth < Val.getBitWidth()) {
692 llvm::APSInt ConvVal(Val);
693 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
694 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
695 // FIXME: Use different diagnostics for overflow in conversion to promoted
696 // type versus "switch expression cannot have this value". Use proper
697 // IntRange checking rather than just looking at the unpromoted type here.
698 if (ConvVal != Val)
699 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
700 << ConvVal.toString(10);
701 }
702}
703
Alexis Hunt724f14e2014-11-28 00:53:20 +0000704typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
705
Dmitri Gribenko58683752013-12-05 22:52:07 +0000706/// Returns true if we should emit a diagnostic about this case expression not
707/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000708static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000709 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000710 const Expr *CaseExpr,
711 EnumValsTy::iterator &EI,
712 EnumValsTy::iterator &EIEnd,
713 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000714 if (const DeclRefExpr *DRE =
715 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000716 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000717 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000718 QualType EnumType = S.Context.getTypeDeclType(ED);
719 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
720 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000721 return false;
722 }
723 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000724
Richard Smith332653c2015-09-04 01:03:03 +0000725 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000726 return !S.IsValueInFlagEnum(ED, Val, false);
727 } else {
728 while (EI != EIEnd && EI->first < Val)
729 EI++;
730
731 if (EI != EIEnd && EI->first == Val)
732 return false;
733 }
734
Dmitri Gribenko58683752013-12-05 22:52:07 +0000735 return true;
736}
737
John McCalldadc5752010-08-24 06:29:42 +0000738StmtResult
John McCallb268a282010-08-23 23:25:46 +0000739Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
740 Stmt *BodyStmt) {
741 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000742 assert(SS == getCurFunction()->SwitchStack.back() &&
743 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000744
David Majnemer418ad3f2014-12-15 07:46:12 +0000745 getCurFunction()->SwitchStack.pop_back();
746
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000747 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000748 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000749
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000750 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000751 if (!CondExpr) return StmtError();
752
753 QualType CondType = CondExpr->getType();
754
John McCalld3dfbd62010-05-18 03:19:21 +0000755 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000756 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000757 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000758
Chris Lattnera96d4272009-10-16 16:45:22 +0000759 // C++ 6.4.2.p2:
760 // Integral promotions are performed (on the switch condition).
761 //
762 // A case value unrepresentable by the original switch condition
763 // type (before the promotion) doesn't make sense, even when it can
764 // be represented by the promoted type. Therefore we need to find
765 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000766 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000767 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000769 // appropriate type now, just return an error.
770 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000771 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000772
Chris Lattner4ebae652010-04-16 23:34:13 +0000773 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000774 // switch(bool_expr) {...} is often a programmer error, e.g.
775 // switch(n && mask) { ... } // Doh - should be "n & mask".
776 // One can always use an if statement instead of switch(bool_expr).
777 Diag(SwitchLoc, diag::warn_bool_switch_condition)
778 << CondExpr->getSourceRange();
779 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000780 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000781
Richard Smith077d0832014-08-04 00:40:48 +0000782 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000783 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000784 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000785 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000786 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
787 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
788
789 // Get the width and signedness that the condition might actually have, for
790 // warning purposes.
791 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
792 // type.
793 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000794 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000795 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000796 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000798 // Accumulate all of the case values in a vector so that we can sort them
799 // and detect duplicates. This vector contains the APInt for the case after
800 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000801 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000802 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000803
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000804 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000805 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
806 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000807
Craig Topperc3ec1492014-05-26 06:22:03 +0000808 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner10cb5e52007-08-23 06:23:56 +0000810 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000811
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000812 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000813 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000814
Anders Carlsson51873c22007-07-22 07:07:56 +0000815 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000816 if (TheDefaultStmt) {
817 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000818 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000819
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000820 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000821 // we'll return a valid AST. This requires recursing down the AST and
822 // finding it, not something we are set up to do right now. For now,
823 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000824 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000825 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000826 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000828 } else {
829 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattnera65e1f32008-01-16 19:17:22 +0000831 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000832
833 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
834 HasDependentValue = true;
835 break;
836 }
Mike Stump11289f42009-09-09 15:08:12 +0000837
Richard Smithf8379a02012-01-18 23:55:52 +0000838 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000839
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000840 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000841 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
842 // constant expression of the promoted type of the switch condition.
843 ExprResult ConvLo =
844 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
845 if (ConvLo.isInvalid()) {
846 CaseListIsErroneous = true;
847 continue;
848 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000849 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000850 } else {
851 // We already verified that the expression has a i-c-e value (C99
852 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000853 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000854
855 // If the LHS is not the same type as the condition, insert an implicit
856 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000857 Lo = DefaultLvalueConversion(Lo).get();
858 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000859 }
860
Richard Smith077d0832014-08-04 00:40:48 +0000861 // Check the unconverted value is within the range of possible values of
862 // the switch expression.
863 checkCaseValue(*this, Lo->getLocStart(), LoVal,
864 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
865
866 // Convert the value to the same width/sign as the condition.
867 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000868
Chris Lattnera65e1f32008-01-16 19:17:22 +0000869 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000870
Chris Lattner10cb5e52007-08-23 06:23:56 +0000871 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000872 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000873 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000874 CS->getRHS()->isValueDependent()) {
875 HasDependentValue = true;
876 break;
877 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000878 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000879 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000880 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000881 }
882 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000883
884 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000885 // If we don't have a default statement, check whether the
886 // condition is constant.
887 llvm::APSInt ConstantCondValue;
888 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000889 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000890 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
891 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000892 assert(!HasConstantCond ||
893 (ConstantCondValue.getBitWidth() == CondWidth &&
894 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000895 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000896 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000897
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000898 // Sort all the scalar case values so we can easily detect duplicates.
899 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
900
901 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000902 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
903 if (ShouldCheckConstantCond &&
904 CaseVals[i].first == ConstantCondValue)
905 ShouldCheckConstantCond = false;
906
907 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000909 // First, determine if either case value has a name
910 StringRef PrevString, CurrString;
911 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
912 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
913 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
914 PrevString = DeclRef->getDecl()->getName();
915 }
916 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
917 CurrString = DeclRef->getDecl()->getName();
918 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000919 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000920 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000921
922 if (PrevString == CurrString)
923 Diag(CaseVals[i].second->getLHS()->getLocStart(),
924 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000925 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000926 else
927 Diag(CaseVals[i].second->getLHS()->getLocStart(),
928 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000929 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
930 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000931 CaseValStr;
932
John McCalld3dfbd62010-05-18 03:19:21 +0000933 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000934 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000935 // FIXME: We really want to remove the bogus case stmt from the
936 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000937 CaseListIsErroneous = true;
938 }
939 }
940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000942 // Detect duplicate case ranges, which usually don't exist at all in
943 // the first place.
944 if (!CaseRanges.empty()) {
945 // Sort all the case ranges by their low value so we can easily detect
946 // overlaps between ranges.
947 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000948
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000949 // Scan the ranges, computing the high values and removing empty ranges.
950 std::vector<llvm::APSInt> HiVals;
951 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000952 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000953 CaseStmt *CR = CaseRanges[i].second;
954 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000955 llvm::APSInt HiVal;
956
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000957 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000958 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
959 // constant expression of the promoted type of the switch condition.
960 ExprResult ConvHi =
961 CheckConvertedConstantExpression(Hi, CondType, HiVal,
962 CCEK_CaseValue);
963 if (ConvHi.isInvalid()) {
964 CaseListIsErroneous = true;
965 continue;
966 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000967 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000968 } else {
969 HiVal = Hi->EvaluateKnownConstInt(Context);
970
971 // If the RHS is not the same type as the condition, insert an
972 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000973 Hi = DefaultLvalueConversion(Hi).get();
974 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000975 }
Mike Stump11289f42009-09-09 15:08:12 +0000976
Richard Smith077d0832014-08-04 00:40:48 +0000977 // Check the unconverted value is within the range of possible values of
978 // the switch expression.
979 checkCaseValue(*this, Hi->getLocStart(), HiVal,
980 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
981
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000982 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000983 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000985 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000988 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000989 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
990 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000991 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +0000993 --i;
994 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 continue;
996 }
John McCalld3dfbd62010-05-18 03:19:21 +0000997
998 if (ShouldCheckConstantCond &&
999 LoVal <= ConstantCondValue &&
1000 ConstantCondValue <= HiVal)
1001 ShouldCheckConstantCond = false;
1002
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 HiVals.push_back(HiVal);
1004 }
Mike Stump11289f42009-09-09 15:08:12 +00001005
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001006 // Rescan the ranges, looking for overlap with singleton values and other
1007 // ranges. Since the range list is sorted, we only need to compare case
1008 // ranges with their neighbors.
1009 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1010 llvm::APSInt &CRLo = CaseRanges[i].first;
1011 llvm::APSInt &CRHi = HiVals[i];
1012 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001013
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001014 // Check to see whether the case range overlaps with any
1015 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001016 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001017 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001019 // Find the smallest value >= the lower bound. If I is in the
1020 // case range, then we have overlap.
1021 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1022 CaseVals.end(), CRLo,
1023 CaseCompareFunctor());
1024 if (I != CaseVals.end() && I->first < CRHi) {
1025 OverlapVal = I->first; // Found overlap with scalar.
1026 OverlapStmt = I->second;
1027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 // Find the smallest value bigger than the upper bound.
1030 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1031 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1032 OverlapVal = (I-1)->first; // Found overlap with scalar.
1033 OverlapStmt = (I-1)->second;
1034 }
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001036 // Check to see if this case stmt overlaps with the subsequent
1037 // case range.
1038 if (i && CRLo <= HiVals[i-1]) {
1039 OverlapVal = HiVals[i-1]; // Found overlap with range.
1040 OverlapStmt = CaseRanges[i-1].second;
1041 }
Mike Stump11289f42009-09-09 15:08:12 +00001042
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001043 if (OverlapStmt) {
1044 // If we have a duplicate, report it.
1045 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1046 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001047 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001048 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001049 // FIXME: We really want to remove the bogus case stmt from the
1050 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001051 CaseListIsErroneous = true;
1052 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001053 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001054 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001055
John McCalld3dfbd62010-05-18 03:19:21 +00001056 // Complain if we have a constant condition and we didn't find a match.
1057 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1058 // TODO: it would be nice if we printed enums as enums, chars as
1059 // chars, etc.
1060 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1061 << ConstantCondValue.toString(10)
1062 << CondExpr->getSourceRange();
1063 }
1064
1065 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001066 // values. We only issue a warning if there is not 'default:', but
1067 // we still do the analysis to preserve this information in the AST
1068 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001069 //
Chris Lattner51679082010-09-16 17:09:42 +00001070 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001071
Douglas Gregorbd6839732010-02-08 22:24:16 +00001072 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001073 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001074 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001075 EnumValsTy EnumVals;
1076
John McCalld3dfbd62010-05-18 03:19:21 +00001077 // Gather all enum values, set their type and sort them,
1078 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001079 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001080 llvm::APSInt Val = EDI->getInitVal();
1081 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001082 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001083 }
1084 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001085 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001086 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001087
1088 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001089 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001090 CI != CaseVals.end(); CI++) {
1091 Expr *CaseExpr = CI->second->getLHS();
1092 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1093 CI->first))
1094 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1095 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001096 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001097
David Blaikiee476f972012-01-22 02:31:55 +00001098 // See which of case ranges aren't in enum
1099 EI = EnumVals.begin();
1100 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001101 RI != CaseRanges.end(); RI++) {
1102 Expr *CaseExpr = RI->second->getLHS();
1103 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1104 RI->first))
1105 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1106 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001107
Chad Rosier02a84392012-08-10 17:56:09 +00001108 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001109 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1110 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001111
1112 CaseExpr = RI->second->getRHS();
1113 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1114 Hi))
1115 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1116 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118
Ted Kremenekc42f3452010-09-09 00:05:53 +00001119 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001120 auto CI = CaseVals.begin();
1121 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001122 bool hasCasesNotInSwitch = false;
1123
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001124 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125
Alexis Hunt724f14e2014-11-28 00:53:20 +00001126 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001127 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001128 while (CI != CaseVals.end() && CI->first < EI->first)
1129 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001130
Douglas Gregorbd6839732010-02-08 22:24:16 +00001131 if (CI != CaseVals.end() && CI->first == EI->first)
1132 continue;
1133
Ted Kremenekc42f3452010-09-09 00:05:53 +00001134 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001135 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001136 llvm::APSInt Hi =
1137 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001138 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001139 if (EI->first <= Hi)
1140 break;
1141 }
1142
Ted Kremenekc42f3452010-09-09 00:05:53 +00001143 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001144 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001145 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001146 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148
David Blaikie60ac6382012-01-23 04:46:12 +00001149 if (TheDefaultStmt && UnhandledNames.empty())
1150 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001151
Chris Lattner51679082010-09-16 17:09:42 +00001152 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001153 if (!UnhandledNames.empty()) {
1154 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1155 TheDefaultStmt ? diag::warn_def_missing_case
1156 : diag::warn_missing_case)
1157 << (int)UnhandledNames.size();
1158
1159 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1160 I != E; ++I)
1161 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001162 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001163
1164 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001165 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001166 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001167 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001168
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001169 if (BodyStmt)
1170 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1171 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001172
Mike Stump87c57ac2009-05-16 07:39:55 +00001173 // FIXME: If the case list was broken is some way, we don't have a good system
1174 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001175 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001176 return StmtError();
1177
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001178 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001179}
1180
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001181void
1182Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1183 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001184 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001185 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001186
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001187 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001188 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001189 SrcType->isIntegerType()) {
1190 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1191 SrcExpr->isIntegerConstantExpr(Context)) {
1192 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001193 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001194 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1195
1196 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001197 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001198 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001199
Alexis Hunt724f14e2014-11-28 00:53:20 +00001200 if (ED->hasAttr<FlagEnumAttr>()) {
1201 if (!IsValueInFlagEnum(ED, RhsVal, true))
1202 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001203 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001204 } else {
1205 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1206 EnumValsTy;
1207 EnumValsTy EnumVals;
1208
1209 // Gather all enum values, set their type and sort them,
1210 // allowing easier comparison with rhs constant.
1211 for (auto *EDI : ED->enumerators()) {
1212 llvm::APSInt Val = EDI->getInitVal();
1213 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1214 EnumVals.push_back(std::make_pair(Val, EDI));
1215 }
1216 if (EnumVals.empty())
1217 return;
1218 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1219 EnumValsTy::iterator EIend =
1220 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1221
1222 // See which values aren't in the enum.
1223 EnumValsTy::const_iterator EI = EnumVals.begin();
1224 while (EI != EIend && EI->first < RhsVal)
1225 EI++;
1226 if (EI == EIend || EI->first != RhsVal) {
1227 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1228 << DstType.getUnqualifiedType();
1229 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001230 }
1231 }
1232 }
1233}
1234
Richard Smith03a4aa32016-06-23 19:02:52 +00001235StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1236 Stmt *Body) {
1237 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001238 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001239
Richard Smith03a4aa32016-06-23 19:02:52 +00001240 auto CondVal = Cond.get();
1241 CheckBreakContinueBinding(CondVal.second);
1242
1243 if (CondVal.second &&
1244 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1245 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001246
John McCallb268a282010-08-23 23:25:46 +00001247 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001248
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001249 if (isa<NullStmt>(Body))
1250 getCurCompoundScope().setHasEmptyLoopBodies();
1251
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001252 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001253 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001254}
1255
John McCalldadc5752010-08-24 06:29:42 +00001256StmtResult
John McCallb268a282010-08-23 23:25:46 +00001257Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001258 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001259 Expr *Cond, SourceLocation CondRParen) {
1260 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001261
Serge Pavlov09f99242014-01-23 15:05:00 +00001262 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001263 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001264 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001265 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001266 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001267
Richard Smith945f8d32013-01-14 22:39:08 +00001268 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001269 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001270 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001271 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
John McCallb268a282010-08-23 23:25:46 +00001273 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001274
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001275 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001276}
1277
Richard Trieu451a5db2012-04-30 18:01:30 +00001278namespace {
1279 // This visitor will traverse a conditional statement and store all
1280 // the evaluated decls into a vector. Simple is set to true if none
1281 // of the excluded constructs are used.
1282 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001283 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001284 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001285 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001286 public:
1287 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001288
Craig Topper4dd9b432014-08-17 23:49:53 +00001289 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001290 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001291 Inherited(S.Context),
1292 Decls(Decls),
1293 Ranges(Ranges),
1294 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001295
Richard Trieu9d228802013-05-31 22:46:45 +00001296 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001297
Richard Trieu9d228802013-05-31 22:46:45 +00001298 // Replaces the method in EvaluatedExprVisitor.
1299 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001300 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001301 }
1302
1303 // Any Stmt not whitelisted will cause the condition to be marked complex.
1304 void VisitStmt(Stmt *S) {
1305 Simple = false;
1306 }
1307
1308 void VisitBinaryOperator(BinaryOperator *E) {
1309 Visit(E->getLHS());
1310 Visit(E->getRHS());
1311 }
1312
1313 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001314 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001315 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001316
Richard Trieu9d228802013-05-31 22:46:45 +00001317 void VisitUnaryOperator(UnaryOperator *E) {
1318 // Skip checking conditionals with derefernces.
1319 if (E->getOpcode() == UO_Deref)
1320 Simple = false;
1321 else
1322 Visit(E->getSubExpr());
1323 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001324
Richard Trieu9d228802013-05-31 22:46:45 +00001325 void VisitConditionalOperator(ConditionalOperator *E) {
1326 Visit(E->getCond());
1327 Visit(E->getTrueExpr());
1328 Visit(E->getFalseExpr());
1329 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Richard Trieu9d228802013-05-31 22:46:45 +00001331 void VisitParenExpr(ParenExpr *E) {
1332 Visit(E->getSubExpr());
1333 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001334
Richard Trieu9d228802013-05-31 22:46:45 +00001335 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1336 Visit(E->getOpaqueValue()->getSourceExpr());
1337 Visit(E->getFalseExpr());
1338 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001339
Richard Trieu9d228802013-05-31 22:46:45 +00001340 void VisitIntegerLiteral(IntegerLiteral *E) { }
1341 void VisitFloatingLiteral(FloatingLiteral *E) { }
1342 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1343 void VisitCharacterLiteral(CharacterLiteral *E) { }
1344 void VisitGNUNullExpr(GNUNullExpr *E) { }
1345 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
Richard Trieu9d228802013-05-31 22:46:45 +00001347 void VisitDeclRefExpr(DeclRefExpr *E) {
1348 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1349 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001350
Richard Trieu9d228802013-05-31 22:46:45 +00001351 Ranges.push_back(E->getSourceRange());
1352
1353 Decls.insert(VD);
1354 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001355
1356 }; // end class DeclExtractor
1357
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001358 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001359 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001360 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001361 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001362 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001363
Richard Trieu9d228802013-05-31 22:46:45 +00001364 public:
1365 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001366
Craig Topper4dd9b432014-08-17 23:49:53 +00001367 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001368 Stmt *Statement) :
1369 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1370 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001371
Richard Trieu9d228802013-05-31 22:46:45 +00001372 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001373 }
1374
Richard Trieu9d228802013-05-31 22:46:45 +00001375 void VisitReturnStmt(ReturnStmt *S) {
1376 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001377 }
1378
Richard Trieu9d228802013-05-31 22:46:45 +00001379 void VisitBreakStmt(BreakStmt *S) {
1380 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001381 }
1382
Richard Trieu9d228802013-05-31 22:46:45 +00001383 void VisitGotoStmt(GotoStmt *S) {
1384 FoundDecl = true;
1385 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001386
Richard Trieu9d228802013-05-31 22:46:45 +00001387 void VisitCastExpr(CastExpr *E) {
1388 if (E->getCastKind() == CK_LValueToRValue)
1389 CheckLValueToRValueCast(E->getSubExpr());
1390 else
1391 Visit(E->getSubExpr());
1392 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001393
Richard Trieu9d228802013-05-31 22:46:45 +00001394 void CheckLValueToRValueCast(Expr *E) {
1395 E = E->IgnoreParenImpCasts();
1396
1397 if (isa<DeclRefExpr>(E)) {
1398 return;
1399 }
1400
1401 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1402 Visit(CO->getCond());
1403 CheckLValueToRValueCast(CO->getTrueExpr());
1404 CheckLValueToRValueCast(CO->getFalseExpr());
1405 return;
1406 }
1407
1408 if (BinaryConditionalOperator *BCO =
1409 dyn_cast<BinaryConditionalOperator>(E)) {
1410 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1411 CheckLValueToRValueCast(BCO->getFalseExpr());
1412 return;
1413 }
1414
1415 Visit(E);
1416 }
1417
1418 void VisitDeclRefExpr(DeclRefExpr *E) {
1419 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1420 if (Decls.count(VD))
1421 FoundDecl = true;
1422 }
1423
Steven Wu92910f62016-03-10 02:02:48 +00001424 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1425 // Only need to visit the semantics for POE.
1426 // SyntaticForm doesn't really use the Decal.
1427 for (auto *S : POE->semantics()) {
1428 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1429 // Look past the OVE into the expression it binds.
1430 Visit(OVE->getSourceExpr());
1431 else
1432 Visit(S);
1433 }
1434 }
1435
Richard Trieu9d228802013-05-31 22:46:45 +00001436 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001437
1438 }; // end class DeclMatcher
1439
1440 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1441 Expr *Third, Stmt *Body) {
1442 // Condition is empty
1443 if (!Second) return;
1444
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001445 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1446 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001447 return;
1448
1449 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1450 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001451 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001452 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001453 DE.Visit(Second);
1454
1455 // Don't analyze complex conditionals.
1456 if (!DE.isSimple()) return;
1457
1458 // No decls found.
1459 if (Decls.size() == 0) return;
1460
Richard Trieu0030f1d2012-05-04 03:01:54 +00001461 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001462 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1463 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001464 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001465 if ((*I)->getType().isVolatileQualified() ||
1466 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001467
1468 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1469 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1470 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1471 return;
1472
1473 // Load decl names into diagnostic.
1474 if (Decls.size() > 4)
1475 PDiag << 0;
1476 else {
1477 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001478 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1479 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001480 I != E; ++I)
1481 PDiag << (*I)->getDeclName();
1482 }
1483
1484 // Load SourceRanges into diagnostic if there is room.
1485 // Otherwise, load the SourceRange of the conditional expression.
1486 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001487 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001488 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001489 I != E; ++I)
1490 PDiag << *I;
1491 else
1492 PDiag << Second->getSourceRange();
1493
1494 S.Diag(Ranges.begin()->getBegin(), PDiag);
1495 }
1496
Richard Trieu4e7c9622013-08-06 21:31:54 +00001497 // If Statement is an incemement or decrement, return true and sets the
1498 // variables Increment and DRE.
1499 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1500 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001501 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1502 if (!Cleanups->cleanupsHaveSideEffects())
1503 Statement = Cleanups->getSubExpr();
1504
Richard Trieu4e7c9622013-08-06 21:31:54 +00001505 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1506 switch (UO->getOpcode()) {
1507 default: return false;
1508 case UO_PostInc:
1509 case UO_PreInc:
1510 Increment = true;
1511 break;
1512 case UO_PostDec:
1513 case UO_PreDec:
1514 Increment = false;
1515 break;
1516 }
1517 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1518 return DRE;
1519 }
1520
1521 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1522 FunctionDecl *FD = Call->getDirectCallee();
1523 if (!FD || !FD->isOverloadedOperator()) return false;
1524 switch (FD->getOverloadedOperator()) {
1525 default: return false;
1526 case OO_PlusPlus:
1527 Increment = true;
1528 break;
1529 case OO_MinusMinus:
1530 Increment = false;
1531 break;
1532 }
1533 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1534 return DRE;
1535 }
1536
1537 return false;
1538 }
1539
Serge Pavlov09f99242014-01-23 15:05:00 +00001540 // A visitor to determine if a continue or break statement is a
1541 // subexpression.
1542 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1543 SourceLocation BreakLoc;
1544 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001545 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001546 BreakContinueFinder(Sema &S, Stmt* Body) :
1547 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001548 Visit(Body);
1549 }
1550
Serge Pavlov09f99242014-01-23 15:05:00 +00001551 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001552
1553 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001554 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001555 }
1556
Serge Pavlov09f99242014-01-23 15:05:00 +00001557 void VisitBreakStmt(BreakStmt* E) {
1558 BreakLoc = E->getBreakLoc();
1559 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001560
Serge Pavlov09f99242014-01-23 15:05:00 +00001561 bool ContinueFound() { return ContinueLoc.isValid(); }
1562 bool BreakFound() { return BreakLoc.isValid(); }
1563 SourceLocation GetContinueLoc() { return ContinueLoc; }
1564 SourceLocation GetBreakLoc() { return BreakLoc; }
1565
1566 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001567
1568 // Emit a warning when a loop increment/decrement appears twice per loop
1569 // iteration. The conditions which trigger this warning are:
1570 // 1) The last statement in the loop body and the third expression in the
1571 // for loop are both increment or both decrement of the same variable
1572 // 2) No continue statements in the loop body.
1573 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1574 // Return when there is nothing to check.
1575 if (!Body || !Third) return;
1576
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001577 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1578 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001579 return;
1580
1581 // Get the last statement from the loop body.
1582 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1583 if (!CS || CS->body_empty()) return;
1584 Stmt *LastStmt = CS->body_back();
1585 if (!LastStmt) return;
1586
1587 bool LoopIncrement, LastIncrement;
1588 DeclRefExpr *LoopDRE, *LastDRE;
1589
1590 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1591 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1592
1593 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001594 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001595 if (LoopIncrement != LastIncrement ||
1596 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1597
Serge Pavlov09f99242014-01-23 15:05:00 +00001598 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001599
1600 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1601 << LastDRE->getDecl() << LastIncrement;
1602 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1603 << LoopIncrement;
1604 }
1605
Richard Trieu451a5db2012-04-30 18:01:30 +00001606} // end namespace
1607
Serge Pavlov09f99242014-01-23 15:05:00 +00001608
1609void Sema::CheckBreakContinueBinding(Expr *E) {
1610 if (!E || getLangOpts().CPlusPlus)
1611 return;
1612 BreakContinueFinder BCFinder(*this, E);
1613 Scope *BreakParent = CurScope->getBreakParent();
1614 if (BCFinder.BreakFound() && BreakParent) {
1615 if (BreakParent->getFlags() & Scope::SwitchScope) {
1616 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1617 } else {
1618 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1619 << "break";
1620 }
1621 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1622 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1623 << "continue";
1624 }
1625}
1626
Richard Smith03a4aa32016-06-23 19:02:52 +00001627StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1628 Stmt *First, ConditionResult Second,
1629 FullExprArg third, SourceLocation RParenLoc,
1630 Stmt *Body) {
1631 if (Second.isInvalid())
1632 return StmtError();
1633
David Blaikiebbafb8a2012-03-11 07:00:24 +00001634 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001635 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001636 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1637 // declare identifiers for objects having storage class 'auto' or
1638 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001639 for (auto *DI : DS->decls()) {
1640 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001641 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001642 VD = nullptr;
1643 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001644 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1645 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001646 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001647 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001648 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001649 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001650
Richard Smith03a4aa32016-06-23 19:02:52 +00001651 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001652 CheckBreakContinueBinding(third.get());
1653
Richard Smith03a4aa32016-06-23 19:02:52 +00001654 if (!Second.get().first)
1655 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1656 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001657 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001658
Richard Smith03a4aa32016-06-23 19:02:52 +00001659 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001660 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001661 Second.get().second->getExprLoc()))
1662 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001663
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001664 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
Anders Carlsson1682af52009-08-01 01:39:59 +00001666 DiagnoseUnusedExprResult(First);
1667 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001668 DiagnoseUnusedExprResult(Body);
1669
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001670 if (isa<NullStmt>(Body))
1671 getCurCompoundScope().setHasEmptyLoopBodies();
1672
Richard Smith03a4aa32016-06-23 19:02:52 +00001673 return new (Context)
1674 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1675 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001676}
1677
John McCall34376a62010-12-04 03:47:34 +00001678/// In an Objective C collection iteration statement:
1679/// for (x in y)
1680/// x can be an arbitrary l-value expression. Bind it up as a
1681/// full-expression.
1682StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001683 // Reduce placeholder expressions here. Note that this rejects the
1684 // use of pseudo-object l-values in this position.
1685 ExprResult result = CheckPlaceholderExpr(E);
1686 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001687 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001688
Richard Smith945f8d32013-01-14 22:39:08 +00001689 ExprResult FullExpr = ActOnFinishFullExpr(E);
1690 if (FullExpr.isInvalid())
1691 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001692 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001693}
1694
John McCall53848232011-07-27 01:07:15 +00001695ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001696Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1697 if (!collection)
1698 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001699
Kaelyn Takata15867822014-11-21 18:48:04 +00001700 ExprResult result = CorrectDelayedTyposInExpr(collection);
1701 if (!result.isUsable())
1702 return ExprError();
1703 collection = result.get();
1704
John McCall53848232011-07-27 01:07:15 +00001705 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001706 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001707
1708 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001709 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001710 if (result.isInvalid())
1711 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001712 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001713
1714 // The operand needs to have object-pointer type.
1715 // TODO: should we do a contextual conversion?
1716 const ObjCObjectPointerType *pointerType =
1717 collection->getType()->getAs<ObjCObjectPointerType>();
1718 if (!pointerType)
1719 return Diag(forLoc, diag::err_collection_expr_type)
1720 << collection->getType() << collection->getSourceRange();
1721
1722 // Check that the operand provides
1723 // - countByEnumeratingWithState:objects:count:
1724 const ObjCObjectType *objectType = pointerType->getObjectType();
1725 ObjCInterfaceDecl *iface = objectType->getInterface();
1726
1727 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001728 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001729 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001730 (getLangOpts().ObjCAutoRefCount
1731 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1732 diag::err_arc_collection_forward, collection)
1733 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001734 // Otherwise, if we have any useful type information, check that
1735 // the type declares the appropriate method.
1736 } else if (iface || !objectType->qual_empty()) {
1737 IdentifierInfo *selectorIdents[] = {
1738 &Context.Idents.get("countByEnumeratingWithState"),
1739 &Context.Idents.get("objects"),
1740 &Context.Idents.get("count")
1741 };
1742 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1743
Craig Topperc3ec1492014-05-26 06:22:03 +00001744 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001745
1746 // If there's an interface, look in both the public and private APIs.
1747 if (iface) {
1748 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001749 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001750 }
1751
1752 // Also check protocol qualifiers.
1753 if (!method)
1754 method = LookupMethodInQualifiedType(selector, pointerType,
1755 /*instance*/ true);
1756
1757 // If we didn't find it anywhere, give up.
1758 if (!method) {
1759 Diag(forLoc, diag::warn_collection_expr_type)
1760 << collection->getType() << selector << collection->getSourceRange();
1761 }
1762
1763 // TODO: check for an incompatible signature?
1764 }
1765
1766 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001767 return collection;
John McCall53848232011-07-27 01:07:15 +00001768}
1769
John McCalldadc5752010-08-24 06:29:42 +00001770StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001771Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001772 Stmt *First, Expr *collection,
1773 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001774
1775 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001776 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001777
Fariborz Jahanian93977672008-01-10 20:33:58 +00001778 if (First) {
1779 QualType FirstType;
1780 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001781 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001782 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1783 diag::err_toomany_element_decls));
1784
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001785 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1786 if (!D || D->isInvalidDecl())
1787 return StmtError();
1788
John McCall31168b02011-06-15 23:02:42 +00001789 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001790 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1791 // declare identifiers for objects having storage class 'auto' or
1792 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001793 if (!D->hasLocalStorage())
1794 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001795 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001796
1797 // If the type contained 'auto', deduce the 'auto' to 'id'.
1798 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001799 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1800 VK_RValue);
1801 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001802 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1803 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001804 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001805 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001806 D->setInvalidDecl();
1807 return StmtError();
1808 }
1809
Richard Smith061f1e22013-04-30 21:23:01 +00001810 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001811
1812 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001813 SourceLocation Loc =
1814 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001815 Diag(Loc, diag::warn_auto_var_is_id)
1816 << D->getDeclName();
1817 }
1818 }
1819
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001820 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001821 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001822 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001823 return StmtError(Diag(First->getLocStart(),
1824 diag::err_selector_element_not_lvalue)
1825 << First->getSourceRange());
1826
Mike Stump11289f42009-09-09 15:08:12 +00001827 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001828 if (FirstType.isConstQualified())
1829 Diag(ForLoc, diag::err_selector_element_const_type)
1830 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001831 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001832 if (!FirstType->isDependentType() &&
1833 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001834 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001835 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1836 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001837 }
Chad Rosier02a84392012-08-10 17:56:09 +00001838
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001839 if (CollectionExprResult.isInvalid())
1840 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001841
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001842 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001843 if (CollectionExprResult.isInvalid())
1844 return StmtError();
1845
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001846 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1847 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001848}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001849
Richard Smith02e85f32011-04-14 22:09:26 +00001850/// Finish building a variable declaration for a for-range statement.
1851/// \return true if an error occurs.
1852static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001853 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001854 if (Decl->getType()->isUndeducedType()) {
1855 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1856 if (!Res.isUsable()) {
1857 Decl->setInvalidDecl();
1858 return true;
1859 }
1860 Init = Res.get();
1861 }
1862
Richard Smith02e85f32011-04-14 22:09:26 +00001863 // Deduce the type for the iterator variable now rather than leaving it to
1864 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001865 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001866 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001867 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001868 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001869 SemaRef.Diag(Loc, DiagID) << Init->getType();
1870 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001871 Decl->setInvalidDecl();
1872 return true;
1873 }
Richard Smith061f1e22013-04-30 21:23:01 +00001874 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001875
John McCall31168b02011-06-15 23:02:42 +00001876 // In ARC, infer lifetime.
1877 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1878 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001879 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001880 SemaRef.inferObjCARCLifetime(Decl))
1881 Decl->setInvalidDecl();
1882
Richard Smith02e85f32011-04-14 22:09:26 +00001883 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1884 /*TypeMayContainAuto=*/false);
1885 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001886 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001887 return false;
1888}
1889
Sam Panzer0f384432012-08-21 00:52:01 +00001890namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001891// An enum to represent whether something is dealing with a call to begin()
1892// or a call to end() in a range-based for loop.
1893enum BeginEndFunction {
1894 BEF_begin,
1895 BEF_end
1896};
Sam Panzer0f384432012-08-21 00:52:01 +00001897
Richard Smith02e85f32011-04-14 22:09:26 +00001898/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001899/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001900/// nor from the diagnostics produced when analysing the implicit expressions
1901/// required in a for-range statement.
1902void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001903 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001904 CallExpr *CE = dyn_cast<CallExpr>(E);
1905 if (!CE)
1906 return;
1907 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1908 if (!D)
1909 return;
1910 SourceLocation Loc = D->getLocation();
1911
1912 std::string Description;
1913 bool IsTemplate = false;
1914 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1915 Description = SemaRef.getTemplateArgumentBindingsText(
1916 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1917 IsTemplate = true;
1918 }
1919
1920 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1921 << BEF << IsTemplate << Description << E->getType();
1922}
1923
Sam Panzer0f384432012-08-21 00:52:01 +00001924/// Build a variable declaration for a for-range statement.
1925VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1926 QualType Type, const char *Name) {
1927 DeclContext *DC = SemaRef.CurContext;
1928 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1929 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1930 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001931 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001932 Decl->setImplicit();
1933 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001934}
1935
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001936}
Richard Smith02e85f32011-04-14 22:09:26 +00001937
Fariborz Jahanian00213472012-07-06 19:04:04 +00001938static bool ObjCEnumerationCollection(Expr *Collection) {
1939 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001940 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001941}
1942
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001943/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001944///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001945/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001946/// A range-based for statement is equivalent to
1947///
1948/// {
1949/// auto && __range = range-init;
1950/// for ( auto __begin = begin-expr,
1951/// __end = end-expr;
1952/// __begin != __end;
1953/// ++__begin ) {
1954/// for-range-declaration = *__begin;
1955/// statement
1956/// }
1957/// }
1958///
1959/// The body of the loop is not available yet, since it cannot be analysed until
1960/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001961StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1962 SourceLocation CoawaitLoc, Stmt *First,
1963 SourceLocation ColonLoc, Expr *Range,
1964 SourceLocation RParenLoc,
1965 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001966 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001967 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001968
Richard Smith3249fed2013-08-21 01:40:36 +00001969 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001970 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001971
1972 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1973 assert(DS && "first part of for range not a decl stmt");
1974
1975 if (!DS->isSingleDecl()) {
1976 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1977 return StmtError();
1978 }
Richard Smith02e85f32011-04-14 22:09:26 +00001979
Richard Smith3249fed2013-08-21 01:40:36 +00001980 Decl *LoopVar = DS->getSingleDecl();
1981 if (LoopVar->isInvalidDecl() || !Range ||
1982 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1983 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001984 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001985 }
Richard Smith02e85f32011-04-14 22:09:26 +00001986
Richard Smithcfd53b42015-10-22 06:13:50 +00001987 // Coroutines: 'for co_await' implicitly co_awaits its range.
1988 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00001989 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00001990 if (Coawait.isInvalid()) return StmtError();
1991 Range = Coawait.get();
1992 }
1993
Richard Smith02e85f32011-04-14 22:09:26 +00001994 // Build auto && __range = range-init
1995 SourceLocation RangeLoc = Range->getLocStart();
1996 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1997 Context.getAutoRRefDeductType(),
1998 "__range");
1999 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002000 diag::err_for_range_deduction_failure)) {
2001 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002002 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002003 }
Richard Smith02e85f32011-04-14 22:09:26 +00002004
2005 // Claim the type doesn't contain auto: we've already done the checking.
2006 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002007 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00002008 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002009 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002010 if (RangeDecl.isInvalid()) {
2011 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002012 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002013 }
Richard Smith02e85f32011-04-14 22:09:26 +00002014
Richard Smithcfd53b42015-10-22 06:13:50 +00002015 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002016 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2017 /*Cond=*/nullptr, /*Inc=*/nullptr,
2018 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002019}
2020
2021/// \brief Create the initialization, compare, and increment steps for
2022/// the range-based for loop expression.
2023/// This function does not handle array-based for loops,
2024/// which are created in Sema::BuildCXXForRangeStmt.
2025///
2026/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2027/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2028/// CandidateSet and BEF are set and some non-success value is returned on
2029/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002030static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002031 Expr *BeginRange, Expr *EndRange,
2032 QualType RangeType,
2033 VarDecl *BeginVar,
2034 VarDecl *EndVar,
2035 SourceLocation ColonLoc,
2036 OverloadCandidateSet *CandidateSet,
2037 ExprResult *BeginExpr,
2038 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002039 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002040 DeclarationNameInfo BeginNameInfo(
2041 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2042 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2043 ColonLoc);
2044
2045 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2046 Sema::LookupMemberName);
2047 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2048
2049 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2050 // - if _RangeT is a class type, the unqualified-ids begin and end are
2051 // looked up in the scope of class _RangeT as if by class member access
2052 // lookup (3.4.5), and if either (or both) finds at least one
2053 // declaration, begin-expr and end-expr are __range.begin() and
2054 // __range.end(), respectively;
2055 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2056 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2057
2058 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2059 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002060 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002061
2062 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2063 << RangeLoc << BeginRange->getType() << *BEF;
2064 return Sema::FRS_DiagnosticIssued;
2065 }
2066 } else {
2067 // - otherwise, begin-expr and end-expr are begin(__range) and
2068 // end(__range), respectively, where begin and end are looked up with
2069 // argument-dependent lookup (3.4.2). For the purposes of this name
2070 // lookup, namespace std is an associated namespace.
2071
2072 }
2073
Richard Smith9f690bd2015-10-27 06:02:45 +00002074 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002075 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002076 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002077 BeginMemberLookup, CandidateSet,
2078 BeginRange, BeginExpr);
2079
Richard Smith9f690bd2015-10-27 06:02:45 +00002080 if (RangeStatus != Sema::FRS_Success) {
2081 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2082 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2083 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002084 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002085 }
Sam Panzer0f384432012-08-21 00:52:01 +00002086 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2087 diag::err_for_range_iter_deduction_failure)) {
2088 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2089 return Sema::FRS_DiagnosticIssued;
2090 }
2091
Richard Smith9f690bd2015-10-27 06:02:45 +00002092 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002093 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002094 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002095 EndMemberLookup, CandidateSet,
2096 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002097 if (RangeStatus != Sema::FRS_Success) {
2098 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2099 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2100 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002101 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002102 }
Sam Panzer0f384432012-08-21 00:52:01 +00002103 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2104 diag::err_for_range_iter_deduction_failure)) {
2105 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2106 return Sema::FRS_DiagnosticIssued;
2107 }
2108 return Sema::FRS_Success;
2109}
2110
2111/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002112/// If the attempt fails, this function will return a valid, null StmtResult
2113/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002114static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2115 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002116 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002117 Stmt *LoopVarDecl,
2118 SourceLocation ColonLoc,
2119 Expr *Range,
2120 SourceLocation RangeLoc,
2121 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002122 // Determine whether we can rebuild the for-range statement with a
2123 // dereferenced range expression.
2124 ExprResult AdjustedRange;
2125 {
2126 Sema::SFINAETrap Trap(SemaRef);
2127
2128 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2129 if (AdjustedRange.isInvalid())
2130 return StmtResult();
2131
Richard Smith9f690bd2015-10-27 06:02:45 +00002132 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2133 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2134 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002135 if (SR.isInvalid())
2136 return StmtResult();
2137 }
2138
2139 // The attempt to dereference worked well enough that it could produce a valid
2140 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2141 // case there are any other (non-fatal) problems with it.
2142 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2143 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002144 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2145 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002146 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002147}
2148
Richard Smith3249fed2013-08-21 01:40:36 +00002149namespace {
2150/// RAII object to automatically invalidate a declaration if an error occurs.
2151struct InvalidateOnErrorScope {
2152 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2153 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2154 ~InvalidateOnErrorScope() {
2155 if (Enabled && Trap.hasErrorOccurred())
2156 D->setInvalidDecl();
2157 }
2158
2159 DiagnosticErrorTrap Trap;
2160 Decl *D;
2161 bool Enabled;
2162};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002163}
Richard Smith3249fed2013-08-21 01:40:36 +00002164
Richard Smitha05b3b52012-09-20 21:52:32 +00002165/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002166StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002167Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002168 SourceLocation ColonLoc, Stmt *RangeDecl,
2169 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002170 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002171 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002172 // FIXME: This should not be used during template instantiation. We should
2173 // pick up the set of unqualified lookup results for the != and + operators
2174 // in the initial parse.
2175 //
2176 // Testcase (accepts-invalid):
2177 // template<typename T> void f() { for (auto x : T()) {} }
2178 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2179 // bool operator!=(N::X, N::X); void operator++(N::X);
2180 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002181 Scope *S = getCurScope();
2182
2183 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2184 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2185 QualType RangeVarType = RangeVar->getType();
2186
2187 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2188 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2189
Richard Smith3249fed2013-08-21 01:40:36 +00002190 // If we hit any errors, mark the loop variable as invalid if its type
2191 // contains 'auto'.
2192 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2193 LoopVar->getType()->isUndeducedType());
2194
Richard Smith01694c32016-03-20 10:33:40 +00002195 StmtResult BeginDeclStmt = Begin;
2196 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002197 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2198
Richard Smith27d807c2013-04-30 13:56:41 +00002199 if (RangeVarType->isDependentType()) {
2200 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002201 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002202
2203 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2204 // them in properly when we instantiate the loop.
2205 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2206 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Richard Smith01694c32016-03-20 10:33:40 +00002207 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002208 SourceLocation RangeLoc = RangeVar->getLocation();
2209
Ted Kremenekbed648e2011-10-10 22:36:28 +00002210 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2211
2212 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2213 VK_LValue, ColonLoc);
2214 if (BeginRangeRef.isInvalid())
2215 return StmtError();
2216
2217 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2218 VK_LValue, ColonLoc);
2219 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002220 return StmtError();
2221
2222 QualType AutoType = Context.getAutoDeductType();
2223 Expr *Range = RangeVar->getInit();
2224 if (!Range)
2225 return StmtError();
2226 QualType RangeType = Range->getType();
2227
2228 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002229 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002230 return StmtError();
2231
2232 // Build auto __begin = begin-expr, __end = end-expr.
2233 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2234 "__begin");
2235 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2236 "__end");
2237
2238 // Build begin-expr and end-expr and attach to __begin and __end variables.
2239 ExprResult BeginExpr, EndExpr;
2240 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2241 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2242 // __range + __bound, respectively, where __bound is the array bound. If
2243 // _RangeT is an array of unknown size or an array of incomplete type,
2244 // the program is ill-formed;
2245
2246 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002247 BeginExpr = BeginRangeRef;
2248 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002249 diag::err_for_range_iter_deduction_failure)) {
2250 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2251 return StmtError();
2252 }
2253
2254 // Find the array bound.
2255 ExprResult BoundExpr;
2256 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002257 BoundExpr = IntegerLiteral::Create(
2258 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002259 else if (const VariableArrayType *VAT =
2260 dyn_cast<VariableArrayType>(UnqAT))
2261 BoundExpr = VAT->getSizeExpr();
2262 else {
2263 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2264 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002265 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002266 }
2267
2268 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002269 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002270 BoundExpr.get());
2271 if (EndExpr.isInvalid())
2272 return StmtError();
2273 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2274 diag::err_for_range_iter_deduction_failure)) {
2275 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2276 return StmtError();
2277 }
2278 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002279 OverloadCandidateSet CandidateSet(RangeLoc,
2280 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002281 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002282 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002283 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002284 EndRangeRef.get(), RangeType,
2285 BeginVar, EndVar, ColonLoc, &CandidateSet,
2286 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002287
Richard Smitha05b3b52012-09-20 21:52:32 +00002288 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002289 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002290 // If the range is being built from an array parameter, emit a
2291 // a diagnostic that it is being treated as a pointer.
2292 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2293 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2294 QualType ArrayTy = PVD->getOriginalType();
2295 QualType PointerTy = PVD->getType();
2296 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2297 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2298 << RangeLoc << PVD << ArrayTy << PointerTy;
2299 Diag(PVD->getLocation(), diag::note_declared_at);
2300 return StmtError();
2301 }
2302 }
2303 }
2304
2305 // If building the range failed, try dereferencing the range expression
2306 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002307 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002308 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002309 LoopVarDecl, ColonLoc,
2310 Range, RangeLoc,
2311 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002312 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002313 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002314 }
2315
Sam Panzer0f384432012-08-21 00:52:01 +00002316 // Otherwise, emit diagnostics if we haven't already.
2317 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002318 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002319 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2320 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002321 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002322 }
2323 // Return an error if no fix was discovered.
2324 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002325 return StmtError();
2326 }
2327
Sam Panzer0f384432012-08-21 00:52:01 +00002328 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2329 "invalid range expression in for loop");
2330
2331 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002332 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002333 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2334 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002335 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2336 ? diag::warn_for_range_begin_end_types_differ
2337 : diag::ext_for_range_begin_end_types_differ)
2338 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002339 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2340 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2341 }
2342
Richard Smith01694c32016-03-20 10:33:40 +00002343 BeginDeclStmt =
2344 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2345 EndDeclStmt =
2346 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002347
Ted Kremenekbed648e2011-10-10 22:36:28 +00002348 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2349 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002350 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002351 if (BeginRef.isInvalid())
2352 return StmtError();
2353
Richard Smith02e85f32011-04-14 22:09:26 +00002354 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2355 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002356 if (EndRef.isInvalid())
2357 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002358
2359 // Build and check __begin != __end expression.
2360 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2361 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002362 if (!NotEqExpr.isInvalid())
2363 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2364 if (!NotEqExpr.isInvalid())
2365 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002366 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002367 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2368 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002369 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2370 if (!Context.hasSameType(BeginType, EndType))
2371 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2372 return StmtError();
2373 }
2374
2375 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002376 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2377 VK_LValue, ColonLoc);
2378 if (BeginRef.isInvalid())
2379 return StmtError();
2380
Richard Smith02e85f32011-04-14 22:09:26 +00002381 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002382 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002383 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002384 if (!IncrExpr.isInvalid())
2385 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002386 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002387 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2388 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002389 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2390 return StmtError();
2391 }
2392
2393 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002394 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2395 VK_LValue, ColonLoc);
2396 if (BeginRef.isInvalid())
2397 return StmtError();
2398
Richard Smith02e85f32011-04-14 22:09:26 +00002399 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2400 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002401 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2402 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002403 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2404 return StmtError();
2405 }
2406
Richard Smitha05b3b52012-09-20 21:52:32 +00002407 // Attach *__begin as initializer for VD. Don't touch it if we're just
2408 // trying to determine whether this would be a valid range.
2409 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002410 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2411 /*TypeMayContainAuto=*/true);
2412 if (LoopVar->isInvalidDecl())
2413 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2414 }
2415 }
2416
Richard Smitha05b3b52012-09-20 21:52:32 +00002417 // Don't bother to actually allocate the result if we're just trying to
2418 // determine whether it would be valid.
2419 if (Kind == BFRK_Check)
2420 return StmtResult();
2421
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002422 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002423 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2424 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002425 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2426 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002427}
2428
Chad Rosier02a84392012-08-10 17:56:09 +00002429/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002430/// statement.
2431StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2432 if (!S || !B)
2433 return StmtError();
2434 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002435
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002436 ForStmt->setBody(B);
2437 return S;
2438}
2439
Richard Trieu3e1d4832015-04-13 22:08:55 +00002440// Warn when the loop variable is a const reference that creates a copy.
2441// Suggest using the non-reference type for copies. If a copy can be prevented
2442// suggest the const reference type that would do so.
2443// For instance, given "for (const &Foo : Range)", suggest
2444// "for (const Foo : Range)" to denote a copy is made for the loop. If
2445// possible, also suggest "for (const &Bar : Range)" if this type prevents
2446// the copy altogether.
2447static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2448 const VarDecl *VD,
2449 QualType RangeInitType) {
2450 const Expr *InitExpr = VD->getInit();
2451 if (!InitExpr)
2452 return;
2453
2454 QualType VariableType = VD->getType();
2455
Tim Shen4a05bb82016-06-21 20:29:17 +00002456 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2457 if (!Cleanups->cleanupsHaveSideEffects())
2458 InitExpr = Cleanups->getSubExpr();
2459
Richard Trieu3e1d4832015-04-13 22:08:55 +00002460 const MaterializeTemporaryExpr *MTE =
2461 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2462
2463 // No copy made.
2464 if (!MTE)
2465 return;
2466
2467 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2468
2469 // Searching for either UnaryOperator for dereference of a pointer or
2470 // CXXOperatorCallExpr for handling iterators.
2471 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2472 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2473 E = CCE->getArg(0);
2474 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2475 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2476 E = ME->getBase();
2477 } else {
2478 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2479 E = MTE->GetTemporaryExpr();
2480 }
2481 E = E->IgnoreImpCasts();
2482 }
2483
2484 bool ReturnsReference = false;
2485 if (isa<UnaryOperator>(E)) {
2486 ReturnsReference = true;
2487 } else {
2488 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2489 const FunctionDecl *FD = Call->getDirectCallee();
2490 QualType ReturnType = FD->getReturnType();
2491 ReturnsReference = ReturnType->isReferenceType();
2492 }
2493
2494 if (ReturnsReference) {
2495 // Loop variable creates a temporary. Suggest either to go with
2496 // non-reference loop variable to indiciate a copy is made, or
2497 // the correct time to bind a const reference.
2498 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2499 << VD << VariableType << E->getType();
2500 QualType NonReferenceType = VariableType.getNonReferenceType();
2501 NonReferenceType.removeLocalConst();
2502 QualType NewReferenceType =
2503 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2504 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2505 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2506 } else {
2507 // The range always returns a copy, so a temporary is always created.
2508 // Suggest removing the reference from the loop variable.
2509 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2510 << VD << RangeInitType;
2511 QualType NonReferenceType = VariableType.getNonReferenceType();
2512 NonReferenceType.removeLocalConst();
2513 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2514 << NonReferenceType << VD->getSourceRange();
2515 }
2516}
2517
2518// Warns when the loop variable can be changed to a reference type to
2519// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2520// "for (const Foo &x : Range)" if this form does not make a copy.
2521static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2522 const VarDecl *VD) {
2523 const Expr *InitExpr = VD->getInit();
2524 if (!InitExpr)
2525 return;
2526
2527 QualType VariableType = VD->getType();
2528
2529 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2530 if (!CE->getConstructor()->isCopyConstructor())
2531 return;
2532 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2533 if (CE->getCastKind() != CK_LValueToRValue)
2534 return;
2535 } else {
2536 return;
2537 }
2538
2539 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2540 // should be emitted. Also, only ignore POD types with trivial copy
2541 // constructors.
2542 if (VariableType.isPODType(SemaRef.Context))
2543 return;
2544
2545 // Suggest changing from a const variable to a const reference variable
2546 // if doing so will prevent a copy.
2547 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2548 << VD << VariableType << InitExpr->getType();
2549 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2550 << SemaRef.Context.getLValueReferenceType(VariableType)
2551 << VD->getSourceRange();
2552}
2553
2554/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2555/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2556/// using "const foo x" to show that a copy is made
2557/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2558/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2559/// prevent the copy.
2560/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2561/// Suggest "const foo &x" to prevent the copy.
2562static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2563 const CXXForRangeStmt *ForStmt) {
2564 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2565 ForStmt->getLocStart()) &&
2566 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2567 ForStmt->getLocStart()) &&
2568 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2569 ForStmt->getLocStart())) {
2570 return;
2571 }
2572
2573 const VarDecl *VD = ForStmt->getLoopVariable();
2574 if (!VD)
2575 return;
2576
2577 QualType VariableType = VD->getType();
2578
2579 if (VariableType->isIncompleteType())
2580 return;
2581
2582 const Expr *InitExpr = VD->getInit();
2583 if (!InitExpr)
2584 return;
2585
2586 if (VariableType->isReferenceType()) {
2587 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2588 ForStmt->getRangeInit()->getType());
2589 } else if (VariableType.isConstQualified()) {
2590 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2591 }
2592}
2593
Richard Smith02e85f32011-04-14 22:09:26 +00002594/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2595/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2596/// body cannot be performed until after the type of the range variable is
2597/// determined.
2598StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2599 if (!S || !B)
2600 return StmtError();
2601
Fariborz Jahanian00213472012-07-06 19:04:04 +00002602 if (isa<ObjCForCollectionStmt>(S))
2603 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002604
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002605 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2606 ForStmt->setBody(B);
2607
2608 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2609 diag::warn_empty_range_based_for_body);
2610
Richard Trieu3e1d4832015-04-13 22:08:55 +00002611 DiagnoseForRangeVariableCopies(*this, ForStmt);
2612
Richard Smith02e85f32011-04-14 22:09:26 +00002613 return S;
2614}
2615
Chris Lattnercab02a62011-02-17 20:34:02 +00002616StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2617 SourceLocation LabelLoc,
2618 LabelDecl *TheDecl) {
2619 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002620 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002621 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002622}
Chris Lattner1c310502007-05-31 06:00:00 +00002623
John McCalldadc5752010-08-24 06:29:42 +00002624StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002625Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002626 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002627 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002628 if (!E->isTypeDependent()) {
2629 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002630 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002631 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002632 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002633 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2634 if (ExprRes.isInvalid())
2635 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002636 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002637 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002638 return StmtError();
2639 }
John McCalla95172b2010-08-01 00:26:45 +00002640
Richard Smith945f8d32013-01-14 22:39:08 +00002641 ExprResult ExprRes = ActOnFinishFullExpr(E);
2642 if (ExprRes.isInvalid())
2643 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002644 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002645
John McCallaab3e412010-08-25 08:40:02 +00002646 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002647
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002648 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002649}
2650
Nico Weberd64657f2015-03-09 02:47:59 +00002651static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2652 const Scope &DestScope) {
2653 if (!S.CurrentSEHFinally.empty() &&
2654 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2655 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2656 }
2657}
2658
John McCalldadc5752010-08-24 06:29:42 +00002659StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002660Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002661 Scope *S = CurScope->getContinueParent();
2662 if (!S) {
2663 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002664 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002665 }
Nico Weberd64657f2015-03-09 02:47:59 +00002666 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002667
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002668 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002669}
2670
John McCalldadc5752010-08-24 06:29:42 +00002671StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002672Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002673 Scope *S = CurScope->getBreakParent();
2674 if (!S) {
2675 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002676 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002677 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002678 if (S->isOpenMPLoopScope())
2679 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2680 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002681 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002682
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002683 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002684}
2685
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002686/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002687/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002688///
Douglas Gregor5d369002011-01-21 18:05:27 +00002689/// \param ReturnType If we're determining the copy elision candidate for
2690/// a return statement, this is the return type of the function. If we're
2691/// determining the copy elision candidate for a throw expression, this will
2692/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002693///
Douglas Gregor5d369002011-01-21 18:05:27 +00002694/// \param E The expression being returned from the function or block, or
2695/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002696///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002697/// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2698/// id-expressions that could be moved out of the function to be considered NRVO
2699/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2700/// determine whether we should try to move as part of a return or throw (which
2701/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002702///
2703/// \returns The NRVO candidate variable, if the return statement may use the
2704/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002705VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2706 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002707 if (!getLangOpts().CPlusPlus)
2708 return nullptr;
2709
2710 // - in a return statement in a function [where] ...
2711 // ... the expression is the name of a non-volatile automatic object ...
2712 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002713 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002714 return nullptr;
2715 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2716 if (!VD)
2717 return nullptr;
2718
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002719 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002720 return VD;
2721 return nullptr;
2722}
2723
2724bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002725 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002726 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002727 // - in a return statement in a function with ...
2728 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002729 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002730 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002731 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002732 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002733 // When considering moving this expression out, allow dissimilar types.
2734 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002735 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2736 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738
John McCall03318c12011-11-11 03:57:31 +00002739 // ...object (other than a function or catch-clause parameter)...
2740 if (VD->getKind() != Decl::Var &&
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002741 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002742 return false;
2743 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002744
John McCall03318c12011-11-11 03:57:31 +00002745 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002746 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002747
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002748 if (AllowParamOrMoveConstructible)
2749 return true;
2750
John McCall03318c12011-11-11 03:57:31 +00002751 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002752 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002753
2754 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002755 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002756
2757 // Variables with higher required alignment than their type's ABI
2758 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002759 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002760 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002761 return false;
John McCall03318c12011-11-11 03:57:31 +00002762
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002763 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002764}
2765
Douglas Gregor626fbed2011-01-21 21:08:57 +00002766/// \brief Perform the initialization of a potentially-movable value, which
2767/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002768///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002769/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00002770/// returned lvalues as rvalues in certain cases (to prefer move construction),
2771/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002772ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002773Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2774 const VarDecl *NRVOCandidate,
2775 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002776 Expr *Value,
2777 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002778 // C++14 [class.copy]p32:
2779 // When the criteria for elision of a copy/move operation are met, but not for
2780 // an exception-declaration, and the object to be copied is designated by an
2781 // lvalue, or when the expression in a return statement is a (possibly
2782 // parenthesized) id-expression that names an object with automatic storage
2783 // duration declared in the body or parameter-declaration-clause of the
2784 // innermost enclosing function or lambda-expression, overload resolution to
2785 // select the constructor for the copy is first performed as if the object
2786 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002787 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002788
2789 if (AllowNRVO && !NRVOCandidate)
2790 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2791
2792 if (AllowNRVO && NRVOCandidate) {
2793 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2794 CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795
Douglas Gregorf282a762011-01-21 19:38:21 +00002796 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002798 InitializationKind Kind = InitializationKind::CreateCopy(
2799 Value->getLocStart(), Value->getLocStart());
2800
2801 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002802 if (Seq) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002803 for (const InitializationSequence::Step &Step : Seq.steps()) {
2804 if (!(Step.Kind ==
2805 InitializationSequence::SK_ConstructorInitialization ||
2806 (Step.Kind == InitializationSequence::SK_UserConversion &&
2807 isa<CXXConstructorDecl>(Step.Function.Function))))
Douglas Gregorf282a762011-01-21 19:38:21 +00002808 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002810 CXXConstructorDecl *Constructor =
2811 cast<CXXConstructorDecl>(Step.Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812
Douglas Gregorf282a762011-01-21 19:38:21 +00002813 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002814 = Constructor->getParamDecl(0)->getType()
2815 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002817 // [...] If the first overload resolution fails or was not performed, or
2818 // if the type of the first parameter of the selected constructor is not
2819 // an rvalue reference to the object’s type (possibly cv-qualified),
2820 // overload resolution is performed again, considering the object as an
2821 // lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002823 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002824 NRVOCandidate->getType()))
Douglas Gregorf282a762011-01-21 19:38:21 +00002825 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826
Douglas Gregorf282a762011-01-21 19:38:21 +00002827 // Promote "AsRvalue" to the heap, since we now need this
2828 // expression node to persist.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002829 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2830 Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831
Douglas Gregorf282a762011-01-21 19:38:21 +00002832 // Complete type-checking the initialization of the return type
2833 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002834 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002835 }
2836 }
2837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838
Douglas Gregorf282a762011-01-21 19:38:21 +00002839 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002841 // (again) now with the return value expression as written.
2842 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002843 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844
Douglas Gregorf282a762011-01-21 19:38:21 +00002845 return Res;
2846}
2847
Richard Smith4db51c22013-09-25 05:02:54 +00002848/// \brief Determine whether the declared return type of the specified function
2849/// contains 'auto'.
2850static bool hasDeducedReturnType(FunctionDecl *FD) {
2851 const FunctionProtoType *FPT =
2852 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002853 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002854}
2855
Eli Friedman34b49062012-01-26 03:00:14 +00002856/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2857/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002858///
John McCalldadc5752010-08-24 06:29:42 +00002859StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002860Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2861 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002862 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002863 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002864 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002865 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00002866 bool HasDeducedReturnType =
2867 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002868
Richard Smithb130fe72016-06-23 19:16:49 +00002869 if (ExprEvalContexts.back().Context == DiscardedStatement &&
2870 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
2871 if (RetValExp) {
2872 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2873 if (ER.isInvalid())
2874 return StmtError();
2875 RetValExp = ER.get();
2876 }
2877 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2878 }
2879
2880 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00002881 // In C++1y, the return type may involve 'auto'.
2882 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2883 FunctionDecl *FD = CurLambda->CallOperator;
2884 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002885 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002886
2887 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2888 assert(AT && "lost auto type from lambda return type");
2889 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2890 FD->setInvalidDecl();
2891 return StmtError();
2892 }
Alp Toker314cc812014-01-25 16:55:45 +00002893 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002894 } else if (CurCap->HasImplicitReturnType) {
2895 // For blocks/lambdas with implicit return types, we check each return
2896 // statement individually, and deduce the common return type when the block
2897 // or lambda is completed.
2898 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002899 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002900 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2901 if (Result.isInvalid())
2902 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002903 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002904
Richard Smith5a0e50c2014-12-19 22:10:51 +00002905 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2906 // when deducing a return type for a lambda-expression (or by extension
2907 // for a block). These rules differ from the stated C++11 rules only in
2908 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002909 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002910 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002911 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002912 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002913 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002914 if (RetValExp) {
2915 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2916 // initializer list, because it is not an expression (even
2917 // though we represent it as one). We still deduce 'void'.
2918 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2919 << RetValExp->getSourceRange();
2920 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002921
Jordan Rosed39e5f12012-07-02 21:19:23 +00002922 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002923 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002924
2925 // Although we'll properly infer the type of the block once it's completed,
2926 // make sure we provide a return type now for better error recovery.
2927 if (CurCap->ReturnType.isNull())
2928 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002929 }
Eli Friedman34b49062012-01-26 03:00:14 +00002930 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002931
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002932 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002933 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2934 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2935 return StmtError();
2936 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002937 } else if (CapturedRegionScopeInfo *CurRegion =
2938 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2939 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2940 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002941 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002942 assert(CurLambda && "unknown kind of captured scope");
2943 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2944 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002945 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2946 return StmtError();
2947 }
2948 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002949
Steve Naroffc540d662008-09-03 18:15:37 +00002950 // Otherwise, verify that this result type matches the previous one. We are
2951 // pickier with blocks than for normal functions because we don't have GCC
2952 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002953 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002954 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002955 // Delay processing for now. TODO: there are lots of dependent
2956 // types we can conclusively prove aren't void.
2957 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002958 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002959 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002960 (RetValExp->isTypeDependent() ||
2961 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002962 if (!getLangOpts().CPlusPlus &&
2963 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002964 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002965 else {
2966 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002967 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002968 }
Steve Naroffc540d662008-09-03 18:15:37 +00002969 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002970 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002971 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2972 } else if (!RetValExp->isTypeDependent()) {
2973 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002974
John McCall5500ef22011-08-17 22:09:46 +00002975 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2976 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2977 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002978
John McCall5500ef22011-08-17 22:09:46 +00002979 // In C++ the return statement is handled via a copy initialization.
2980 // the C version of which boils down to CheckSingleAssignmentConstraints.
2981 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2982 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2983 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002984 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002985 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2986 FnRetType, RetValExp);
2987 if (Res.isInvalid()) {
2988 // FIXME: Cleanup temporaries here, anyway?
2989 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002990 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002991 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002992 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002993 } else {
2994 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002995 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002996
John McCall75f92b52011-08-17 21:34:14 +00002997 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002998 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2999 if (ER.isInvalid())
3000 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003001 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003002 }
John McCall5500ef22011-08-17 22:09:46 +00003003 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3004 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003005
Jordan Rosed39e5f12012-07-02 21:19:23 +00003006 // If we need to check for the named return value optimization,
3007 // or if we need to infer the return type,
3008 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003009 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003010 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003011
Richard Smith9f690bd2015-10-27 06:02:45 +00003012 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3013 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3014
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003015 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003016}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003017
Nico Weber72889432014-09-06 01:25:55 +00003018namespace {
3019/// \brief Marks all typedefs in all local classes in a type referenced.
3020///
3021/// In a function like
3022/// auto f() {
3023/// struct S { typedef int a; };
3024/// return S();
3025/// }
3026///
3027/// the local type escapes and could be referenced in some TUs but not in
3028/// others. Pretend that all local typedefs are always referenced, to not warn
3029/// on this. This isn't necessary if f has internal linkage, or the typedef
3030/// is private.
3031class LocalTypedefNameReferencer
3032 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3033public:
3034 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3035 bool VisitRecordType(const RecordType *RT);
3036private:
3037 Sema &S;
3038};
3039bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3040 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3041 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3042 R->isDependentType())
3043 return true;
3044 for (auto *TmpD : R->decls())
3045 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3046 if (T->getAccess() != AS_private || R->hasFriends())
3047 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3048 return true;
3049}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003050}
Nico Weber72889432014-09-06 01:25:55 +00003051
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003052TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003053 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003054 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3055 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003056 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003057}
3058
Richard Smith2a7d4812013-05-04 07:00:32 +00003059/// Deduce the return type for a function from a returned expression, per
3060/// C++1y [dcl.spec.auto]p6.
3061bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3062 SourceLocation ReturnLoc,
3063 Expr *&RetExpr,
3064 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003065 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003066 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003067
Richard Smithc58f38f2013-08-14 20:16:31 +00003068 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3069 // If the deduction is for a return statement and the initializer is
3070 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003071 Diag(RetExpr->getExprLoc(),
3072 getCurLambda() ? diag::err_lambda_return_init_list
3073 : diag::err_auto_fn_return_init_list)
3074 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003075 return true;
3076 }
3077
3078 if (FD->isDependentContext()) {
3079 // C++1y [dcl.spec.auto]p12:
3080 // Return type deduction [...] occurs when the definition is
3081 // instantiated even if the function body contains a return
3082 // statement with a non-type-dependent operand.
3083 assert(AT->isDeduced() && "should have deduced to dependent type");
3084 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003085 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003086
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003087 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003088 // Otherwise, [...] deduce a value for U using the rules of template
3089 // argument deduction.
3090 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3091
3092 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3093 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3094 << OrigResultType.getType() << RetExpr->getType();
3095
3096 if (DAR != DAR_Succeeded)
3097 return true;
Nico Weber72889432014-09-06 01:25:55 +00003098
3099 // If a local type is part of the returned type, mark its fields as
3100 // referenced.
3101 LocalTypedefNameReferencer Referencer(*this);
3102 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003103 } else {
3104 // In the case of a return with no operand, the initializer is considered
3105 // to be void().
3106 //
3107 // Deduction here can only succeed if the return type is exactly 'cv auto'
3108 // or 'decltype(auto)', so just check for that case directly.
3109 if (!OrigResultType.getType()->getAs<AutoType>()) {
3110 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3111 << OrigResultType.getType();
3112 return true;
3113 }
3114 // We always deduce U = void in this case.
3115 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3116 if (Deduced.isNull())
3117 return true;
3118 }
3119
3120 // If a function with a declared return type that contains a placeholder type
3121 // has multiple return statements, the return type is deduced for each return
3122 // statement. [...] if the type deduced is not the same in each deduction,
3123 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003124 QualType DeducedT = AT->getDeducedType();
3125 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003126 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003127 // It is possible that NewAT->getDeducedType() is null. When that happens,
3128 // we should not crash, instead we ignore this deduction.
3129 if (NewAT->getDeducedType().isNull())
3130 return false;
3131
Douglas Gregora602a152015-10-01 20:20:47 +00003132 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003133 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003134 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3135 NewAT->getDeducedType());
3136 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003137 const LambdaScopeInfo *LambdaSI = getCurLambda();
3138 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3139 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003140 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003141 << true /*IsLambda*/;
3142 } else {
3143 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3144 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003145 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003146 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003147 return true;
3148 }
3149 } else if (!FD->isInvalidDecl()) {
3150 // Update all declarations of the function to have the deduced return type.
3151 Context.adjustDeducedFunctionResultType(FD, Deduced);
3152 }
3153
3154 return false;
3155}
3156
John McCalldadc5752010-08-24 06:29:42 +00003157StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003158Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3159 Scope *CurScope) {
3160 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Richard Smithb130fe72016-06-23 19:16:49 +00003161 if (R.isInvalid() || ExprEvalContexts.back().Context == DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003162 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003163
3164 if (VarDecl *VD =
3165 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3166 CurScope->addNRVOCandidate(VD);
3167 } else {
3168 CurScope->setNoNRVO();
3169 }
3170
Nico Weberd64657f2015-03-09 02:47:59 +00003171 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3172
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003173 return R;
3174}
3175
3176StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003177 // Check for unexpanded parameter packs.
3178 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3179 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003180
Eli Friedman34b49062012-01-26 03:00:14 +00003181 if (isa<CapturingScopeInfo>(getCurFunction()))
3182 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003183
Chris Lattner79413952008-12-04 23:50:19 +00003184 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003185 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003186 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003187 bool isObjCMethod = false;
3188
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003189 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003190 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003191 if (FD->hasAttrs())
3192 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003193 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003194 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003195 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003196 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003197 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003198 isObjCMethod = true;
3199 if (MD->hasAttrs())
3200 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003201 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3202 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003203 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003204 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003205 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3206 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003207 }
3208 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003209 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003210
Richard Smithb130fe72016-06-23 19:16:49 +00003211 // C++1z: discarded return statements are not considered when deducing a
3212 // return type.
3213 if (ExprEvalContexts.back().Context == DiscardedStatement &&
3214 FnRetType->getContainedAutoType()) {
3215 if (RetValExp) {
3216 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3217 if (ER.isInvalid())
3218 return StmtError();
3219 RetValExp = ER.get();
3220 }
3221 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3222 }
3223
Richard Smith2a7d4812013-05-04 07:00:32 +00003224 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3225 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003226 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003227 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3228 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003229 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003230 FD->setInvalidDecl();
3231 return StmtError();
3232 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003233 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003234 }
3235 }
3236 }
3237
Richard Smithc58f38f2013-08-14 20:16:31 +00003238 bool HasDependentReturnType = FnRetType->isDependentType();
3239
Craig Topperc3ec1492014-05-26 06:22:03 +00003240 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003241 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003242 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003243 if (isa<InitListExpr>(RetValExp)) {
3244 // We simply never allow init lists as the return value of void
3245 // functions. This is compatible because this was never allowed before,
3246 // so there's no legacy code to deal with.
3247 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3248 int FunctionKind = 0;
3249 if (isa<ObjCMethodDecl>(CurDecl))
3250 FunctionKind = 1;
3251 else if (isa<CXXConstructorDecl>(CurDecl))
3252 FunctionKind = 2;
3253 else if (isa<CXXDestructorDecl>(CurDecl))
3254 FunctionKind = 3;
3255
3256 Diag(ReturnLoc, diag::err_return_init_list)
3257 << CurDecl->getDeclName() << FunctionKind
3258 << RetValExp->getSourceRange();
3259
3260 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003261 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003262 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003263 // C99 6.8.6.4p1 (ext_ since GCC warns)
3264 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003265 if (RetValExp->getType()->isVoidType()) {
3266 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3267 if (isa<CXXConstructorDecl>(CurDecl) ||
3268 isa<CXXDestructorDecl>(CurDecl))
3269 D = diag::err_ctor_dtor_returns_void;
3270 else
3271 D = diag::ext_return_has_void_expr;
3272 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003273 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003274 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003275 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003276 if (Result.isInvalid())
3277 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003278 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003279 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003280 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003281 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003282 // return of void in constructor/destructor is illegal in C++.
3283 if (D == diag::err_ctor_dtor_returns_void) {
3284 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3285 Diag(ReturnLoc, D)
3286 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3287 << RetValExp->getSourceRange();
3288 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003289 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003290 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003291 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003292 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003293
3294 int FunctionKind = 0;
3295 if (isa<ObjCMethodDecl>(CurDecl))
3296 FunctionKind = 1;
3297 else if (isa<CXXConstructorDecl>(CurDecl))
3298 FunctionKind = 2;
3299 else if (isa<CXXDestructorDecl>(CurDecl))
3300 FunctionKind = 3;
3301
Nick Lewycky1be750a2011-06-01 07:44:31 +00003302 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003303 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003304 << RetValExp->getSourceRange();
3305 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003306 }
Mike Stump11289f42009-09-09 15:08:12 +00003307
Sebastian Redleef474c2012-02-22 10:50:08 +00003308 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003309 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3310 if (ER.isInvalid())
3311 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003312 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003313 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315
Craig Topperc3ec1492014-05-26 06:22:03 +00003316 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003317 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003318 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003319
David Majnemer2887ad32014-12-13 08:12:56 +00003320 unsigned DiagID;
3321 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3322 // C++11 [stmt.return]p2
3323 DiagID = diag::err_constexpr_return_missing_expr;
3324 FD->setInvalidDecl();
3325 } else if (getLangOpts().C99) {
3326 // C99 6.8.6.4p1 (ext_ since GCC warns)
3327 DiagID = diag::ext_return_missing_expr;
3328 } else {
3329 // C90 6.6.6.4p4
3330 DiagID = diag::warn_return_missing_expr;
3331 }
3332
3333 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003334 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003335 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003336 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003337
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003338 Result = new (Context) ReturnStmt(ReturnLoc);
3339 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003340 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003341 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003342
3343 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3344
3345 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3346 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3347 // function return.
3348
3349 // In C++ the return statement is handled via a copy initialization,
3350 // the C version of which boils down to CheckSingleAssignmentConstraints.
3351 if (RetValExp)
3352 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003353 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003354 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003356 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003357 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003359 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003360 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003361 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003362 return StmtError();
3363 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003364 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003365
3366 // If we have a related result type, we need to implicitly
3367 // convert back to the formal result type. We can't pretend to
3368 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003369 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003370 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003371 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3372 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003373 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3374 if (Res.isInvalid()) {
3375 // FIXME: Clean up temporaries here anyway?
3376 return StmtError();
3377 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003378 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003379 }
3380
Artyom Skrobov9f213442014-01-24 11:10:39 +00003381 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3382 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
John McCallacf0ee52010-10-08 02:01:28 +00003385 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003386 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3387 if (ER.isInvalid())
3388 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003389 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003390 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003391 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393
3394 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003395 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003396 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003397 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003398
Richard Smith9f690bd2015-10-27 06:02:45 +00003399 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3400 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3401
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003402 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003403}
3404
John McCalldadc5752010-08-24 06:29:42 +00003405StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003406Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003407 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003408 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003409 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003410 if (Var && Var->isInvalidDecl())
3411 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003413 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003414}
3415
John McCalldadc5752010-08-24 06:29:42 +00003416StmtResult
John McCallb268a282010-08-23 23:25:46 +00003417Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003418 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003419}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003420
John McCalldadc5752010-08-24 06:29:42 +00003421StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003423 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003424 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003425 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3426
John McCallaab3e412010-08-25 08:40:02 +00003427 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003428 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003429 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3430 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003431}
3432
John McCall0bd3e402012-05-08 21:41:25 +00003433StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003434 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003435 ExprResult Result = DefaultLvalueConversion(Throw);
3436 if (Result.isInvalid())
3437 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003438
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003439 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003440 if (Result.isInvalid())
3441 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003442 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003443
Douglas Gregor2900c162010-04-22 21:44:01 +00003444 QualType ThrowType = Throw->getType();
3445 // Make sure the expression type is an ObjC pointer or "void *".
3446 if (!ThrowType->isDependentType() &&
3447 !ThrowType->isObjCObjectPointerType()) {
3448 const PointerType *PT = ThrowType->getAs<PointerType>();
3449 if (!PT || !PT->getPointeeType()->isVoidType())
3450 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3451 << Throw->getType() << Throw->getSourceRange());
3452 }
3453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003455 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003456}
3457
John McCalldadc5752010-08-24 06:29:42 +00003458StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003460 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003461 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003462 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3463
John McCallb268a282010-08-23 23:25:46 +00003464 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003465 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003466 // in the context of an @catch clause).
3467 Scope *AtCatchParent = CurScope;
3468 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3469 AtCatchParent = AtCatchParent->getParent();
3470 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003471 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472 }
John McCallb268a282010-08-23 23:25:46 +00003473 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003474}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003475
John McCalld9bb7432011-07-27 21:50:02 +00003476ExprResult
3477Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3478 ExprResult result = DefaultLvalueConversion(operand);
3479 if (result.isInvalid())
3480 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003481 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003482
3483 // Make sure the expression type is an ObjC pointer or "void *".
3484 QualType type = operand->getType();
3485 if (!type->isDependentType() &&
3486 !type->isObjCObjectPointerType()) {
3487 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003488 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3489 if (getLangOpts().CPlusPlus) {
3490 if (RequireCompleteType(atLoc, type,
3491 diag::err_incomplete_receiver_type))
3492 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3493 << type << operand->getSourceRange();
3494
3495 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3496 if (!result.isUsable())
3497 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3498 << type << operand->getSourceRange();
3499
3500 operand = result.get();
3501 } else {
3502 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3503 << type << operand->getSourceRange();
3504 }
3505 }
John McCalld9bb7432011-07-27 21:50:02 +00003506 }
3507
3508 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003509 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003510}
3511
John McCalldadc5752010-08-24 06:29:42 +00003512StmtResult
John McCallb268a282010-08-23 23:25:46 +00003513Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3514 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003515 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003516 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003517 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003518}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003519
3520/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3521/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003522StmtResult
John McCall48871652010-08-21 09:40:31 +00003523Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003524 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003525 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003526 return new (Context)
3527 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003528}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003529
John McCall31168b02011-06-15 23:02:42 +00003530StmtResult
3531Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3532 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003533 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003534}
3535
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003536namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003537class CatchHandlerType {
3538 QualType QT;
3539 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003540
Aaron Ballman8aee642902015-04-08 00:05:29 +00003541 // This is a special constructor to be used only with DenseMapInfo's
3542 // getEmptyKey() and getTombstoneKey() functions.
3543 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3544 enum Unique { ForDenseMap };
3545 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3546
Sebastian Redl63c4da02009-07-29 17:15:45 +00003547public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003548 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003549 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003550 /// level pointer and cv-qualifiers.
3551 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3552 if (QT->isPointerType())
3553 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003554
Aaron Ballman8aee642902015-04-08 00:05:29 +00003555 if (IsPointer || QT->isReferenceType())
3556 QT = QT->getPointeeType();
3557 QT = QT.getUnqualifiedType();
3558 }
3559
3560 /// Used when creating a CatchHandlerType from a base class type; pretends the
3561 /// type passed in had the pointer qualifier, does not need to get an
3562 /// unqualified type.
3563 CatchHandlerType(QualType QT, bool IsPointer)
3564 : QT(QT), IsPointer(IsPointer) {}
3565
3566 QualType underlying() const { return QT; }
3567 bool isPointer() const { return IsPointer; }
3568
3569 friend bool operator==(const CatchHandlerType &LHS,
3570 const CatchHandlerType &RHS) {
3571 // If the pointer qualification does not match, we can return early.
3572 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003573 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003574 // Otherwise, check the underlying type without cv-qualifiers.
3575 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003576 }
3577};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003578} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003579
Aaron Ballman8aee642902015-04-08 00:05:29 +00003580namespace llvm {
3581template <> struct DenseMapInfo<CatchHandlerType> {
3582 static CatchHandlerType getEmptyKey() {
3583 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3584 CatchHandlerType::ForDenseMap);
3585 }
3586
3587 static CatchHandlerType getTombstoneKey() {
3588 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3589 CatchHandlerType::ForDenseMap);
3590 }
3591
3592 static unsigned getHashValue(const CatchHandlerType &Base) {
3593 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3594 }
3595
3596 static bool isEqual(const CatchHandlerType &LHS,
3597 const CatchHandlerType &RHS) {
3598 return LHS == RHS;
3599 }
3600};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003601}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003602
3603namespace {
3604class CatchTypePublicBases {
3605 ASTContext &Ctx;
3606 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3607 const bool CheckAgainstPointer;
3608
3609 CXXCatchStmt *FoundHandler;
3610 CanQualType FoundHandlerType;
3611
3612public:
3613 CatchTypePublicBases(
3614 ASTContext &Ctx,
3615 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3616 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3617 FoundHandler(nullptr) {}
3618
3619 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3620 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3621
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003622 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003623 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003624 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003625 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003626 auto I = M.find(Check);
3627 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003628 FoundHandler = I->second;
3629 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003630 return true;
3631 }
3632 }
3633 return false;
3634 }
3635};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003636}
Dan Gohman28ade552010-07-26 21:25:24 +00003637
Sebastian Redl9b244a82008-12-22 21:35:02 +00003638/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3639/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003640StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3641 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003642 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003643 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003644 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003645 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003646
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003647 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3648 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3649
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003650 sema::FunctionScopeInfo *FSI = getCurFunction();
3651
Reid Klecknere7175912015-02-02 22:15:31 +00003652 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003653 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003654 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003655 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003656 }
3657
Robert Wilhelmcafda822013-08-22 09:20:03 +00003658 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003659 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003660 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003661
Aaron Ballman8aee642902015-04-08 00:05:29 +00003662 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003663 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003664 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003665
Aaron Ballman8aee642902015-04-08 00:05:29 +00003666 // Diagnose when the handler is a catch-all handler, but it isn't the last
3667 // handler for the try block. [except.handle]p5. Also, skip exception
3668 // declarations that are invalid, since we can't usefully report on them.
3669 if (!H->getExceptionDecl()) {
3670 if (i < NumHandlers - 1)
3671 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003672 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003673 } else if (H->getExceptionDecl()->isInvalidDecl())
3674 continue;
3675
3676 // Walk the type hierarchy to diagnose when this type has already been
3677 // handled (duplication), or cannot be handled (derivation inversion). We
3678 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003679 CatchHandlerType HandlerCHT =
3680 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003681
3682 // We can ignore whether the type is a reference or a pointer; we need the
3683 // underlying declaration type in order to get at the underlying record
3684 // decl, if there is one.
3685 QualType Underlying = HandlerCHT.underlying();
3686 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3687 if (!RD->hasDefinition())
3688 continue;
3689 // Check that none of the public, unambiguous base classes are in the
3690 // map ([except.handle]p1). Give the base classes the same pointer
3691 // qualification as the original type we are basing off of. This allows
3692 // comparison against the handler type using the same top-level pointer
3693 // as the original type.
3694 CXXBasePaths Paths;
3695 Paths.setOrigin(RD);
3696 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003697 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003698 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3699 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3700 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3701 diag::warn_exception_caught_by_earlier_handler)
3702 << H->getCaughtType();
3703 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3704 diag::note_previous_exception_handler)
3705 << Problem->getCaughtType();
3706 }
3707 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003708 }
Mike Stump11289f42009-09-09 15:08:12 +00003709
Aaron Ballman8aee642902015-04-08 00:05:29 +00003710 // Add the type the list of ones we have handled; diagnose if we've already
3711 // handled it.
3712 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3713 if (!R.second) {
3714 const CXXCatchStmt *Problem = R.first->second;
3715 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3716 diag::warn_exception_caught_by_earlier_handler)
3717 << H->getCaughtType();
3718 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3719 diag::note_previous_exception_handler)
3720 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003721 }
3722 }
Mike Stump11289f42009-09-09 15:08:12 +00003723
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003724 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003725
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003726 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003727}
John Wiegley1c0675e2011-04-28 01:08:34 +00003728
Reid Klecknere7175912015-02-02 22:15:31 +00003729StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3730 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003731 assert(TryBlock && Handler);
3732
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003733 sema::FunctionScopeInfo *FSI = getCurFunction();
3734
Reid Klecknere7175912015-02-02 22:15:31 +00003735 // SEH __try is incompatible with C++ try. Borland appears to support this,
3736 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003737 if (!getLangOpts().Borland) {
3738 if (FSI->FirstCXXTryLoc.isValid()) {
3739 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3740 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3741 }
Reid Klecknere7175912015-02-02 22:15:31 +00003742 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003743
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003744 FSI->setHasSEHTry(TryLoc);
3745
3746 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3747 // track if they use SEH.
3748 DeclContext *DC = CurContext;
3749 while (DC && !DC->isFunctionOrMethod())
3750 DC = DC->getParent();
3751 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3752 if (FD)
3753 FD->setUsesSEHTry(true);
3754 else
3755 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003756
Reid Kleckner8819a402015-07-10 00:16:25 +00003757 // Reject __try on unsupported targets.
3758 if (!Context.getTargetInfo().isSEHTrySupported())
3759 Diag(TryLoc, diag::err_seh_try_unsupported);
3760
Reid Klecknere7175912015-02-02 22:15:31 +00003761 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003762}
3763
3764StmtResult
3765Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3766 Expr *FilterExpr,
3767 Stmt *Block) {
3768 assert(FilterExpr && Block);
3769
3770 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003771 return StmtError(Diag(FilterExpr->getExprLoc(),
3772 diag::err_filter_expression_integral)
3773 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003774 }
3775
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003776 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003777}
3778
Nico Weberd64657f2015-03-09 02:47:59 +00003779void Sema::ActOnStartSEHFinallyBlock() {
3780 CurrentSEHFinally.push_back(CurScope);
3781}
3782
Nico Weberce903292015-03-09 03:17:15 +00003783void Sema::ActOnAbortSEHFinallyBlock() {
3784 CurrentSEHFinally.pop_back();
3785}
3786
Nico Weberd64657f2015-03-09 02:47:59 +00003787StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003788 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003789 CurrentSEHFinally.pop_back();
3790 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003791}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003792
Nico Weberc7d05962014-07-06 22:32:59 +00003793StmtResult
3794Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003795 Scope *SEHTryParent = CurScope;
3796 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3797 SEHTryParent = SEHTryParent->getParent();
3798 if (!SEHTryParent)
3799 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003800 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003801
Nico Weber9b982072014-07-07 00:12:30 +00003802 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003803}
3804
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003805StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3806 bool IsIfExists,
3807 NestedNameSpecifierLoc QualifierLoc,
3808 DeclarationNameInfo NameInfo,
3809 Stmt *Nested)
3810{
3811 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003812 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003813 cast<CompoundStmt>(Nested));
3814}
3815
3816
Chad Rosier02a84392012-08-10 17:56:09 +00003817StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003818 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003819 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003820 UnqualifiedId &Name,
3821 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003822 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003823 SS.getWithLocInContext(Context),
3824 GetNameFromUnqualifiedId(Name),
3825 Nested);
3826}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003827
3828RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003829Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3830 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003831 DeclContext *DC = CurContext;
3832 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3833 DC = DC->getParent();
3834
Craig Topperc3ec1492014-05-26 06:22:03 +00003835 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003836 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003837 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3838 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003839 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003840 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003841
Alexey Bataev330de032014-10-29 12:21:55 +00003842 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003843 DC->addDecl(RD);
3844 RD->setImplicit();
3845 RD->startDefinition();
3846
Alexey Bataev9959db52014-05-06 10:08:46 +00003847 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003848 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003849 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003850 return RD;
3851}
3852
3853static void buildCapturedStmtCaptureList(
3854 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3855 SmallVectorImpl<Expr *> &CaptureInits,
3856 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3857
3858 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3859 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3860
3861 if (Cap->isThisCapture()) {
3862 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3863 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003864 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003865 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003866 } else if (Cap->isVLATypeCapture()) {
3867 Captures.push_back(
3868 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3869 CaptureInits.push_back(nullptr);
3870 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003871 }
3872
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003873 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003874 Cap->isReferenceCapture()
3875 ? CapturedStmt::VCK_ByRef
3876 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003877 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003878 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003879 }
3880}
3881
3882void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003883 CapturedRegionKind Kind,
3884 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003885 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003886 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003887
Alexey Bataev9959db52014-05-06 10:08:46 +00003888 // Build the context parameter
3889 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3890 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3891 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3892 ImplicitParamDecl *Param
3893 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3894 DC->addDecl(Param);
3895
3896 CD->setContextParam(0, Param);
3897
3898 // Enter the capturing scope for this captured region.
3899 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3900
3901 if (CurScope)
3902 PushDeclContext(CurScope, CD);
3903 else
3904 CurContext = CD;
3905
3906 PushExpressionEvaluationContext(PotentiallyEvaluated);
3907}
3908
3909void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3910 CapturedRegionKind Kind,
3911 ArrayRef<CapturedParamNameType> Params) {
3912 CapturedDecl *CD = nullptr;
3913 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3914
3915 // Build the context parameter
3916 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3917 bool ContextIsFound = false;
3918 unsigned ParamNum = 0;
3919 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3920 E = Params.end();
3921 I != E; ++I, ++ParamNum) {
3922 if (I->second.isNull()) {
3923 assert(!ContextIsFound &&
3924 "null type has been found already for '__context' parameter");
3925 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3926 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3927 ImplicitParamDecl *Param
3928 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3929 DC->addDecl(Param);
3930 CD->setContextParam(ParamNum, Param);
3931 ContextIsFound = true;
3932 } else {
3933 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3934 ImplicitParamDecl *Param
3935 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3936 DC->addDecl(Param);
3937 CD->setParam(ParamNum, Param);
3938 }
3939 }
3940 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003941 if (!ContextIsFound) {
3942 // Add __context implicitly if it is not specified.
3943 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3944 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3945 ImplicitParamDecl *Param =
3946 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3947 DC->addDecl(Param);
3948 CD->setContextParam(ParamNum, Param);
3949 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003950 // Enter the capturing scope for this captured region.
3951 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3952
3953 if (CurScope)
3954 PushDeclContext(CurScope, CD);
3955 else
3956 CurContext = CD;
3957
3958 PushExpressionEvaluationContext(PotentiallyEvaluated);
3959}
3960
Wei Pan17fbf6e2013-05-04 03:59:06 +00003961void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003962 DiscardCleanupsInEvaluationContext();
3963 PopExpressionEvaluationContext();
3964
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003965 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3966 RecordDecl *Record = RSI->TheRecordDecl;
3967 Record->setInvalidDecl();
3968
Aaron Ballman62e47c42014-03-10 13:43:55 +00003969 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003970 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3971 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003972
Wei Pan17fbf6e2013-05-04 03:59:06 +00003973 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003974 PopFunctionScopeInfo();
3975}
3976
3977StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3978 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3979
3980 SmallVector<CapturedStmt::Capture, 4> Captures;
3981 SmallVector<Expr *, 4> CaptureInits;
3982 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3983
3984 CapturedDecl *CD = RSI->TheCapturedDecl;
3985 RecordDecl *RD = RSI->TheRecordDecl;
3986
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003987 CapturedStmt *Res = CapturedStmt::Create(
3988 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
3989 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003990
3991 CD->setBody(Res->getCapturedStmt());
3992 RD->completeDefinition();
3993
Wei Pan17fbf6e2013-05-04 03:59:06 +00003994 DiscardCleanupsInEvaluationContext();
3995 PopExpressionEvaluationContext();
3996
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003997 PopDeclContext();
3998 PopFunctionScopeInfo();
3999
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004000 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004001}