blob: 61ef8f3a81c78fdeea4225ccd5461149391a5615 [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 Smithc7a05a92016-06-29 21:17:59 +0000511 if (InitStmt)
512 Diag(InitStmt->getLocStart(), diag::err_init_stmt_not_supported);
513
Richard Smithb130fe72016-06-23 19:16:49 +0000514 if (Cond.isInvalid())
515 Cond = ConditionResult(
516 *this, nullptr,
517 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
518 Context.BoolTy, VK_RValue),
519 IfLoc),
520 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000521
Richard Smithb130fe72016-06-23 19:16:49 +0000522 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000523 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000524 CondExpr->getExprLoc()))
525 CommaVisitor(*this).Visit(CondExpr);
526
527 if (!elseStmt)
528 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
529 diag::warn_empty_if_body);
530
531 return BuildIfStmt(IfLoc, IsConstexpr, Cond, thenStmt, ElseLoc, elseStmt);
532}
533
534StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
535 ConditionResult Cond, Stmt *thenStmt,
536 SourceLocation ElseLoc, Stmt *elseStmt) {
537 if (Cond.isInvalid())
538 return StmtError();
539
540 if (IsConstexpr)
541 getCurFunction()->setHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000542
543 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000544 DiagnoseUnusedExprResult(elseStmt);
545
Richard Smithb130fe72016-06-23 19:16:49 +0000546 return new (Context) IfStmt(Context, IfLoc, IsConstexpr, 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
Richard Smithc7a05a92016-06-29 21:17:59 +0000671 if (InitStmt)
672 Diag(InitStmt->getLocStart(), diag::err_init_stmt_not_supported);
673
John McCallaab3e412010-08-25 08:40:02 +0000674 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Richard Smith03a4aa32016-06-23 19:02:52 +0000676 SwitchStmt *SS =
677 new (Context) SwitchStmt(Context, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000678 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000679 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000680}
681
Gabor Greif16e02862010-10-01 22:05:14 +0000682static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000683 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000684 Val.setIsSigned(IsSigned);
685}
686
Richard Smith077d0832014-08-04 00:40:48 +0000687/// Check the specified case value is in range for the given unpromoted switch
688/// type.
689static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
690 unsigned UnpromotedWidth, bool UnpromotedSign) {
691 // If the case value was signed and negative and the switch expression is
692 // unsigned, don't bother to warn: this is implementation-defined behavior.
693 // FIXME: Introduce a second, default-ignored warning for this case?
694 if (UnpromotedWidth < Val.getBitWidth()) {
695 llvm::APSInt ConvVal(Val);
696 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
697 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
698 // FIXME: Use different diagnostics for overflow in conversion to promoted
699 // type versus "switch expression cannot have this value". Use proper
700 // IntRange checking rather than just looking at the unpromoted type here.
701 if (ConvVal != Val)
702 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
703 << ConvVal.toString(10);
704 }
705}
706
Alexis Hunt724f14e2014-11-28 00:53:20 +0000707typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
708
Dmitri Gribenko58683752013-12-05 22:52:07 +0000709/// Returns true if we should emit a diagnostic about this case expression not
710/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000711static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000712 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000713 const Expr *CaseExpr,
714 EnumValsTy::iterator &EI,
715 EnumValsTy::iterator &EIEnd,
716 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000717 if (const DeclRefExpr *DRE =
718 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000719 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000720 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000721 QualType EnumType = S.Context.getTypeDeclType(ED);
722 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
723 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000724 return false;
725 }
726 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000727
Richard Smith332653c2015-09-04 01:03:03 +0000728 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000729 return !S.IsValueInFlagEnum(ED, Val, false);
730 } else {
731 while (EI != EIEnd && EI->first < Val)
732 EI++;
733
734 if (EI != EIEnd && EI->first == Val)
735 return false;
736 }
737
Dmitri Gribenko58683752013-12-05 22:52:07 +0000738 return true;
739}
740
John McCalldadc5752010-08-24 06:29:42 +0000741StmtResult
John McCallb268a282010-08-23 23:25:46 +0000742Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
743 Stmt *BodyStmt) {
744 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000745 assert(SS == getCurFunction()->SwitchStack.back() &&
746 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000747
David Majnemer418ad3f2014-12-15 07:46:12 +0000748 getCurFunction()->SwitchStack.pop_back();
749
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000750 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000751 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000752
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000753 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000754 if (!CondExpr) return StmtError();
755
756 QualType CondType = CondExpr->getType();
757
John McCalld3dfbd62010-05-18 03:19:21 +0000758 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000759 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000760 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000761
Chris Lattnera96d4272009-10-16 16:45:22 +0000762 // C++ 6.4.2.p2:
763 // Integral promotions are performed (on the switch condition).
764 //
765 // A case value unrepresentable by the original switch condition
766 // type (before the promotion) doesn't make sense, even when it can
767 // be represented by the promoted type. Therefore we need to find
768 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000769 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000770 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000772 // appropriate type now, just return an error.
773 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000774 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000775
Chris Lattner4ebae652010-04-16 23:34:13 +0000776 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000777 // switch(bool_expr) {...} is often a programmer error, e.g.
778 // switch(n && mask) { ... } // Doh - should be "n & mask".
779 // One can always use an if statement instead of switch(bool_expr).
780 Diag(SwitchLoc, diag::warn_bool_switch_condition)
781 << CondExpr->getSourceRange();
782 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000783 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000784
Richard Smith077d0832014-08-04 00:40:48 +0000785 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000786 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000787 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000788 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000789 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
790 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
791
792 // Get the width and signedness that the condition might actually have, for
793 // warning purposes.
794 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
795 // type.
796 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000797 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000798 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000799 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000800
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000801 // Accumulate all of the case values in a vector so that we can sort them
802 // and detect duplicates. This vector contains the APInt for the case after
803 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000804 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000805 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000807 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000808 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
809 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000810
Craig Topperc3ec1492014-05-26 06:22:03 +0000811 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattner10cb5e52007-08-23 06:23:56 +0000813 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000814
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000815 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000816 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000817
Anders Carlsson51873c22007-07-22 07:07:56 +0000818 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000819 if (TheDefaultStmt) {
820 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000821 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000822
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000823 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000824 // we'll return a valid AST. This requires recursing down the AST and
825 // finding it, not something we are set up to do right now. For now,
826 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000827 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000828 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000829 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000831 } else {
832 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000833
Chris Lattnera65e1f32008-01-16 19:17:22 +0000834 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000835
836 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
837 HasDependentValue = true;
838 break;
839 }
Mike Stump11289f42009-09-09 15:08:12 +0000840
Richard Smithf8379a02012-01-18 23:55:52 +0000841 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000842
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000843 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000844 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
845 // constant expression of the promoted type of the switch condition.
846 ExprResult ConvLo =
847 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
848 if (ConvLo.isInvalid()) {
849 CaseListIsErroneous = true;
850 continue;
851 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000852 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000853 } else {
854 // We already verified that the expression has a i-c-e value (C99
855 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000856 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000857
858 // If the LHS is not the same type as the condition, insert an implicit
859 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000860 Lo = DefaultLvalueConversion(Lo).get();
861 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000862 }
863
Richard Smith077d0832014-08-04 00:40:48 +0000864 // Check the unconverted value is within the range of possible values of
865 // the switch expression.
866 checkCaseValue(*this, Lo->getLocStart(), LoVal,
867 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
868
869 // Convert the value to the same width/sign as the condition.
870 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000871
Chris Lattnera65e1f32008-01-16 19:17:22 +0000872 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000873
Chris Lattner10cb5e52007-08-23 06:23:56 +0000874 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000875 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000876 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000877 CS->getRHS()->isValueDependent()) {
878 HasDependentValue = true;
879 break;
880 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000881 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000882 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000883 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000884 }
885 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000886
887 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000888 // If we don't have a default statement, check whether the
889 // condition is constant.
890 llvm::APSInt ConstantCondValue;
891 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000892 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000893 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
894 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000895 assert(!HasConstantCond ||
896 (ConstantCondValue.getBitWidth() == CondWidth &&
897 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000898 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000899 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000900
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000901 // Sort all the scalar case values so we can easily detect duplicates.
902 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
903
904 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000905 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
906 if (ShouldCheckConstantCond &&
907 CaseVals[i].first == ConstantCondValue)
908 ShouldCheckConstantCond = false;
909
910 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000911 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000912 // First, determine if either case value has a name
913 StringRef PrevString, CurrString;
914 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
915 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
916 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
917 PrevString = DeclRef->getDecl()->getName();
918 }
919 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
920 CurrString = DeclRef->getDecl()->getName();
921 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000922 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000923 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000924
925 if (PrevString == CurrString)
926 Diag(CaseVals[i].second->getLHS()->getLocStart(),
927 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000928 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000929 else
930 Diag(CaseVals[i].second->getLHS()->getLocStart(),
931 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000932 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
933 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000934 CaseValStr;
935
John McCalld3dfbd62010-05-18 03:19:21 +0000936 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000937 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000938 // FIXME: We really want to remove the bogus case stmt from the
939 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000940 CaseListIsErroneous = true;
941 }
942 }
943 }
Mike Stump11289f42009-09-09 15:08:12 +0000944
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000945 // Detect duplicate case ranges, which usually don't exist at all in
946 // the first place.
947 if (!CaseRanges.empty()) {
948 // Sort all the case ranges by their low value so we can easily detect
949 // overlaps between ranges.
950 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000951
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000952 // Scan the ranges, computing the high values and removing empty ranges.
953 std::vector<llvm::APSInt> HiVals;
954 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000955 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000956 CaseStmt *CR = CaseRanges[i].second;
957 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000958 llvm::APSInt HiVal;
959
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000960 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000961 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
962 // constant expression of the promoted type of the switch condition.
963 ExprResult ConvHi =
964 CheckConvertedConstantExpression(Hi, CondType, HiVal,
965 CCEK_CaseValue);
966 if (ConvHi.isInvalid()) {
967 CaseListIsErroneous = true;
968 continue;
969 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000970 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000971 } else {
972 HiVal = Hi->EvaluateKnownConstInt(Context);
973
974 // If the RHS is not the same type as the condition, insert an
975 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000976 Hi = DefaultLvalueConversion(Hi).get();
977 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Richard Smith077d0832014-08-04 00:40:48 +0000980 // Check the unconverted value is within the range of possible values of
981 // the switch expression.
982 checkCaseValue(*this, Hi->getLocStart(), HiVal,
983 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
984
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000985 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000986 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000987
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000988 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000990 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000991 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
993 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000994 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +0000996 --i;
997 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000998 continue;
999 }
John McCalld3dfbd62010-05-18 03:19:21 +00001000
1001 if (ShouldCheckConstantCond &&
1002 LoVal <= ConstantCondValue &&
1003 ConstantCondValue <= HiVal)
1004 ShouldCheckConstantCond = false;
1005
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001006 HiVals.push_back(HiVal);
1007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001009 // Rescan the ranges, looking for overlap with singleton values and other
1010 // ranges. Since the range list is sorted, we only need to compare case
1011 // ranges with their neighbors.
1012 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1013 llvm::APSInt &CRLo = CaseRanges[i].first;
1014 llvm::APSInt &CRHi = HiVals[i];
1015 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001016
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001017 // Check to see whether the case range overlaps with any
1018 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001019 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001020 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001021
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001022 // Find the smallest value >= the lower bound. If I is in the
1023 // case range, then we have overlap.
1024 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1025 CaseVals.end(), CRLo,
1026 CaseCompareFunctor());
1027 if (I != CaseVals.end() && I->first < CRHi) {
1028 OverlapVal = I->first; // Found overlap with scalar.
1029 OverlapStmt = I->second;
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001032 // Find the smallest value bigger than the upper bound.
1033 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1034 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1035 OverlapVal = (I-1)->first; // Found overlap with scalar.
1036 OverlapStmt = (I-1)->second;
1037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001039 // Check to see if this case stmt overlaps with the subsequent
1040 // case range.
1041 if (i && CRLo <= HiVals[i-1]) {
1042 OverlapVal = HiVals[i-1]; // Found overlap with range.
1043 OverlapStmt = CaseRanges[i-1].second;
1044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001046 if (OverlapStmt) {
1047 // If we have a duplicate, report it.
1048 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1049 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001050 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001051 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001052 // FIXME: We really want to remove the bogus case stmt from the
1053 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001054 CaseListIsErroneous = true;
1055 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001056 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001057 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001058
John McCalld3dfbd62010-05-18 03:19:21 +00001059 // Complain if we have a constant condition and we didn't find a match.
1060 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1061 // TODO: it would be nice if we printed enums as enums, chars as
1062 // chars, etc.
1063 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1064 << ConstantCondValue.toString(10)
1065 << CondExpr->getSourceRange();
1066 }
1067
1068 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001069 // values. We only issue a warning if there is not 'default:', but
1070 // we still do the analysis to preserve this information in the AST
1071 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001072 //
Chris Lattner51679082010-09-16 17:09:42 +00001073 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001074
Douglas Gregorbd6839732010-02-08 22:24:16 +00001075 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001076 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001077 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001078 EnumValsTy EnumVals;
1079
John McCalld3dfbd62010-05-18 03:19:21 +00001080 // Gather all enum values, set their type and sort them,
1081 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001082 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001083 llvm::APSInt Val = EDI->getInitVal();
1084 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001085 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001086 }
1087 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001088 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001089 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001090
1091 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001092 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001093 CI != CaseVals.end(); CI++) {
1094 Expr *CaseExpr = CI->second->getLHS();
1095 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1096 CI->first))
1097 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1098 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001099 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001100
David Blaikiee476f972012-01-22 02:31:55 +00001101 // See which of case ranges aren't in enum
1102 EI = EnumVals.begin();
1103 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001104 RI != CaseRanges.end(); RI++) {
1105 Expr *CaseExpr = RI->second->getLHS();
1106 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1107 RI->first))
1108 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1109 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001110
Chad Rosier02a84392012-08-10 17:56:09 +00001111 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001112 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1113 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001114
1115 CaseExpr = RI->second->getRHS();
1116 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1117 Hi))
1118 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1119 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
Ted Kremenekc42f3452010-09-09 00:05:53 +00001122 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001123 auto CI = CaseVals.begin();
1124 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001125 bool hasCasesNotInSwitch = false;
1126
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001127 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128
Alexis Hunt724f14e2014-11-28 00:53:20 +00001129 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001130 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001131 while (CI != CaseVals.end() && CI->first < EI->first)
1132 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001133
Douglas Gregorbd6839732010-02-08 22:24:16 +00001134 if (CI != CaseVals.end() && CI->first == EI->first)
1135 continue;
1136
Ted Kremenekc42f3452010-09-09 00:05:53 +00001137 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001138 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001139 llvm::APSInt Hi =
1140 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001141 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001142 if (EI->first <= Hi)
1143 break;
1144 }
1145
Ted Kremenekc42f3452010-09-09 00:05:53 +00001146 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001147 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001148 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001149 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
David Blaikie60ac6382012-01-23 04:46:12 +00001152 if (TheDefaultStmt && UnhandledNames.empty())
1153 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001154
Chris Lattner51679082010-09-16 17:09:42 +00001155 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001156 if (!UnhandledNames.empty()) {
1157 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1158 TheDefaultStmt ? diag::warn_def_missing_case
1159 : diag::warn_missing_case)
1160 << (int)UnhandledNames.size();
1161
1162 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1163 I != E; ++I)
1164 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001165 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001166
1167 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001168 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001169 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001170 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001171
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001172 if (BodyStmt)
1173 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1174 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001175
Mike Stump87c57ac2009-05-16 07:39:55 +00001176 // FIXME: If the case list was broken is some way, we don't have a good system
1177 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001178 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001179 return StmtError();
1180
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001181 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001182}
1183
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001184void
1185Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1186 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001187 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001188 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001189
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001190 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001191 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001192 SrcType->isIntegerType()) {
1193 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1194 SrcExpr->isIntegerConstantExpr(Context)) {
1195 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001196 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001197 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1198
1199 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001200 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001201 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001202
Alexis Hunt724f14e2014-11-28 00:53:20 +00001203 if (ED->hasAttr<FlagEnumAttr>()) {
1204 if (!IsValueInFlagEnum(ED, RhsVal, true))
1205 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001206 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001207 } else {
1208 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1209 EnumValsTy;
1210 EnumValsTy EnumVals;
1211
1212 // Gather all enum values, set their type and sort them,
1213 // allowing easier comparison with rhs constant.
1214 for (auto *EDI : ED->enumerators()) {
1215 llvm::APSInt Val = EDI->getInitVal();
1216 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1217 EnumVals.push_back(std::make_pair(Val, EDI));
1218 }
1219 if (EnumVals.empty())
1220 return;
1221 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1222 EnumValsTy::iterator EIend =
1223 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1224
1225 // See which values aren't in the enum.
1226 EnumValsTy::const_iterator EI = EnumVals.begin();
1227 while (EI != EIend && EI->first < RhsVal)
1228 EI++;
1229 if (EI == EIend || EI->first != RhsVal) {
1230 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1231 << DstType.getUnqualifiedType();
1232 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001233 }
1234 }
1235 }
1236}
1237
Richard Smith03a4aa32016-06-23 19:02:52 +00001238StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1239 Stmt *Body) {
1240 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001241 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242
Richard Smith03a4aa32016-06-23 19:02:52 +00001243 auto CondVal = Cond.get();
1244 CheckBreakContinueBinding(CondVal.second);
1245
1246 if (CondVal.second &&
1247 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1248 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001249
John McCallb268a282010-08-23 23:25:46 +00001250 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001251
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001252 if (isa<NullStmt>(Body))
1253 getCurCompoundScope().setHasEmptyLoopBodies();
1254
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001255 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001256 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001257}
1258
John McCalldadc5752010-08-24 06:29:42 +00001259StmtResult
John McCallb268a282010-08-23 23:25:46 +00001260Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001261 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001262 Expr *Cond, SourceLocation CondRParen) {
1263 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001264
Serge Pavlov09f99242014-01-23 15:05:00 +00001265 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001266 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001267 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001268 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001269 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001270
Richard Smith945f8d32013-01-14 22:39:08 +00001271 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001272 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001273 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001274 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
John McCallb268a282010-08-23 23:25:46 +00001276 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001277
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001278 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001279}
1280
Richard Trieu451a5db2012-04-30 18:01:30 +00001281namespace {
1282 // This visitor will traverse a conditional statement and store all
1283 // the evaluated decls into a vector. Simple is set to true if none
1284 // of the excluded constructs are used.
1285 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001286 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001287 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001288 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001289 public:
1290 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001291
Craig Topper4dd9b432014-08-17 23:49:53 +00001292 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001293 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001294 Inherited(S.Context),
1295 Decls(Decls),
1296 Ranges(Ranges),
1297 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001298
Richard Trieu9d228802013-05-31 22:46:45 +00001299 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001300
Richard Trieu9d228802013-05-31 22:46:45 +00001301 // Replaces the method in EvaluatedExprVisitor.
1302 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001303 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001304 }
1305
1306 // Any Stmt not whitelisted will cause the condition to be marked complex.
1307 void VisitStmt(Stmt *S) {
1308 Simple = false;
1309 }
1310
1311 void VisitBinaryOperator(BinaryOperator *E) {
1312 Visit(E->getLHS());
1313 Visit(E->getRHS());
1314 }
1315
1316 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001317 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001318 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001319
Richard Trieu9d228802013-05-31 22:46:45 +00001320 void VisitUnaryOperator(UnaryOperator *E) {
1321 // Skip checking conditionals with derefernces.
1322 if (E->getOpcode() == UO_Deref)
1323 Simple = false;
1324 else
1325 Visit(E->getSubExpr());
1326 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001327
Richard Trieu9d228802013-05-31 22:46:45 +00001328 void VisitConditionalOperator(ConditionalOperator *E) {
1329 Visit(E->getCond());
1330 Visit(E->getTrueExpr());
1331 Visit(E->getFalseExpr());
1332 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001333
Richard Trieu9d228802013-05-31 22:46:45 +00001334 void VisitParenExpr(ParenExpr *E) {
1335 Visit(E->getSubExpr());
1336 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001337
Richard Trieu9d228802013-05-31 22:46:45 +00001338 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1339 Visit(E->getOpaqueValue()->getSourceExpr());
1340 Visit(E->getFalseExpr());
1341 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 void VisitIntegerLiteral(IntegerLiteral *E) { }
1344 void VisitFloatingLiteral(FloatingLiteral *E) { }
1345 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1346 void VisitCharacterLiteral(CharacterLiteral *E) { }
1347 void VisitGNUNullExpr(GNUNullExpr *E) { }
1348 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001349
Richard Trieu9d228802013-05-31 22:46:45 +00001350 void VisitDeclRefExpr(DeclRefExpr *E) {
1351 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1352 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001353
Richard Trieu9d228802013-05-31 22:46:45 +00001354 Ranges.push_back(E->getSourceRange());
1355
1356 Decls.insert(VD);
1357 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001358
1359 }; // end class DeclExtractor
1360
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001361 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001362 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001363 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001364 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001365 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001366
Richard Trieu9d228802013-05-31 22:46:45 +00001367 public:
1368 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001369
Craig Topper4dd9b432014-08-17 23:49:53 +00001370 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001371 Stmt *Statement) :
1372 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1373 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001374
Richard Trieu9d228802013-05-31 22:46:45 +00001375 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001376 }
1377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void VisitReturnStmt(ReturnStmt *S) {
1379 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001380 }
1381
Richard Trieu9d228802013-05-31 22:46:45 +00001382 void VisitBreakStmt(BreakStmt *S) {
1383 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001384 }
1385
Richard Trieu9d228802013-05-31 22:46:45 +00001386 void VisitGotoStmt(GotoStmt *S) {
1387 FoundDecl = true;
1388 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001389
Richard Trieu9d228802013-05-31 22:46:45 +00001390 void VisitCastExpr(CastExpr *E) {
1391 if (E->getCastKind() == CK_LValueToRValue)
1392 CheckLValueToRValueCast(E->getSubExpr());
1393 else
1394 Visit(E->getSubExpr());
1395 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001396
Richard Trieu9d228802013-05-31 22:46:45 +00001397 void CheckLValueToRValueCast(Expr *E) {
1398 E = E->IgnoreParenImpCasts();
1399
1400 if (isa<DeclRefExpr>(E)) {
1401 return;
1402 }
1403
1404 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1405 Visit(CO->getCond());
1406 CheckLValueToRValueCast(CO->getTrueExpr());
1407 CheckLValueToRValueCast(CO->getFalseExpr());
1408 return;
1409 }
1410
1411 if (BinaryConditionalOperator *BCO =
1412 dyn_cast<BinaryConditionalOperator>(E)) {
1413 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1414 CheckLValueToRValueCast(BCO->getFalseExpr());
1415 return;
1416 }
1417
1418 Visit(E);
1419 }
1420
1421 void VisitDeclRefExpr(DeclRefExpr *E) {
1422 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1423 if (Decls.count(VD))
1424 FoundDecl = true;
1425 }
1426
Steven Wu92910f62016-03-10 02:02:48 +00001427 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1428 // Only need to visit the semantics for POE.
1429 // SyntaticForm doesn't really use the Decal.
1430 for (auto *S : POE->semantics()) {
1431 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1432 // Look past the OVE into the expression it binds.
1433 Visit(OVE->getSourceExpr());
1434 else
1435 Visit(S);
1436 }
1437 }
1438
Richard Trieu9d228802013-05-31 22:46:45 +00001439 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001440
1441 }; // end class DeclMatcher
1442
1443 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1444 Expr *Third, Stmt *Body) {
1445 // Condition is empty
1446 if (!Second) return;
1447
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001448 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1449 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001450 return;
1451
1452 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1453 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001454 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001455 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001456 DE.Visit(Second);
1457
1458 // Don't analyze complex conditionals.
1459 if (!DE.isSimple()) return;
1460
1461 // No decls found.
1462 if (Decls.size() == 0) return;
1463
Richard Trieu0030f1d2012-05-04 03:01:54 +00001464 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001465 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1466 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001467 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001468 if ((*I)->getType().isVolatileQualified() ||
1469 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001470
1471 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1472 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1473 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1474 return;
1475
1476 // Load decl names into diagnostic.
1477 if (Decls.size() > 4)
1478 PDiag << 0;
1479 else {
1480 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001481 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1482 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001483 I != E; ++I)
1484 PDiag << (*I)->getDeclName();
1485 }
1486
1487 // Load SourceRanges into diagnostic if there is room.
1488 // Otherwise, load the SourceRange of the conditional expression.
1489 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001490 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001491 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001492 I != E; ++I)
1493 PDiag << *I;
1494 else
1495 PDiag << Second->getSourceRange();
1496
1497 S.Diag(Ranges.begin()->getBegin(), PDiag);
1498 }
1499
Richard Trieu4e7c9622013-08-06 21:31:54 +00001500 // If Statement is an incemement or decrement, return true and sets the
1501 // variables Increment and DRE.
1502 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1503 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001504 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1505 if (!Cleanups->cleanupsHaveSideEffects())
1506 Statement = Cleanups->getSubExpr();
1507
Richard Trieu4e7c9622013-08-06 21:31:54 +00001508 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1509 switch (UO->getOpcode()) {
1510 default: return false;
1511 case UO_PostInc:
1512 case UO_PreInc:
1513 Increment = true;
1514 break;
1515 case UO_PostDec:
1516 case UO_PreDec:
1517 Increment = false;
1518 break;
1519 }
1520 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1521 return DRE;
1522 }
1523
1524 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1525 FunctionDecl *FD = Call->getDirectCallee();
1526 if (!FD || !FD->isOverloadedOperator()) return false;
1527 switch (FD->getOverloadedOperator()) {
1528 default: return false;
1529 case OO_PlusPlus:
1530 Increment = true;
1531 break;
1532 case OO_MinusMinus:
1533 Increment = false;
1534 break;
1535 }
1536 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1537 return DRE;
1538 }
1539
1540 return false;
1541 }
1542
Serge Pavlov09f99242014-01-23 15:05:00 +00001543 // A visitor to determine if a continue or break statement is a
1544 // subexpression.
1545 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1546 SourceLocation BreakLoc;
1547 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001548 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001549 BreakContinueFinder(Sema &S, Stmt* Body) :
1550 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001551 Visit(Body);
1552 }
1553
Serge Pavlov09f99242014-01-23 15:05:00 +00001554 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001555
1556 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001557 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001558 }
1559
Serge Pavlov09f99242014-01-23 15:05:00 +00001560 void VisitBreakStmt(BreakStmt* E) {
1561 BreakLoc = E->getBreakLoc();
1562 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001563
Serge Pavlov09f99242014-01-23 15:05:00 +00001564 bool ContinueFound() { return ContinueLoc.isValid(); }
1565 bool BreakFound() { return BreakLoc.isValid(); }
1566 SourceLocation GetContinueLoc() { return ContinueLoc; }
1567 SourceLocation GetBreakLoc() { return BreakLoc; }
1568
1569 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001570
1571 // Emit a warning when a loop increment/decrement appears twice per loop
1572 // iteration. The conditions which trigger this warning are:
1573 // 1) The last statement in the loop body and the third expression in the
1574 // for loop are both increment or both decrement of the same variable
1575 // 2) No continue statements in the loop body.
1576 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1577 // Return when there is nothing to check.
1578 if (!Body || !Third) return;
1579
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001580 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1581 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001582 return;
1583
1584 // Get the last statement from the loop body.
1585 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1586 if (!CS || CS->body_empty()) return;
1587 Stmt *LastStmt = CS->body_back();
1588 if (!LastStmt) return;
1589
1590 bool LoopIncrement, LastIncrement;
1591 DeclRefExpr *LoopDRE, *LastDRE;
1592
1593 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1594 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1595
1596 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001597 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001598 if (LoopIncrement != LastIncrement ||
1599 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1600
Serge Pavlov09f99242014-01-23 15:05:00 +00001601 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001602
1603 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1604 << LastDRE->getDecl() << LastIncrement;
1605 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1606 << LoopIncrement;
1607 }
1608
Richard Trieu451a5db2012-04-30 18:01:30 +00001609} // end namespace
1610
Serge Pavlov09f99242014-01-23 15:05:00 +00001611
1612void Sema::CheckBreakContinueBinding(Expr *E) {
1613 if (!E || getLangOpts().CPlusPlus)
1614 return;
1615 BreakContinueFinder BCFinder(*this, E);
1616 Scope *BreakParent = CurScope->getBreakParent();
1617 if (BCFinder.BreakFound() && BreakParent) {
1618 if (BreakParent->getFlags() & Scope::SwitchScope) {
1619 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1620 } else {
1621 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1622 << "break";
1623 }
1624 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1625 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1626 << "continue";
1627 }
1628}
1629
Richard Smith03a4aa32016-06-23 19:02:52 +00001630StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1631 Stmt *First, ConditionResult Second,
1632 FullExprArg third, SourceLocation RParenLoc,
1633 Stmt *Body) {
1634 if (Second.isInvalid())
1635 return StmtError();
1636
David Blaikiebbafb8a2012-03-11 07:00:24 +00001637 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001638 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001639 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1640 // declare identifiers for objects having storage class 'auto' or
1641 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001642 for (auto *DI : DS->decls()) {
1643 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001644 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001645 VD = nullptr;
1646 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001647 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1648 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001649 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001650 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001651 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001652 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001653
Richard Smith03a4aa32016-06-23 19:02:52 +00001654 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001655 CheckBreakContinueBinding(third.get());
1656
Richard Smith03a4aa32016-06-23 19:02:52 +00001657 if (!Second.get().first)
1658 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1659 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001660 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001661
Richard Smith03a4aa32016-06-23 19:02:52 +00001662 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001663 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001664 Second.get().second->getExprLoc()))
1665 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001666
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001667 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
Anders Carlsson1682af52009-08-01 01:39:59 +00001669 DiagnoseUnusedExprResult(First);
1670 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001671 DiagnoseUnusedExprResult(Body);
1672
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001673 if (isa<NullStmt>(Body))
1674 getCurCompoundScope().setHasEmptyLoopBodies();
1675
Richard Smith03a4aa32016-06-23 19:02:52 +00001676 return new (Context)
1677 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1678 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001679}
1680
John McCall34376a62010-12-04 03:47:34 +00001681/// In an Objective C collection iteration statement:
1682/// for (x in y)
1683/// x can be an arbitrary l-value expression. Bind it up as a
1684/// full-expression.
1685StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001686 // Reduce placeholder expressions here. Note that this rejects the
1687 // use of pseudo-object l-values in this position.
1688 ExprResult result = CheckPlaceholderExpr(E);
1689 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001690 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001691
Richard Smith945f8d32013-01-14 22:39:08 +00001692 ExprResult FullExpr = ActOnFinishFullExpr(E);
1693 if (FullExpr.isInvalid())
1694 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001695 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001696}
1697
John McCall53848232011-07-27 01:07:15 +00001698ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001699Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1700 if (!collection)
1701 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001702
Kaelyn Takata15867822014-11-21 18:48:04 +00001703 ExprResult result = CorrectDelayedTyposInExpr(collection);
1704 if (!result.isUsable())
1705 return ExprError();
1706 collection = result.get();
1707
John McCall53848232011-07-27 01:07:15 +00001708 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001709 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001710
1711 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001712 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001713 if (result.isInvalid())
1714 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001715 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001716
1717 // The operand needs to have object-pointer type.
1718 // TODO: should we do a contextual conversion?
1719 const ObjCObjectPointerType *pointerType =
1720 collection->getType()->getAs<ObjCObjectPointerType>();
1721 if (!pointerType)
1722 return Diag(forLoc, diag::err_collection_expr_type)
1723 << collection->getType() << collection->getSourceRange();
1724
1725 // Check that the operand provides
1726 // - countByEnumeratingWithState:objects:count:
1727 const ObjCObjectType *objectType = pointerType->getObjectType();
1728 ObjCInterfaceDecl *iface = objectType->getInterface();
1729
1730 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001731 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001732 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001733 (getLangOpts().ObjCAutoRefCount
1734 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1735 diag::err_arc_collection_forward, collection)
1736 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001737 // Otherwise, if we have any useful type information, check that
1738 // the type declares the appropriate method.
1739 } else if (iface || !objectType->qual_empty()) {
1740 IdentifierInfo *selectorIdents[] = {
1741 &Context.Idents.get("countByEnumeratingWithState"),
1742 &Context.Idents.get("objects"),
1743 &Context.Idents.get("count")
1744 };
1745 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1746
Craig Topperc3ec1492014-05-26 06:22:03 +00001747 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001748
1749 // If there's an interface, look in both the public and private APIs.
1750 if (iface) {
1751 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001752 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001753 }
1754
1755 // Also check protocol qualifiers.
1756 if (!method)
1757 method = LookupMethodInQualifiedType(selector, pointerType,
1758 /*instance*/ true);
1759
1760 // If we didn't find it anywhere, give up.
1761 if (!method) {
1762 Diag(forLoc, diag::warn_collection_expr_type)
1763 << collection->getType() << selector << collection->getSourceRange();
1764 }
1765
1766 // TODO: check for an incompatible signature?
1767 }
1768
1769 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001770 return collection;
John McCall53848232011-07-27 01:07:15 +00001771}
1772
John McCalldadc5752010-08-24 06:29:42 +00001773StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001774Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001775 Stmt *First, Expr *collection,
1776 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001777
1778 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001779 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001780
Fariborz Jahanian93977672008-01-10 20:33:58 +00001781 if (First) {
1782 QualType FirstType;
1783 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001784 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001785 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1786 diag::err_toomany_element_decls));
1787
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001788 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1789 if (!D || D->isInvalidDecl())
1790 return StmtError();
1791
John McCall31168b02011-06-15 23:02:42 +00001792 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001793 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1794 // declare identifiers for objects having storage class 'auto' or
1795 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001796 if (!D->hasLocalStorage())
1797 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001798 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001799
1800 // If the type contained 'auto', deduce the 'auto' to 'id'.
1801 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001802 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1803 VK_RValue);
1804 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001805 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1806 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001807 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001808 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001809 D->setInvalidDecl();
1810 return StmtError();
1811 }
1812
Richard Smith061f1e22013-04-30 21:23:01 +00001813 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001814
1815 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001816 SourceLocation Loc =
1817 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001818 Diag(Loc, diag::warn_auto_var_is_id)
1819 << D->getDeclName();
1820 }
1821 }
1822
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001823 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001824 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001825 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001826 return StmtError(Diag(First->getLocStart(),
1827 diag::err_selector_element_not_lvalue)
1828 << First->getSourceRange());
1829
Mike Stump11289f42009-09-09 15:08:12 +00001830 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001831 if (FirstType.isConstQualified())
1832 Diag(ForLoc, diag::err_selector_element_const_type)
1833 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001834 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001835 if (!FirstType->isDependentType() &&
1836 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001837 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001838 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1839 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001840 }
Chad Rosier02a84392012-08-10 17:56:09 +00001841
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001842 if (CollectionExprResult.isInvalid())
1843 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001844
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001845 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001846 if (CollectionExprResult.isInvalid())
1847 return StmtError();
1848
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001849 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1850 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001851}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001852
Richard Smith02e85f32011-04-14 22:09:26 +00001853/// Finish building a variable declaration for a for-range statement.
1854/// \return true if an error occurs.
1855static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001856 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001857 if (Decl->getType()->isUndeducedType()) {
1858 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1859 if (!Res.isUsable()) {
1860 Decl->setInvalidDecl();
1861 return true;
1862 }
1863 Init = Res.get();
1864 }
1865
Richard Smith02e85f32011-04-14 22:09:26 +00001866 // Deduce the type for the iterator variable now rather than leaving it to
1867 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001868 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001869 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001870 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001871 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001872 SemaRef.Diag(Loc, DiagID) << Init->getType();
1873 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001874 Decl->setInvalidDecl();
1875 return true;
1876 }
Richard Smith061f1e22013-04-30 21:23:01 +00001877 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001878
John McCall31168b02011-06-15 23:02:42 +00001879 // In ARC, infer lifetime.
1880 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1881 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001882 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001883 SemaRef.inferObjCARCLifetime(Decl))
1884 Decl->setInvalidDecl();
1885
Richard Smith02e85f32011-04-14 22:09:26 +00001886 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1887 /*TypeMayContainAuto=*/false);
1888 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001889 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001890 return false;
1891}
1892
Sam Panzer0f384432012-08-21 00:52:01 +00001893namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001894// An enum to represent whether something is dealing with a call to begin()
1895// or a call to end() in a range-based for loop.
1896enum BeginEndFunction {
1897 BEF_begin,
1898 BEF_end
1899};
Sam Panzer0f384432012-08-21 00:52:01 +00001900
Richard Smith02e85f32011-04-14 22:09:26 +00001901/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001902/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001903/// nor from the diagnostics produced when analysing the implicit expressions
1904/// required in a for-range statement.
1905void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001906 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001907 CallExpr *CE = dyn_cast<CallExpr>(E);
1908 if (!CE)
1909 return;
1910 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1911 if (!D)
1912 return;
1913 SourceLocation Loc = D->getLocation();
1914
1915 std::string Description;
1916 bool IsTemplate = false;
1917 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1918 Description = SemaRef.getTemplateArgumentBindingsText(
1919 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1920 IsTemplate = true;
1921 }
1922
1923 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1924 << BEF << IsTemplate << Description << E->getType();
1925}
1926
Sam Panzer0f384432012-08-21 00:52:01 +00001927/// Build a variable declaration for a for-range statement.
1928VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1929 QualType Type, const char *Name) {
1930 DeclContext *DC = SemaRef.CurContext;
1931 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1932 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1933 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001934 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001935 Decl->setImplicit();
1936 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001937}
1938
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001939}
Richard Smith02e85f32011-04-14 22:09:26 +00001940
Fariborz Jahanian00213472012-07-06 19:04:04 +00001941static bool ObjCEnumerationCollection(Expr *Collection) {
1942 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001943 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001944}
1945
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001946/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001947///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001948/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001949/// A range-based for statement is equivalent to
1950///
1951/// {
1952/// auto && __range = range-init;
1953/// for ( auto __begin = begin-expr,
1954/// __end = end-expr;
1955/// __begin != __end;
1956/// ++__begin ) {
1957/// for-range-declaration = *__begin;
1958/// statement
1959/// }
1960/// }
1961///
1962/// The body of the loop is not available yet, since it cannot be analysed until
1963/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001964StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1965 SourceLocation CoawaitLoc, Stmt *First,
1966 SourceLocation ColonLoc, Expr *Range,
1967 SourceLocation RParenLoc,
1968 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001969 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001970 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001971
Richard Smith3249fed2013-08-21 01:40:36 +00001972 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001973 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001974
1975 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1976 assert(DS && "first part of for range not a decl stmt");
1977
1978 if (!DS->isSingleDecl()) {
1979 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1980 return StmtError();
1981 }
Richard Smith02e85f32011-04-14 22:09:26 +00001982
Richard Smith3249fed2013-08-21 01:40:36 +00001983 Decl *LoopVar = DS->getSingleDecl();
1984 if (LoopVar->isInvalidDecl() || !Range ||
1985 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1986 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001987 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001988 }
Richard Smith02e85f32011-04-14 22:09:26 +00001989
Richard Smithcfd53b42015-10-22 06:13:50 +00001990 // Coroutines: 'for co_await' implicitly co_awaits its range.
1991 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00001992 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00001993 if (Coawait.isInvalid()) return StmtError();
1994 Range = Coawait.get();
1995 }
1996
Richard Smith02e85f32011-04-14 22:09:26 +00001997 // Build auto && __range = range-init
1998 SourceLocation RangeLoc = Range->getLocStart();
1999 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2000 Context.getAutoRRefDeductType(),
2001 "__range");
2002 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002003 diag::err_for_range_deduction_failure)) {
2004 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002005 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002006 }
Richard Smith02e85f32011-04-14 22:09:26 +00002007
2008 // Claim the type doesn't contain auto: we've already done the checking.
2009 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002010 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00002011 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002012 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002013 if (RangeDecl.isInvalid()) {
2014 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002015 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002016 }
Richard Smith02e85f32011-04-14 22:09:26 +00002017
Richard Smithcfd53b42015-10-22 06:13:50 +00002018 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002019 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2020 /*Cond=*/nullptr, /*Inc=*/nullptr,
2021 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002022}
2023
2024/// \brief Create the initialization, compare, and increment steps for
2025/// the range-based for loop expression.
2026/// This function does not handle array-based for loops,
2027/// which are created in Sema::BuildCXXForRangeStmt.
2028///
2029/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2030/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2031/// CandidateSet and BEF are set and some non-success value is returned on
2032/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002033static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002034 Expr *BeginRange, Expr *EndRange,
2035 QualType RangeType,
2036 VarDecl *BeginVar,
2037 VarDecl *EndVar,
2038 SourceLocation ColonLoc,
2039 OverloadCandidateSet *CandidateSet,
2040 ExprResult *BeginExpr,
2041 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002042 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002043 DeclarationNameInfo BeginNameInfo(
2044 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2045 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2046 ColonLoc);
2047
2048 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2049 Sema::LookupMemberName);
2050 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2051
2052 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2053 // - if _RangeT is a class type, the unqualified-ids begin and end are
2054 // looked up in the scope of class _RangeT as if by class member access
2055 // lookup (3.4.5), and if either (or both) finds at least one
2056 // declaration, begin-expr and end-expr are __range.begin() and
2057 // __range.end(), respectively;
2058 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2059 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2060
2061 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2062 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002063 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002064
2065 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2066 << RangeLoc << BeginRange->getType() << *BEF;
2067 return Sema::FRS_DiagnosticIssued;
2068 }
2069 } else {
2070 // - otherwise, begin-expr and end-expr are begin(__range) and
2071 // end(__range), respectively, where begin and end are looked up with
2072 // argument-dependent lookup (3.4.2). For the purposes of this name
2073 // lookup, namespace std is an associated namespace.
2074
2075 }
2076
Richard Smith9f690bd2015-10-27 06:02:45 +00002077 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002078 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002079 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002080 BeginMemberLookup, CandidateSet,
2081 BeginRange, BeginExpr);
2082
Richard Smith9f690bd2015-10-27 06:02:45 +00002083 if (RangeStatus != Sema::FRS_Success) {
2084 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2085 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2086 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002087 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002088 }
Sam Panzer0f384432012-08-21 00:52:01 +00002089 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2090 diag::err_for_range_iter_deduction_failure)) {
2091 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2092 return Sema::FRS_DiagnosticIssued;
2093 }
2094
Richard Smith9f690bd2015-10-27 06:02:45 +00002095 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002096 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002097 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002098 EndMemberLookup, CandidateSet,
2099 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002100 if (RangeStatus != Sema::FRS_Success) {
2101 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2102 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2103 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002104 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002105 }
Sam Panzer0f384432012-08-21 00:52:01 +00002106 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2107 diag::err_for_range_iter_deduction_failure)) {
2108 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2109 return Sema::FRS_DiagnosticIssued;
2110 }
2111 return Sema::FRS_Success;
2112}
2113
2114/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002115/// If the attempt fails, this function will return a valid, null StmtResult
2116/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002117static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2118 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002119 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002120 Stmt *LoopVarDecl,
2121 SourceLocation ColonLoc,
2122 Expr *Range,
2123 SourceLocation RangeLoc,
2124 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002125 // Determine whether we can rebuild the for-range statement with a
2126 // dereferenced range expression.
2127 ExprResult AdjustedRange;
2128 {
2129 Sema::SFINAETrap Trap(SemaRef);
2130
2131 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2132 if (AdjustedRange.isInvalid())
2133 return StmtResult();
2134
Richard Smith9f690bd2015-10-27 06:02:45 +00002135 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2136 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2137 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002138 if (SR.isInvalid())
2139 return StmtResult();
2140 }
2141
2142 // The attempt to dereference worked well enough that it could produce a valid
2143 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2144 // case there are any other (non-fatal) problems with it.
2145 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2146 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002147 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2148 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002149 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002150}
2151
Richard Smith3249fed2013-08-21 01:40:36 +00002152namespace {
2153/// RAII object to automatically invalidate a declaration if an error occurs.
2154struct InvalidateOnErrorScope {
2155 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2156 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2157 ~InvalidateOnErrorScope() {
2158 if (Enabled && Trap.hasErrorOccurred())
2159 D->setInvalidDecl();
2160 }
2161
2162 DiagnosticErrorTrap Trap;
2163 Decl *D;
2164 bool Enabled;
2165};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002166}
Richard Smith3249fed2013-08-21 01:40:36 +00002167
Richard Smitha05b3b52012-09-20 21:52:32 +00002168/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002169StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002170Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002171 SourceLocation ColonLoc, Stmt *RangeDecl,
2172 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002173 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002174 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002175 // FIXME: This should not be used during template instantiation. We should
2176 // pick up the set of unqualified lookup results for the != and + operators
2177 // in the initial parse.
2178 //
2179 // Testcase (accepts-invalid):
2180 // template<typename T> void f() { for (auto x : T()) {} }
2181 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2182 // bool operator!=(N::X, N::X); void operator++(N::X);
2183 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002184 Scope *S = getCurScope();
2185
2186 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2187 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2188 QualType RangeVarType = RangeVar->getType();
2189
2190 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2191 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2192
Richard Smith3249fed2013-08-21 01:40:36 +00002193 // If we hit any errors, mark the loop variable as invalid if its type
2194 // contains 'auto'.
2195 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2196 LoopVar->getType()->isUndeducedType());
2197
Richard Smith01694c32016-03-20 10:33:40 +00002198 StmtResult BeginDeclStmt = Begin;
2199 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002200 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2201
Richard Smith27d807c2013-04-30 13:56:41 +00002202 if (RangeVarType->isDependentType()) {
2203 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002204 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002205
2206 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2207 // them in properly when we instantiate the loop.
2208 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2209 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Richard Smith01694c32016-03-20 10:33:40 +00002210 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002211 SourceLocation RangeLoc = RangeVar->getLocation();
2212
Ted Kremenekbed648e2011-10-10 22:36:28 +00002213 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2214
2215 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2216 VK_LValue, ColonLoc);
2217 if (BeginRangeRef.isInvalid())
2218 return StmtError();
2219
2220 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2221 VK_LValue, ColonLoc);
2222 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002223 return StmtError();
2224
2225 QualType AutoType = Context.getAutoDeductType();
2226 Expr *Range = RangeVar->getInit();
2227 if (!Range)
2228 return StmtError();
2229 QualType RangeType = Range->getType();
2230
2231 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002232 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002233 return StmtError();
2234
2235 // Build auto __begin = begin-expr, __end = end-expr.
2236 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2237 "__begin");
2238 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2239 "__end");
2240
2241 // Build begin-expr and end-expr and attach to __begin and __end variables.
2242 ExprResult BeginExpr, EndExpr;
2243 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2244 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2245 // __range + __bound, respectively, where __bound is the array bound. If
2246 // _RangeT is an array of unknown size or an array of incomplete type,
2247 // the program is ill-formed;
2248
2249 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002250 BeginExpr = BeginRangeRef;
2251 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002252 diag::err_for_range_iter_deduction_failure)) {
2253 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2254 return StmtError();
2255 }
2256
2257 // Find the array bound.
2258 ExprResult BoundExpr;
2259 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002260 BoundExpr = IntegerLiteral::Create(
2261 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002262 else if (const VariableArrayType *VAT =
2263 dyn_cast<VariableArrayType>(UnqAT))
2264 BoundExpr = VAT->getSizeExpr();
2265 else {
2266 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2267 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002268 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002269 }
2270
2271 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002272 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002273 BoundExpr.get());
2274 if (EndExpr.isInvalid())
2275 return StmtError();
2276 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2277 diag::err_for_range_iter_deduction_failure)) {
2278 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2279 return StmtError();
2280 }
2281 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002282 OverloadCandidateSet CandidateSet(RangeLoc,
2283 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002284 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002285 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002286 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002287 EndRangeRef.get(), RangeType,
2288 BeginVar, EndVar, ColonLoc, &CandidateSet,
2289 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002290
Richard Smitha05b3b52012-09-20 21:52:32 +00002291 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002292 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002293 // If the range is being built from an array parameter, emit a
2294 // a diagnostic that it is being treated as a pointer.
2295 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2296 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2297 QualType ArrayTy = PVD->getOriginalType();
2298 QualType PointerTy = PVD->getType();
2299 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2300 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2301 << RangeLoc << PVD << ArrayTy << PointerTy;
2302 Diag(PVD->getLocation(), diag::note_declared_at);
2303 return StmtError();
2304 }
2305 }
2306 }
2307
2308 // If building the range failed, try dereferencing the range expression
2309 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002310 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002311 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002312 LoopVarDecl, ColonLoc,
2313 Range, RangeLoc,
2314 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002315 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002316 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002317 }
2318
Sam Panzer0f384432012-08-21 00:52:01 +00002319 // Otherwise, emit diagnostics if we haven't already.
2320 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002321 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002322 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2323 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002324 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002325 }
2326 // Return an error if no fix was discovered.
2327 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002328 return StmtError();
2329 }
2330
Sam Panzer0f384432012-08-21 00:52:01 +00002331 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2332 "invalid range expression in for loop");
2333
2334 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002335 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002336 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2337 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002338 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2339 ? diag::warn_for_range_begin_end_types_differ
2340 : diag::ext_for_range_begin_end_types_differ)
2341 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002342 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2343 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2344 }
2345
Richard Smith01694c32016-03-20 10:33:40 +00002346 BeginDeclStmt =
2347 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2348 EndDeclStmt =
2349 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002350
Ted Kremenekbed648e2011-10-10 22:36:28 +00002351 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2352 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002353 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002354 if (BeginRef.isInvalid())
2355 return StmtError();
2356
Richard Smith02e85f32011-04-14 22:09:26 +00002357 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2358 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002359 if (EndRef.isInvalid())
2360 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002361
2362 // Build and check __begin != __end expression.
2363 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2364 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002365 if (!NotEqExpr.isInvalid())
2366 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2367 if (!NotEqExpr.isInvalid())
2368 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002369 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002370 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2371 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002372 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2373 if (!Context.hasSameType(BeginType, EndType))
2374 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2375 return StmtError();
2376 }
2377
2378 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002379 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2380 VK_LValue, ColonLoc);
2381 if (BeginRef.isInvalid())
2382 return StmtError();
2383
Richard Smith02e85f32011-04-14 22:09:26 +00002384 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002385 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002386 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002387 if (!IncrExpr.isInvalid())
2388 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002389 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002390 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2391 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002392 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2393 return StmtError();
2394 }
2395
2396 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002397 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2398 VK_LValue, ColonLoc);
2399 if (BeginRef.isInvalid())
2400 return StmtError();
2401
Richard Smith02e85f32011-04-14 22:09:26 +00002402 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2403 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002404 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2405 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002406 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2407 return StmtError();
2408 }
2409
Richard Smitha05b3b52012-09-20 21:52:32 +00002410 // Attach *__begin as initializer for VD. Don't touch it if we're just
2411 // trying to determine whether this would be a valid range.
2412 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002413 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2414 /*TypeMayContainAuto=*/true);
2415 if (LoopVar->isInvalidDecl())
2416 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2417 }
2418 }
2419
Richard Smitha05b3b52012-09-20 21:52:32 +00002420 // Don't bother to actually allocate the result if we're just trying to
2421 // determine whether it would be valid.
2422 if (Kind == BFRK_Check)
2423 return StmtResult();
2424
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002425 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002426 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2427 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002428 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2429 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002430}
2431
Chad Rosier02a84392012-08-10 17:56:09 +00002432/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002433/// statement.
2434StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2435 if (!S || !B)
2436 return StmtError();
2437 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002438
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002439 ForStmt->setBody(B);
2440 return S;
2441}
2442
Richard Trieu3e1d4832015-04-13 22:08:55 +00002443// Warn when the loop variable is a const reference that creates a copy.
2444// Suggest using the non-reference type for copies. If a copy can be prevented
2445// suggest the const reference type that would do so.
2446// For instance, given "for (const &Foo : Range)", suggest
2447// "for (const Foo : Range)" to denote a copy is made for the loop. If
2448// possible, also suggest "for (const &Bar : Range)" if this type prevents
2449// the copy altogether.
2450static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2451 const VarDecl *VD,
2452 QualType RangeInitType) {
2453 const Expr *InitExpr = VD->getInit();
2454 if (!InitExpr)
2455 return;
2456
2457 QualType VariableType = VD->getType();
2458
Tim Shen4a05bb82016-06-21 20:29:17 +00002459 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2460 if (!Cleanups->cleanupsHaveSideEffects())
2461 InitExpr = Cleanups->getSubExpr();
2462
Richard Trieu3e1d4832015-04-13 22:08:55 +00002463 const MaterializeTemporaryExpr *MTE =
2464 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2465
2466 // No copy made.
2467 if (!MTE)
2468 return;
2469
2470 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2471
2472 // Searching for either UnaryOperator for dereference of a pointer or
2473 // CXXOperatorCallExpr for handling iterators.
2474 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2475 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2476 E = CCE->getArg(0);
2477 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2478 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2479 E = ME->getBase();
2480 } else {
2481 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2482 E = MTE->GetTemporaryExpr();
2483 }
2484 E = E->IgnoreImpCasts();
2485 }
2486
2487 bool ReturnsReference = false;
2488 if (isa<UnaryOperator>(E)) {
2489 ReturnsReference = true;
2490 } else {
2491 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2492 const FunctionDecl *FD = Call->getDirectCallee();
2493 QualType ReturnType = FD->getReturnType();
2494 ReturnsReference = ReturnType->isReferenceType();
2495 }
2496
2497 if (ReturnsReference) {
2498 // Loop variable creates a temporary. Suggest either to go with
2499 // non-reference loop variable to indiciate a copy is made, or
2500 // the correct time to bind a const reference.
2501 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2502 << VD << VariableType << E->getType();
2503 QualType NonReferenceType = VariableType.getNonReferenceType();
2504 NonReferenceType.removeLocalConst();
2505 QualType NewReferenceType =
2506 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2507 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2508 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2509 } else {
2510 // The range always returns a copy, so a temporary is always created.
2511 // Suggest removing the reference from the loop variable.
2512 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2513 << VD << RangeInitType;
2514 QualType NonReferenceType = VariableType.getNonReferenceType();
2515 NonReferenceType.removeLocalConst();
2516 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2517 << NonReferenceType << VD->getSourceRange();
2518 }
2519}
2520
2521// Warns when the loop variable can be changed to a reference type to
2522// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2523// "for (const Foo &x : Range)" if this form does not make a copy.
2524static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2525 const VarDecl *VD) {
2526 const Expr *InitExpr = VD->getInit();
2527 if (!InitExpr)
2528 return;
2529
2530 QualType VariableType = VD->getType();
2531
2532 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2533 if (!CE->getConstructor()->isCopyConstructor())
2534 return;
2535 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2536 if (CE->getCastKind() != CK_LValueToRValue)
2537 return;
2538 } else {
2539 return;
2540 }
2541
2542 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2543 // should be emitted. Also, only ignore POD types with trivial copy
2544 // constructors.
2545 if (VariableType.isPODType(SemaRef.Context))
2546 return;
2547
2548 // Suggest changing from a const variable to a const reference variable
2549 // if doing so will prevent a copy.
2550 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2551 << VD << VariableType << InitExpr->getType();
2552 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2553 << SemaRef.Context.getLValueReferenceType(VariableType)
2554 << VD->getSourceRange();
2555}
2556
2557/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2558/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2559/// using "const foo x" to show that a copy is made
2560/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2561/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2562/// prevent the copy.
2563/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2564/// Suggest "const foo &x" to prevent the copy.
2565static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2566 const CXXForRangeStmt *ForStmt) {
2567 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2568 ForStmt->getLocStart()) &&
2569 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2570 ForStmt->getLocStart()) &&
2571 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2572 ForStmt->getLocStart())) {
2573 return;
2574 }
2575
2576 const VarDecl *VD = ForStmt->getLoopVariable();
2577 if (!VD)
2578 return;
2579
2580 QualType VariableType = VD->getType();
2581
2582 if (VariableType->isIncompleteType())
2583 return;
2584
2585 const Expr *InitExpr = VD->getInit();
2586 if (!InitExpr)
2587 return;
2588
2589 if (VariableType->isReferenceType()) {
2590 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2591 ForStmt->getRangeInit()->getType());
2592 } else if (VariableType.isConstQualified()) {
2593 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2594 }
2595}
2596
Richard Smith02e85f32011-04-14 22:09:26 +00002597/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2598/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2599/// body cannot be performed until after the type of the range variable is
2600/// determined.
2601StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2602 if (!S || !B)
2603 return StmtError();
2604
Fariborz Jahanian00213472012-07-06 19:04:04 +00002605 if (isa<ObjCForCollectionStmt>(S))
2606 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002607
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002608 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2609 ForStmt->setBody(B);
2610
2611 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2612 diag::warn_empty_range_based_for_body);
2613
Richard Trieu3e1d4832015-04-13 22:08:55 +00002614 DiagnoseForRangeVariableCopies(*this, ForStmt);
2615
Richard Smith02e85f32011-04-14 22:09:26 +00002616 return S;
2617}
2618
Chris Lattnercab02a62011-02-17 20:34:02 +00002619StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2620 SourceLocation LabelLoc,
2621 LabelDecl *TheDecl) {
2622 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002623 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002624 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002625}
Chris Lattner1c310502007-05-31 06:00:00 +00002626
John McCalldadc5752010-08-24 06:29:42 +00002627StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002628Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002629 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002630 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002631 if (!E->isTypeDependent()) {
2632 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002633 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002634 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002635 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002636 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2637 if (ExprRes.isInvalid())
2638 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002639 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002640 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002641 return StmtError();
2642 }
John McCalla95172b2010-08-01 00:26:45 +00002643
Richard Smith945f8d32013-01-14 22:39:08 +00002644 ExprResult ExprRes = ActOnFinishFullExpr(E);
2645 if (ExprRes.isInvalid())
2646 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002647 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002648
John McCallaab3e412010-08-25 08:40:02 +00002649 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002650
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002651 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002652}
2653
Nico Weberd64657f2015-03-09 02:47:59 +00002654static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2655 const Scope &DestScope) {
2656 if (!S.CurrentSEHFinally.empty() &&
2657 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2658 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2659 }
2660}
2661
John McCalldadc5752010-08-24 06:29:42 +00002662StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002663Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002664 Scope *S = CurScope->getContinueParent();
2665 if (!S) {
2666 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002667 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002668 }
Nico Weberd64657f2015-03-09 02:47:59 +00002669 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002670
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002671 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002672}
2673
John McCalldadc5752010-08-24 06:29:42 +00002674StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002675Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002676 Scope *S = CurScope->getBreakParent();
2677 if (!S) {
2678 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002679 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002680 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002681 if (S->isOpenMPLoopScope())
2682 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2683 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002684 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002685
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002686 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002687}
2688
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002689/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002690/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002691///
Douglas Gregor5d369002011-01-21 18:05:27 +00002692/// \param ReturnType If we're determining the copy elision candidate for
2693/// a return statement, this is the return type of the function. If we're
2694/// determining the copy elision candidate for a throw expression, this will
2695/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002696///
Douglas Gregor5d369002011-01-21 18:05:27 +00002697/// \param E The expression being returned from the function or block, or
2698/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002699///
Douglas Gregor86394412011-05-20 15:00:53 +00002700/// \param AllowFunctionParameter Whether we allow function parameters to
2701/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2702/// we re-use this logic to determine whether we should try to move as part of
2703/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002704///
2705/// \returns The NRVO candidate variable, if the return statement may use the
2706/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002707VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2708 Expr *E,
2709 bool AllowFunctionParameter) {
2710 if (!getLangOpts().CPlusPlus)
2711 return nullptr;
2712
2713 // - in a return statement in a function [where] ...
2714 // ... the expression is the name of a non-volatile automatic object ...
2715 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002716 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002717 return nullptr;
2718 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2719 if (!VD)
2720 return nullptr;
2721
2722 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2723 return VD;
2724 return nullptr;
2725}
2726
2727bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2728 bool AllowFunctionParameter) {
2729 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002730 // - in a return statement in a function with ...
2731 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002732 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002733 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002734 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002735 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002736 if (!VDType->isDependentType() &&
2737 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2738 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002740
John McCall03318c12011-11-11 03:57:31 +00002741 // ...object (other than a function or catch-clause parameter)...
2742 if (VD->getKind() != Decl::Var &&
2743 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002744 return false;
2745 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
John McCall03318c12011-11-11 03:57:31 +00002747 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002748 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002749
2750 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002751 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002752
2753 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002754 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002755
2756 // Variables with higher required alignment than their type's ABI
2757 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002758 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002759 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002760 return false;
John McCall03318c12011-11-11 03:57:31 +00002761
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002762 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002763}
2764
Douglas Gregor626fbed2011-01-21 21:08:57 +00002765/// \brief Perform the initialization of a potentially-movable value, which
2766/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002767///
2768/// This routine implements C++0x [class.copy]p33, which attempts to treat
2769/// returned lvalues as rvalues in certain cases (to prefer move construction),
2770/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002772Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2773 const VarDecl *NRVOCandidate,
2774 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002775 Expr *Value,
2776 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002777 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002778 // When the criteria for elision of a copy operation are met or would
2779 // be met save for the fact that the source object is a function
2780 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002781 // overload resolution to select the constructor for the copy is first
2782 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002783 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002784 if (AllowNRVO &&
2785 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002787 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002788
Douglas Gregorf282a762011-01-21 19:38:21 +00002789 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002791 = InitializationKind::CreateCopy(Value->getLocStart(),
2792 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002793 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002794
2795 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002796 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002797 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002798 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002799 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002800 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2801 StepEnd = Seq.step_end();
2802 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002803 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002804 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
2806 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002807 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002808
Douglas Gregorf282a762011-01-21 19:38:21 +00002809 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002810 = Constructor->getParamDecl(0)->getType()
2811 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812
Douglas Gregorf282a762011-01-21 19:38:21 +00002813 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002815 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2816 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002817 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Douglas Gregorf282a762011-01-21 19:38:21 +00002819 // Promote "AsRvalue" to the heap, since we now need this
2820 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002821 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002822 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823
Douglas Gregorf282a762011-01-21 19:38:21 +00002824 // Complete type-checking the initialization of the return type
2825 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002826 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002827 }
2828 }
2829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830
Douglas Gregorf282a762011-01-21 19:38:21 +00002831 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002833 // (again) now with the return value expression as written.
2834 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002835 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836
Douglas Gregorf282a762011-01-21 19:38:21 +00002837 return Res;
2838}
2839
Richard Smith4db51c22013-09-25 05:02:54 +00002840/// \brief Determine whether the declared return type of the specified function
2841/// contains 'auto'.
2842static bool hasDeducedReturnType(FunctionDecl *FD) {
2843 const FunctionProtoType *FPT =
2844 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002845 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002846}
2847
Eli Friedman34b49062012-01-26 03:00:14 +00002848/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2849/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002850///
John McCalldadc5752010-08-24 06:29:42 +00002851StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002852Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2853 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002854 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002855 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002856 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002857 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00002858 bool HasDeducedReturnType =
2859 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002860
Richard Smithb130fe72016-06-23 19:16:49 +00002861 if (ExprEvalContexts.back().Context == DiscardedStatement &&
2862 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
2863 if (RetValExp) {
2864 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2865 if (ER.isInvalid())
2866 return StmtError();
2867 RetValExp = ER.get();
2868 }
2869 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2870 }
2871
2872 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00002873 // In C++1y, the return type may involve 'auto'.
2874 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2875 FunctionDecl *FD = CurLambda->CallOperator;
2876 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002877 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002878
2879 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2880 assert(AT && "lost auto type from lambda return type");
2881 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2882 FD->setInvalidDecl();
2883 return StmtError();
2884 }
Alp Toker314cc812014-01-25 16:55:45 +00002885 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002886 } else if (CurCap->HasImplicitReturnType) {
2887 // For blocks/lambdas with implicit return types, we check each return
2888 // statement individually, and deduce the common return type when the block
2889 // or lambda is completed.
2890 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002891 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002892 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2893 if (Result.isInvalid())
2894 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002895 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002896
Richard Smith5a0e50c2014-12-19 22:10:51 +00002897 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2898 // when deducing a return type for a lambda-expression (or by extension
2899 // for a block). These rules differ from the stated C++11 rules only in
2900 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002901 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002902 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002903 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002904 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002905 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002906 if (RetValExp) {
2907 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2908 // initializer list, because it is not an expression (even
2909 // though we represent it as one). We still deduce 'void'.
2910 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2911 << RetValExp->getSourceRange();
2912 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002913
Jordan Rosed39e5f12012-07-02 21:19:23 +00002914 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002915 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002916
2917 // Although we'll properly infer the type of the block once it's completed,
2918 // make sure we provide a return type now for better error recovery.
2919 if (CurCap->ReturnType.isNull())
2920 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002921 }
Eli Friedman34b49062012-01-26 03:00:14 +00002922 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002923
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002924 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002925 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2926 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2927 return StmtError();
2928 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002929 } else if (CapturedRegionScopeInfo *CurRegion =
2930 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2931 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2932 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002933 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002934 assert(CurLambda && "unknown kind of captured scope");
2935 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2936 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002937 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2938 return StmtError();
2939 }
2940 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002941
Steve Naroffc540d662008-09-03 18:15:37 +00002942 // Otherwise, verify that this result type matches the previous one. We are
2943 // pickier with blocks than for normal functions because we don't have GCC
2944 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002945 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002946 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002947 // Delay processing for now. TODO: there are lots of dependent
2948 // types we can conclusively prove aren't void.
2949 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002950 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002951 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002952 (RetValExp->isTypeDependent() ||
2953 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002954 if (!getLangOpts().CPlusPlus &&
2955 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002956 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002957 else {
2958 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002959 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002960 }
Steve Naroffc540d662008-09-03 18:15:37 +00002961 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002962 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002963 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2964 } else if (!RetValExp->isTypeDependent()) {
2965 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002966
John McCall5500ef22011-08-17 22:09:46 +00002967 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2968 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2969 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002970
John McCall5500ef22011-08-17 22:09:46 +00002971 // In C++ the return statement is handled via a copy initialization.
2972 // the C version of which boils down to CheckSingleAssignmentConstraints.
2973 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2974 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2975 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002976 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002977 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2978 FnRetType, RetValExp);
2979 if (Res.isInvalid()) {
2980 // FIXME: Cleanup temporaries here, anyway?
2981 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002982 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002983 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002984 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002985 } else {
2986 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002987 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002988
John McCall75f92b52011-08-17 21:34:14 +00002989 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002990 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2991 if (ER.isInvalid())
2992 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002993 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002994 }
John McCall5500ef22011-08-17 22:09:46 +00002995 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2996 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002997
Jordan Rosed39e5f12012-07-02 21:19:23 +00002998 // If we need to check for the named return value optimization,
2999 // or if we need to infer the return type,
3000 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003001 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003002 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Richard Smith9f690bd2015-10-27 06:02:45 +00003004 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3005 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3006
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003007 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003008}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003009
Nico Weber72889432014-09-06 01:25:55 +00003010namespace {
3011/// \brief Marks all typedefs in all local classes in a type referenced.
3012///
3013/// In a function like
3014/// auto f() {
3015/// struct S { typedef int a; };
3016/// return S();
3017/// }
3018///
3019/// the local type escapes and could be referenced in some TUs but not in
3020/// others. Pretend that all local typedefs are always referenced, to not warn
3021/// on this. This isn't necessary if f has internal linkage, or the typedef
3022/// is private.
3023class LocalTypedefNameReferencer
3024 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3025public:
3026 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3027 bool VisitRecordType(const RecordType *RT);
3028private:
3029 Sema &S;
3030};
3031bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3032 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3033 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3034 R->isDependentType())
3035 return true;
3036 for (auto *TmpD : R->decls())
3037 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3038 if (T->getAccess() != AS_private || R->hasFriends())
3039 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3040 return true;
3041}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003042}
Nico Weber72889432014-09-06 01:25:55 +00003043
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003044TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003045 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003046 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3047 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003048 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003049}
3050
Richard Smith2a7d4812013-05-04 07:00:32 +00003051/// Deduce the return type for a function from a returned expression, per
3052/// C++1y [dcl.spec.auto]p6.
3053bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3054 SourceLocation ReturnLoc,
3055 Expr *&RetExpr,
3056 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003057 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003058 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003059
Richard Smithc58f38f2013-08-14 20:16:31 +00003060 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3061 // If the deduction is for a return statement and the initializer is
3062 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003063 Diag(RetExpr->getExprLoc(),
3064 getCurLambda() ? diag::err_lambda_return_init_list
3065 : diag::err_auto_fn_return_init_list)
3066 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003067 return true;
3068 }
3069
3070 if (FD->isDependentContext()) {
3071 // C++1y [dcl.spec.auto]p12:
3072 // Return type deduction [...] occurs when the definition is
3073 // instantiated even if the function body contains a return
3074 // statement with a non-type-dependent operand.
3075 assert(AT->isDeduced() && "should have deduced to dependent type");
3076 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003077 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003078
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003079 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003080 // Otherwise, [...] deduce a value for U using the rules of template
3081 // argument deduction.
3082 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3083
3084 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3085 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3086 << OrigResultType.getType() << RetExpr->getType();
3087
3088 if (DAR != DAR_Succeeded)
3089 return true;
Nico Weber72889432014-09-06 01:25:55 +00003090
3091 // If a local type is part of the returned type, mark its fields as
3092 // referenced.
3093 LocalTypedefNameReferencer Referencer(*this);
3094 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003095 } else {
3096 // In the case of a return with no operand, the initializer is considered
3097 // to be void().
3098 //
3099 // Deduction here can only succeed if the return type is exactly 'cv auto'
3100 // or 'decltype(auto)', so just check for that case directly.
3101 if (!OrigResultType.getType()->getAs<AutoType>()) {
3102 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3103 << OrigResultType.getType();
3104 return true;
3105 }
3106 // We always deduce U = void in this case.
3107 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3108 if (Deduced.isNull())
3109 return true;
3110 }
3111
3112 // If a function with a declared return type that contains a placeholder type
3113 // has multiple return statements, the return type is deduced for each return
3114 // statement. [...] if the type deduced is not the same in each deduction,
3115 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003116 QualType DeducedT = AT->getDeducedType();
3117 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003118 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003119 // It is possible that NewAT->getDeducedType() is null. When that happens,
3120 // we should not crash, instead we ignore this deduction.
3121 if (NewAT->getDeducedType().isNull())
3122 return false;
3123
Douglas Gregora602a152015-10-01 20:20:47 +00003124 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003125 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003126 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3127 NewAT->getDeducedType());
3128 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003129 const LambdaScopeInfo *LambdaSI = getCurLambda();
3130 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3131 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003132 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003133 << true /*IsLambda*/;
3134 } else {
3135 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3136 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003137 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003138 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003139 return true;
3140 }
3141 } else if (!FD->isInvalidDecl()) {
3142 // Update all declarations of the function to have the deduced return type.
3143 Context.adjustDeducedFunctionResultType(FD, Deduced);
3144 }
3145
3146 return false;
3147}
3148
John McCalldadc5752010-08-24 06:29:42 +00003149StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003150Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3151 Scope *CurScope) {
3152 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Richard Smithb130fe72016-06-23 19:16:49 +00003153 if (R.isInvalid() || ExprEvalContexts.back().Context == DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003154 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003155
3156 if (VarDecl *VD =
3157 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3158 CurScope->addNRVOCandidate(VD);
3159 } else {
3160 CurScope->setNoNRVO();
3161 }
3162
Nico Weberd64657f2015-03-09 02:47:59 +00003163 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3164
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003165 return R;
3166}
3167
3168StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003169 // Check for unexpanded parameter packs.
3170 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3171 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003172
Eli Friedman34b49062012-01-26 03:00:14 +00003173 if (isa<CapturingScopeInfo>(getCurFunction()))
3174 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003175
Chris Lattner79413952008-12-04 23:50:19 +00003176 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003177 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003178 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003179 bool isObjCMethod = false;
3180
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003181 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003182 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003183 if (FD->hasAttrs())
3184 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003185 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003186 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003187 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003188 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003189 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003190 isObjCMethod = true;
3191 if (MD->hasAttrs())
3192 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003193 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3194 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003195 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003196 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003197 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3198 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003199 }
3200 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003201 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003202
Richard Smithb130fe72016-06-23 19:16:49 +00003203 // C++1z: discarded return statements are not considered when deducing a
3204 // return type.
3205 if (ExprEvalContexts.back().Context == DiscardedStatement &&
3206 FnRetType->getContainedAutoType()) {
3207 if (RetValExp) {
3208 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3209 if (ER.isInvalid())
3210 return StmtError();
3211 RetValExp = ER.get();
3212 }
3213 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3214 }
3215
Richard Smith2a7d4812013-05-04 07:00:32 +00003216 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3217 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003218 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003219 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3220 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003221 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003222 FD->setInvalidDecl();
3223 return StmtError();
3224 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003225 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003226 }
3227 }
3228 }
3229
Richard Smithc58f38f2013-08-14 20:16:31 +00003230 bool HasDependentReturnType = FnRetType->isDependentType();
3231
Craig Topperc3ec1492014-05-26 06:22:03 +00003232 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003233 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003234 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003235 if (isa<InitListExpr>(RetValExp)) {
3236 // We simply never allow init lists as the return value of void
3237 // functions. This is compatible because this was never allowed before,
3238 // so there's no legacy code to deal with.
3239 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3240 int FunctionKind = 0;
3241 if (isa<ObjCMethodDecl>(CurDecl))
3242 FunctionKind = 1;
3243 else if (isa<CXXConstructorDecl>(CurDecl))
3244 FunctionKind = 2;
3245 else if (isa<CXXDestructorDecl>(CurDecl))
3246 FunctionKind = 3;
3247
3248 Diag(ReturnLoc, diag::err_return_init_list)
3249 << CurDecl->getDeclName() << FunctionKind
3250 << RetValExp->getSourceRange();
3251
3252 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003253 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003254 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003255 // C99 6.8.6.4p1 (ext_ since GCC warns)
3256 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003257 if (RetValExp->getType()->isVoidType()) {
3258 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3259 if (isa<CXXConstructorDecl>(CurDecl) ||
3260 isa<CXXDestructorDecl>(CurDecl))
3261 D = diag::err_ctor_dtor_returns_void;
3262 else
3263 D = diag::ext_return_has_void_expr;
3264 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003265 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003266 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003267 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003268 if (Result.isInvalid())
3269 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003271 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003272 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003273 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003274 // return of void in constructor/destructor is illegal in C++.
3275 if (D == diag::err_ctor_dtor_returns_void) {
3276 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3277 Diag(ReturnLoc, D)
3278 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3279 << RetValExp->getSourceRange();
3280 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003281 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003282 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003283 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003284 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003285
3286 int FunctionKind = 0;
3287 if (isa<ObjCMethodDecl>(CurDecl))
3288 FunctionKind = 1;
3289 else if (isa<CXXConstructorDecl>(CurDecl))
3290 FunctionKind = 2;
3291 else if (isa<CXXDestructorDecl>(CurDecl))
3292 FunctionKind = 3;
3293
Nick Lewycky1be750a2011-06-01 07:44:31 +00003294 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003295 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003296 << RetValExp->getSourceRange();
3297 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003298 }
Mike Stump11289f42009-09-09 15:08:12 +00003299
Sebastian Redleef474c2012-02-22 10:50:08 +00003300 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003301 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3302 if (ER.isInvalid())
3303 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003304 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003305 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003309 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003310 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003311
David Majnemer2887ad32014-12-13 08:12:56 +00003312 unsigned DiagID;
3313 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3314 // C++11 [stmt.return]p2
3315 DiagID = diag::err_constexpr_return_missing_expr;
3316 FD->setInvalidDecl();
3317 } else if (getLangOpts().C99) {
3318 // C99 6.8.6.4p1 (ext_ since GCC warns)
3319 DiagID = diag::ext_return_missing_expr;
3320 } else {
3321 // C90 6.6.6.4p4
3322 DiagID = diag::warn_return_missing_expr;
3323 }
3324
3325 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003326 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003327 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003328 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003329
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003330 Result = new (Context) ReturnStmt(ReturnLoc);
3331 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003332 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003333 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003334
3335 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3336
3337 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3338 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3339 // function return.
3340
3341 // In C++ the return statement is handled via a copy initialization,
3342 // the C version of which boils down to CheckSingleAssignmentConstraints.
3343 if (RetValExp)
3344 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003345 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003346 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003348 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003349 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003351 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003352 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003353 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003354 return StmtError();
3355 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003356 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003357
3358 // If we have a related result type, we need to implicitly
3359 // convert back to the formal result type. We can't pretend to
3360 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003361 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003362 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003363 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3364 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003365 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3366 if (Res.isInvalid()) {
3367 // FIXME: Clean up temporaries here anyway?
3368 return StmtError();
3369 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003370 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003371 }
3372
Artyom Skrobov9f213442014-01-24 11:10:39 +00003373 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3374 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376
John McCallacf0ee52010-10-08 02:01:28 +00003377 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003378 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3379 if (ER.isInvalid())
3380 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003381 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003382 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003383 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385
3386 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003387 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003388 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003389 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003390
Richard Smith9f690bd2015-10-27 06:02:45 +00003391 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3392 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3393
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003394 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003395}
3396
John McCalldadc5752010-08-24 06:29:42 +00003397StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003398Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003399 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003400 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003401 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003402 if (Var && Var->isInvalidDecl())
3403 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003405 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003406}
3407
John McCalldadc5752010-08-24 06:29:42 +00003408StmtResult
John McCallb268a282010-08-23 23:25:46 +00003409Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003410 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003411}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003412
John McCalldadc5752010-08-24 06:29:42 +00003413StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003415 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003416 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003417 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3418
John McCallaab3e412010-08-25 08:40:02 +00003419 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003420 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003421 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3422 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003423}
3424
John McCall0bd3e402012-05-08 21:41:25 +00003425StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003426 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003427 ExprResult Result = DefaultLvalueConversion(Throw);
3428 if (Result.isInvalid())
3429 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003430
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003431 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003432 if (Result.isInvalid())
3433 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003434 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003435
Douglas Gregor2900c162010-04-22 21:44:01 +00003436 QualType ThrowType = Throw->getType();
3437 // Make sure the expression type is an ObjC pointer or "void *".
3438 if (!ThrowType->isDependentType() &&
3439 !ThrowType->isObjCObjectPointerType()) {
3440 const PointerType *PT = ThrowType->getAs<PointerType>();
3441 if (!PT || !PT->getPointeeType()->isVoidType())
3442 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3443 << Throw->getType() << Throw->getSourceRange());
3444 }
3445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003447 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003448}
3449
John McCalldadc5752010-08-24 06:29:42 +00003450StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003452 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003453 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003454 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3455
John McCallb268a282010-08-23 23:25:46 +00003456 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003457 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003458 // in the context of an @catch clause).
3459 Scope *AtCatchParent = CurScope;
3460 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3461 AtCatchParent = AtCatchParent->getParent();
3462 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003463 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464 }
John McCallb268a282010-08-23 23:25:46 +00003465 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003466}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003467
John McCalld9bb7432011-07-27 21:50:02 +00003468ExprResult
3469Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3470 ExprResult result = DefaultLvalueConversion(operand);
3471 if (result.isInvalid())
3472 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003473 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003474
3475 // Make sure the expression type is an ObjC pointer or "void *".
3476 QualType type = operand->getType();
3477 if (!type->isDependentType() &&
3478 !type->isObjCObjectPointerType()) {
3479 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003480 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3481 if (getLangOpts().CPlusPlus) {
3482 if (RequireCompleteType(atLoc, type,
3483 diag::err_incomplete_receiver_type))
3484 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3485 << type << operand->getSourceRange();
3486
3487 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3488 if (!result.isUsable())
3489 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3490 << type << operand->getSourceRange();
3491
3492 operand = result.get();
3493 } else {
3494 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3495 << type << operand->getSourceRange();
3496 }
3497 }
John McCalld9bb7432011-07-27 21:50:02 +00003498 }
3499
3500 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003501 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003502}
3503
John McCalldadc5752010-08-24 06:29:42 +00003504StmtResult
John McCallb268a282010-08-23 23:25:46 +00003505Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3506 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003507 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003508 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003509 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003510}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003511
3512/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3513/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003514StmtResult
John McCall48871652010-08-21 09:40:31 +00003515Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003516 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003517 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003518 return new (Context)
3519 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003520}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003521
John McCall31168b02011-06-15 23:02:42 +00003522StmtResult
3523Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3524 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003525 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003526}
3527
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003528namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003529class CatchHandlerType {
3530 QualType QT;
3531 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003532
Aaron Ballman8aee642902015-04-08 00:05:29 +00003533 // This is a special constructor to be used only with DenseMapInfo's
3534 // getEmptyKey() and getTombstoneKey() functions.
3535 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3536 enum Unique { ForDenseMap };
3537 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3538
Sebastian Redl63c4da02009-07-29 17:15:45 +00003539public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003540 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003541 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003542 /// level pointer and cv-qualifiers.
3543 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3544 if (QT->isPointerType())
3545 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003546
Aaron Ballman8aee642902015-04-08 00:05:29 +00003547 if (IsPointer || QT->isReferenceType())
3548 QT = QT->getPointeeType();
3549 QT = QT.getUnqualifiedType();
3550 }
3551
3552 /// Used when creating a CatchHandlerType from a base class type; pretends the
3553 /// type passed in had the pointer qualifier, does not need to get an
3554 /// unqualified type.
3555 CatchHandlerType(QualType QT, bool IsPointer)
3556 : QT(QT), IsPointer(IsPointer) {}
3557
3558 QualType underlying() const { return QT; }
3559 bool isPointer() const { return IsPointer; }
3560
3561 friend bool operator==(const CatchHandlerType &LHS,
3562 const CatchHandlerType &RHS) {
3563 // If the pointer qualification does not match, we can return early.
3564 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003565 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003566 // Otherwise, check the underlying type without cv-qualifiers.
3567 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003568 }
3569};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003570} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003571
Aaron Ballman8aee642902015-04-08 00:05:29 +00003572namespace llvm {
3573template <> struct DenseMapInfo<CatchHandlerType> {
3574 static CatchHandlerType getEmptyKey() {
3575 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3576 CatchHandlerType::ForDenseMap);
3577 }
3578
3579 static CatchHandlerType getTombstoneKey() {
3580 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3581 CatchHandlerType::ForDenseMap);
3582 }
3583
3584 static unsigned getHashValue(const CatchHandlerType &Base) {
3585 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3586 }
3587
3588 static bool isEqual(const CatchHandlerType &LHS,
3589 const CatchHandlerType &RHS) {
3590 return LHS == RHS;
3591 }
3592};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003593}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003594
3595namespace {
3596class CatchTypePublicBases {
3597 ASTContext &Ctx;
3598 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3599 const bool CheckAgainstPointer;
3600
3601 CXXCatchStmt *FoundHandler;
3602 CanQualType FoundHandlerType;
3603
3604public:
3605 CatchTypePublicBases(
3606 ASTContext &Ctx,
3607 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3608 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3609 FoundHandler(nullptr) {}
3610
3611 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3612 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3613
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003614 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003615 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003616 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003617 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003618 auto I = M.find(Check);
3619 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003620 FoundHandler = I->second;
3621 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003622 return true;
3623 }
3624 }
3625 return false;
3626 }
3627};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003628}
Dan Gohman28ade552010-07-26 21:25:24 +00003629
Sebastian Redl9b244a82008-12-22 21:35:02 +00003630/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3631/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003632StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3633 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003634 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003635 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003636 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003637 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003638
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003639 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3640 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3641
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003642 sema::FunctionScopeInfo *FSI = getCurFunction();
3643
Reid Klecknere7175912015-02-02 22:15:31 +00003644 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003645 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003646 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003647 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003648 }
3649
Robert Wilhelmcafda822013-08-22 09:20:03 +00003650 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003651 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003652 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003653
Aaron Ballman8aee642902015-04-08 00:05:29 +00003654 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003655 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003656 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003657
Aaron Ballman8aee642902015-04-08 00:05:29 +00003658 // Diagnose when the handler is a catch-all handler, but it isn't the last
3659 // handler for the try block. [except.handle]p5. Also, skip exception
3660 // declarations that are invalid, since we can't usefully report on them.
3661 if (!H->getExceptionDecl()) {
3662 if (i < NumHandlers - 1)
3663 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003664 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003665 } else if (H->getExceptionDecl()->isInvalidDecl())
3666 continue;
3667
3668 // Walk the type hierarchy to diagnose when this type has already been
3669 // handled (duplication), or cannot be handled (derivation inversion). We
3670 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003671 CatchHandlerType HandlerCHT =
3672 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003673
3674 // We can ignore whether the type is a reference or a pointer; we need the
3675 // underlying declaration type in order to get at the underlying record
3676 // decl, if there is one.
3677 QualType Underlying = HandlerCHT.underlying();
3678 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3679 if (!RD->hasDefinition())
3680 continue;
3681 // Check that none of the public, unambiguous base classes are in the
3682 // map ([except.handle]p1). Give the base classes the same pointer
3683 // qualification as the original type we are basing off of. This allows
3684 // comparison against the handler type using the same top-level pointer
3685 // as the original type.
3686 CXXBasePaths Paths;
3687 Paths.setOrigin(RD);
3688 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003689 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003690 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3691 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3692 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3693 diag::warn_exception_caught_by_earlier_handler)
3694 << H->getCaughtType();
3695 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3696 diag::note_previous_exception_handler)
3697 << Problem->getCaughtType();
3698 }
3699 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
Aaron Ballman8aee642902015-04-08 00:05:29 +00003702 // Add the type the list of ones we have handled; diagnose if we've already
3703 // handled it.
3704 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3705 if (!R.second) {
3706 const CXXCatchStmt *Problem = R.first->second;
3707 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3708 diag::warn_exception_caught_by_earlier_handler)
3709 << H->getCaughtType();
3710 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3711 diag::note_previous_exception_handler)
3712 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003713 }
3714 }
Mike Stump11289f42009-09-09 15:08:12 +00003715
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003716 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003717
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003718 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003719}
John Wiegley1c0675e2011-04-28 01:08:34 +00003720
Reid Klecknere7175912015-02-02 22:15:31 +00003721StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3722 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003723 assert(TryBlock && Handler);
3724
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003725 sema::FunctionScopeInfo *FSI = getCurFunction();
3726
Reid Klecknere7175912015-02-02 22:15:31 +00003727 // SEH __try is incompatible with C++ try. Borland appears to support this,
3728 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003729 if (!getLangOpts().Borland) {
3730 if (FSI->FirstCXXTryLoc.isValid()) {
3731 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3732 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3733 }
Reid Klecknere7175912015-02-02 22:15:31 +00003734 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003735
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003736 FSI->setHasSEHTry(TryLoc);
3737
3738 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3739 // track if they use SEH.
3740 DeclContext *DC = CurContext;
3741 while (DC && !DC->isFunctionOrMethod())
3742 DC = DC->getParent();
3743 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3744 if (FD)
3745 FD->setUsesSEHTry(true);
3746 else
3747 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003748
Reid Kleckner8819a402015-07-10 00:16:25 +00003749 // Reject __try on unsupported targets.
3750 if (!Context.getTargetInfo().isSEHTrySupported())
3751 Diag(TryLoc, diag::err_seh_try_unsupported);
3752
Reid Klecknere7175912015-02-02 22:15:31 +00003753 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003754}
3755
3756StmtResult
3757Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3758 Expr *FilterExpr,
3759 Stmt *Block) {
3760 assert(FilterExpr && Block);
3761
3762 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003763 return StmtError(Diag(FilterExpr->getExprLoc(),
3764 diag::err_filter_expression_integral)
3765 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003766 }
3767
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003768 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003769}
3770
Nico Weberd64657f2015-03-09 02:47:59 +00003771void Sema::ActOnStartSEHFinallyBlock() {
3772 CurrentSEHFinally.push_back(CurScope);
3773}
3774
Nico Weberce903292015-03-09 03:17:15 +00003775void Sema::ActOnAbortSEHFinallyBlock() {
3776 CurrentSEHFinally.pop_back();
3777}
3778
Nico Weberd64657f2015-03-09 02:47:59 +00003779StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003780 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003781 CurrentSEHFinally.pop_back();
3782 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003783}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003784
Nico Weberc7d05962014-07-06 22:32:59 +00003785StmtResult
3786Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003787 Scope *SEHTryParent = CurScope;
3788 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3789 SEHTryParent = SEHTryParent->getParent();
3790 if (!SEHTryParent)
3791 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003792 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003793
Nico Weber9b982072014-07-07 00:12:30 +00003794 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003795}
3796
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003797StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3798 bool IsIfExists,
3799 NestedNameSpecifierLoc QualifierLoc,
3800 DeclarationNameInfo NameInfo,
3801 Stmt *Nested)
3802{
3803 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003804 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003805 cast<CompoundStmt>(Nested));
3806}
3807
3808
Chad Rosier02a84392012-08-10 17:56:09 +00003809StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003810 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003811 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003812 UnqualifiedId &Name,
3813 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003814 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003815 SS.getWithLocInContext(Context),
3816 GetNameFromUnqualifiedId(Name),
3817 Nested);
3818}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003819
3820RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003821Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3822 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003823 DeclContext *DC = CurContext;
3824 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3825 DC = DC->getParent();
3826
Craig Topperc3ec1492014-05-26 06:22:03 +00003827 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003828 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003829 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3830 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003831 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003832 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003833
Alexey Bataev330de032014-10-29 12:21:55 +00003834 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003835 DC->addDecl(RD);
3836 RD->setImplicit();
3837 RD->startDefinition();
3838
Alexey Bataev9959db52014-05-06 10:08:46 +00003839 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003840 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003841 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003842 return RD;
3843}
3844
3845static void buildCapturedStmtCaptureList(
3846 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3847 SmallVectorImpl<Expr *> &CaptureInits,
3848 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3849
3850 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3851 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3852
3853 if (Cap->isThisCapture()) {
3854 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3855 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003856 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003857 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003858 } else if (Cap->isVLATypeCapture()) {
3859 Captures.push_back(
3860 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3861 CaptureInits.push_back(nullptr);
3862 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003863 }
3864
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003865 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003866 Cap->isReferenceCapture()
3867 ? CapturedStmt::VCK_ByRef
3868 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003869 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003870 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003871 }
3872}
3873
3874void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003875 CapturedRegionKind Kind,
3876 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003877 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003878 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003879
Alexey Bataev9959db52014-05-06 10:08:46 +00003880 // Build the context parameter
3881 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3882 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3883 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3884 ImplicitParamDecl *Param
3885 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3886 DC->addDecl(Param);
3887
3888 CD->setContextParam(0, Param);
3889
3890 // Enter the capturing scope for this captured region.
3891 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3892
3893 if (CurScope)
3894 PushDeclContext(CurScope, CD);
3895 else
3896 CurContext = CD;
3897
3898 PushExpressionEvaluationContext(PotentiallyEvaluated);
3899}
3900
3901void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3902 CapturedRegionKind Kind,
3903 ArrayRef<CapturedParamNameType> Params) {
3904 CapturedDecl *CD = nullptr;
3905 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3906
3907 // Build the context parameter
3908 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3909 bool ContextIsFound = false;
3910 unsigned ParamNum = 0;
3911 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3912 E = Params.end();
3913 I != E; ++I, ++ParamNum) {
3914 if (I->second.isNull()) {
3915 assert(!ContextIsFound &&
3916 "null type has been found already for '__context' parameter");
3917 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3918 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3919 ImplicitParamDecl *Param
3920 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3921 DC->addDecl(Param);
3922 CD->setContextParam(ParamNum, Param);
3923 ContextIsFound = true;
3924 } else {
3925 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3926 ImplicitParamDecl *Param
3927 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3928 DC->addDecl(Param);
3929 CD->setParam(ParamNum, Param);
3930 }
3931 }
3932 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003933 if (!ContextIsFound) {
3934 // Add __context implicitly if it is not specified.
3935 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3936 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3937 ImplicitParamDecl *Param =
3938 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3939 DC->addDecl(Param);
3940 CD->setContextParam(ParamNum, Param);
3941 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003942 // Enter the capturing scope for this captured region.
3943 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3944
3945 if (CurScope)
3946 PushDeclContext(CurScope, CD);
3947 else
3948 CurContext = CD;
3949
3950 PushExpressionEvaluationContext(PotentiallyEvaluated);
3951}
3952
Wei Pan17fbf6e2013-05-04 03:59:06 +00003953void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003954 DiscardCleanupsInEvaluationContext();
3955 PopExpressionEvaluationContext();
3956
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003957 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3958 RecordDecl *Record = RSI->TheRecordDecl;
3959 Record->setInvalidDecl();
3960
Aaron Ballman62e47c42014-03-10 13:43:55 +00003961 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003962 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3963 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003964
Wei Pan17fbf6e2013-05-04 03:59:06 +00003965 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003966 PopFunctionScopeInfo();
3967}
3968
3969StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3970 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3971
3972 SmallVector<CapturedStmt::Capture, 4> Captures;
3973 SmallVector<Expr *, 4> CaptureInits;
3974 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3975
3976 CapturedDecl *CD = RSI->TheCapturedDecl;
3977 RecordDecl *RD = RSI->TheRecordDecl;
3978
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003979 CapturedStmt *Res = CapturedStmt::Create(
3980 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
3981 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003982
3983 CD->setBody(Res->getCapturedStmt());
3984 RD->completeDefinition();
3985
Wei Pan17fbf6e2013-05-04 03:59:06 +00003986 DiscardCleanupsInEvaluationContext();
3987 PopExpressionEvaluationContext();
3988
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003989 PopDeclContext();
3990 PopFunctionScopeInfo();
3991
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003992 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003993}