blob: fec12000950c8a3027bde52dd7c4e6e04f011d13 [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"
Chris Lattneraf8d5812006-11-10 05:07:45 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000042
Richard Smith945f8d32013-01-14 22:39:08 +000043StmtResult Sema::ActOnExprStmt(ExprResult FE) {
44 if (FE.isInvalid())
45 return StmtError();
46
47 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
48 /*DiscardedValue*/ true);
49 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000050 return StmtError();
51
Chris Lattner903eb512008-07-25 23:18:17 +000052 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
53 // void expression for its side effects. Conversion to void allows any
54 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000055
Chris Lattner903eb512008-07-25 23:18:17 +000056 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000057 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000058}
59
60
John McCalleaef89b2013-03-22 02:10:40 +000061StmtResult Sema::ActOnExprStmtError() {
62 DiscardCleanupsInEvaluationContext();
63 return StmtError();
64}
65
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000066StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000067 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000068 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000069}
70
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000071StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
72 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000073 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnercbafe8d2009-04-12 20:13:14 +000075 // If we have an invalid decl, just return an error.
76 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000077
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000078 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000079}
Chris Lattneraf8d5812006-11-10 05:07:45 +000080
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000081void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000082 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000083
Douglas Gregor2eb1c572013-04-08 20:52:24 +000084 // If we don't have a declaration, or we have an invalid declaration,
85 // just return.
86 if (DG.isNull() || !DG.isSingleDecl())
87 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000088
Douglas Gregor2eb1c572013-04-08 20:52:24 +000089 Decl *decl = DG.getSingleDecl();
90 if (!decl || decl->isInvalidDecl())
91 return;
92
93 // Only variable declarations are permitted.
94 VarDecl *var = dyn_cast<VarDecl>(decl);
95 if (!var) {
96 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
97 decl->setInvalidDecl();
98 return;
99 }
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // foreach variables are never actually initialized in the way that
102 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000103 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000104
John McCalld4631322011-06-17 06:42:21 +0000105 // In ARC, we don't need to retain the iteration variable of a fast
106 // enumeration loop. Rather than actually trying to catch that
107 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000108 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000109 QualType type = var->getType();
110
111 // Only do this if we inferred the lifetime. Inferred lifetime
112 // will show up as a local qualifier because explicit lifetime
113 // should have shown up as an AttributedType instead.
114 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
115 // Add 'const' and mark the variable as pseudo-strong.
116 var->setType(type.withConst());
117 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000118 }
119 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000120}
121
Richard Trieu99e1c952014-03-11 03:11:08 +0000122/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
123/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124///
125/// Adding a cast to void (or other expression wrappers) will prevent the
126/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000127static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000128 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000129 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
131 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000132 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000133 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000134
Richard Trieu99e1c952014-03-11 03:11:08 +0000135 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000136 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000137 IsNotEqual = Op->getOpcode() == BO_NE;
138 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000139 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000140 switch (Op->getOperator()) {
141 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000142 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000143 case OO_EqualEqual:
144 case OO_ExclaimEqual:
145 IsRelational = false;
146 break;
147 case OO_Less:
148 case OO_Greater:
149 case OO_GreaterEqual:
150 case OO_LessEqual:
151 IsRelational = true;
152 break;
153 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000156 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
157 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000158 } else {
159 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000160 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000161 }
162
163 // Suppress warnings when the operator, suspicious as it may be, comes from
164 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000165 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000166 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000167
Chandler Carruthe2669392011-08-17 09:34:37 +0000168 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000170
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000171 // If the LHS is a plausible entity to assign to, provide a fixit hint to
172 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000173 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000174 if (IsNotEqual)
175 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
176 << FixItHint::CreateReplacement(Loc, "|=");
177 else
178 S.Diag(Loc, diag::note_equality_comparison_to_assign)
179 << FixItHint::CreateReplacement(Loc, "=");
180 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000181
182 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000183}
184
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000185void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000186 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
187 return DiagnoseUnusedExprResult(Label->getSubStmt());
188
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000189 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000190 if (!E)
191 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000192
193 // If we are in an unevaluated expression context, then there can be no unused
194 // results because the results aren't expected to be used in the first place.
195 if (isUnevaluatedContext())
196 return;
197
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000198 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000199 // In most cases, we don't want to warn if the expression is written in a
200 // macro body, or if the macro comes from a system header. If the offending
201 // expression is a call to a function with the warn_unused_result attribute,
202 // we warn no matter the location. Because of the order in which the various
203 // checks need to happen, we factor out the macro-related test here.
204 bool ShouldSuppress =
205 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
206 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000207
Eli Friedmanc11535c2012-05-24 00:47:05 +0000208 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000209 SourceLocation Loc;
210 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000211 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner6dc7e572012-08-31 22:39:21 +0000214 // If this is a GNU statement expression expanded from a macro, it is probably
215 // unused because it is a function-like macro that can be used as either an
216 // expression or statement. Don't warn, because it is almost certainly a
217 // false positive.
218 if (isa<StmtExpr>(E) && Loc.isMacroID())
219 return;
220
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000221 // Okay, we have an unused result. Depending on what the base expression is,
222 // we might want to make a more specific diagnostic. Check for one of these
223 // cases now.
224 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000225 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000226 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000227 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
228 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000229
Chandler Carruthe2669392011-08-17 09:34:37 +0000230 if (DiagnoseUnusedComparison(*this, E))
231 return;
232
Eli Friedmanc11535c2012-05-24 00:47:05 +0000233 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000234 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000235 if (E->getType()->isVoidType())
236 return;
237
Chris Lattner1a6babf2009-10-13 04:53:48 +0000238 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000239 // a more specific message to make it clear what is happening. If the call
240 // is written in a macro body, only warn if it has the warn_unused_result
241 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000242 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +0000243 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
244 if (Func ? Func->hasUnusedResultAttr()
245 : FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000246 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000247 return;
248 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 if (ShouldSuppress)
250 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000251 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000252 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
253 return;
254 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000255 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000256 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
257 return;
258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000260 } else if (ShouldSuppress)
261 return;
262
263 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000264 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000265 Diag(Loc, diag::err_arc_unused_init_message) << R1;
266 return;
267 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000268 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000269 if (MD) {
270 if (MD->hasAttr<WarnUnusedResultAttr>()) {
271 Diag(Loc, diag::warn_unused_result) << R1 << R2;
272 return;
273 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000274 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000275 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
276 const Expr *Source = POE->getSyntacticForm();
277 if (isa<ObjCSubscriptRefExpr>(Source))
278 DiagID = diag::warn_unused_container_subscript_expr;
279 else
280 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000281 } else if (const CXXFunctionalCastExpr *FC
282 = dyn_cast<CXXFunctionalCastExpr>(E)) {
283 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
284 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
285 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000286 }
John McCall2351cb92010-04-06 22:24:14 +0000287 // Diagnose "(void*) blah" as a typo for "(void) blah".
288 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
289 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
290 QualType T = TI->getType();
291
292 // We really do want to use the non-canonical type here.
293 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000294 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000295
296 Diag(Loc, diag::warn_unused_voidptr)
297 << FixItHint::CreateRemoval(TL.getStarLoc());
298 return;
299 }
300 }
301
Eli Friedmanc11535c2012-05-24 00:47:05 +0000302 if (E->isGLValue() && E->getType().isVolatileQualified()) {
303 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
304 return;
305 }
306
Craig Topperc3ec1492014-05-26 06:22:03 +0000307 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000308}
309
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000310void Sema::ActOnStartOfCompoundStmt() {
311 PushCompoundScope();
312}
313
314void Sema::ActOnFinishOfCompoundStmt() {
315 PopCompoundScope();
316}
317
318sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
319 return getCurFunction()->CompoundScopes.back();
320}
321
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000322StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
323 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
324 const unsigned NumElts = Elts.size();
325
Chris Lattnerd864daf2007-08-27 04:29:41 +0000326 // If we're in C89 mode, check that we don't have any decls after stmts. If
327 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000328 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000329 // Note that __extension__ can be around a decl.
330 unsigned i = 0;
331 // Skip over all declarations.
332 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
333 /*empty*/;
334
335 // We found the end of the list or a statement. Scan for another declstmt.
336 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
337 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000340 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000341 Diag(D->getLocation(), diag::ext_mixed_decls_code);
342 }
343 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000344 // Warn about unused expressions in statements.
345 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000346 // Ignore statements that are last in a statement expression.
347 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000348 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000349
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000350 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000351 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000352
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000353 // Check for suspicious empty body (null statement) in `for' and `while'
354 // statements. Don't do anything for template instantiations, this just adds
355 // noise.
356 if (NumElts != 0 && !CurrentInstantiationScope &&
357 getCurCompoundScope().HasEmptyLoopBodies) {
358 for (unsigned i = 0; i != NumElts - 1; ++i)
359 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
360 }
361
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000362 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000363}
364
John McCalldadc5752010-08-24 06:29:42 +0000365StmtResult
John McCallb268a282010-08-23 23:25:46 +0000366Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
367 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000368 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000369 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000370
John McCallaab3e412010-08-25 08:40:02 +0000371 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000372 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000373 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000374 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000375
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000376 ExprResult LHS =
377 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
378 if (!getLangOpts().CPlusPlus11)
379 return VerifyIntegerConstantExpression(E);
380 if (Expr *CondExpr =
381 getCurFunction()->SwitchStack.back()->getCond()) {
382 QualType CondType = CondExpr->getType();
383 llvm::APSInt TempVal;
384 return CheckConvertedConstantExpression(E, CondType, TempVal,
385 CCEK_CaseValue);
386 }
387 return ExprError();
388 });
389 if (LHS.isInvalid())
390 return StmtError();
391 LHSVal = LHS.get();
392
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000393 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000394 // C99 6.8.4.2p3: The expression shall be an integer constant.
395 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000396 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000397 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000398 if (!LHSVal)
399 return StmtError();
400 }
Richard Smithf8379a02012-01-18 23:55:52 +0000401
402 // GCC extension: The expression shall be an integer constant.
403
Richard Smithf4c51d92012-02-04 09:53:13 +0000404 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000405 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000406 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000407 }
408 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000409
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000410 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000411 getLangOpts().CPlusPlus11);
412 if (LHS.isInvalid())
413 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000414
Richard Smith5b555da2014-11-20 01:24:12 +0000415 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
416 getLangOpts().CPlusPlus11)
417 : ExprResult();
418 if (RHS.isInvalid())
419 return StmtError();
420
421 CaseStmt *CS = new (Context)
422 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000423 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000424 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000425}
426
Chris Lattner34a22092009-03-04 04:23:07 +0000427/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000428void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000429 DiagnoseUnusedExprResult(SubStmt);
430
Chris Lattner34a22092009-03-04 04:23:07 +0000431 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000432 CS->setSubStmt(SubStmt);
433}
434
John McCalldadc5752010-08-24 06:29:42 +0000435StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000436Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000437 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000438 DiagnoseUnusedExprResult(SubStmt);
439
John McCallaab3e412010-08-25 08:40:02 +0000440 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000441 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000442 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000443 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000444
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000445 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000446 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000447 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000448}
449
John McCalldadc5752010-08-24 06:29:42 +0000450StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000451Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
452 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000453 // If the label was multiply defined, reject it now.
454 if (TheDecl->getStmt()) {
455 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
456 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000458 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000459
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000460 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000461 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
462 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000463 if (!TheDecl->isGnuLocal()) {
464 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000465 if (!TheDecl->isMSAsmLabel()) {
466 // Don't update the location of MS ASM labels. These will result in
467 // a diagnostic, and changing the location here will mess that up.
468 TheDecl->setLocation(IdentLoc);
469 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000470 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000471 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000472}
473
Richard Smithc202b282012-04-14 00:33:13 +0000474StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000475 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000476 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000477 // Fill in the declaration and return it.
478 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000479 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000480}
481
John McCalldadc5752010-08-24 06:29:42 +0000482StmtResult
John McCall48871652010-08-21 09:40:31 +0000483Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000484 Stmt *thenStmt, SourceLocation ElseLoc,
485 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000486 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000487
Craig Topperc3ec1492014-05-26 06:22:03 +0000488 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000489 if (CondVar) {
490 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000491 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +0000492 CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
Douglas Gregor633caca2009-11-23 23:44:04 +0000493 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000494 Expr *ConditionExpr = CondResult.getAs<Expr>();
Olivier Goffart122993b2015-10-11 17:27:29 +0000495 if (ConditionExpr) {
496 DiagnoseUnusedExprResult(thenStmt);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
Olivier Goffart122993b2015-10-11 17:27:29 +0000498 if (!elseStmt) {
499 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
500 diag::warn_empty_if_body);
501 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000502
Olivier Goffart122993b2015-10-11 17:27:29 +0000503 DiagnoseUnusedExprResult(elseStmt);
504 } else {
505 // Create a dummy Expr for the condition for error recovery
506 ConditionExpr = new (Context) OpaqueValueExpr(SourceLocation(),
507 Context.BoolTy, VK_RValue);
Anders Carlssondb83d772007-10-10 20:50:11 +0000508 }
509
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000510 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
511 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000512}
Steve Naroff86272ea2007-05-29 02:14:17 +0000513
Chris Lattner67998452007-08-23 18:29:20 +0000514namespace {
515 struct CaseCompareFunctor {
516 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
517 const llvm::APSInt &RHS) {
518 return LHS.first < RHS;
519 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000520 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
521 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
522 return LHS.first < RHS.first;
523 }
Chris Lattner67998452007-08-23 18:29:20 +0000524 bool operator()(const llvm::APSInt &LHS,
525 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
526 return LHS < RHS.first;
527 }
528 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000529}
Chris Lattner67998452007-08-23 18:29:20 +0000530
Chris Lattner4b2ff022007-09-21 18:15:22 +0000531/// CmpCaseVals - Comparison predicate for sorting case values.
532///
533static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
534 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
535 if (lhs.first < rhs.first)
536 return true;
537
538 if (lhs.first == rhs.first &&
539 lhs.second->getCaseLoc().getRawEncoding()
540 < rhs.second->getCaseLoc().getRawEncoding())
541 return true;
542 return false;
543}
544
Douglas Gregorbd6839732010-02-08 22:24:16 +0000545/// CmpEnumVals - Comparison predicate for sorting enumeration values.
546///
547static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
548 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
549{
550 return lhs.first < rhs.first;
551}
552
553/// EqEnumVals - Comparison preficate for uniqing enumeration values.
554///
555static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
556 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
557{
558 return lhs.first == rhs.first;
559}
560
Chris Lattnera96d4272009-10-16 16:45:22 +0000561/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
562/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000563static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
564 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
565 expr = cleanups->getSubExpr();
566 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
567 if (impcast->getCastKind() != CK_IntegralCast) break;
568 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000569 }
570 return expr->getType();
571}
572
John McCalldadc5752010-08-24 06:29:42 +0000573StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000575 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000576 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000577
Craig Topperc3ec1492014-05-26 06:22:03 +0000578 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000579 if (CondVar) {
580 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000581 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
582 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000583 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000585 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
John McCallb268a282010-08-23 23:25:46 +0000588 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000589 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregore2b37442012-05-04 22:38:52 +0000591 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
592 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000593
Douglas Gregore2b37442012-05-04 22:38:52 +0000594 public:
595 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000596 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
597 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000598
Craig Toppere14c0f82014-03-12 04:55:44 +0000599 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
600 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000601 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
602 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000603
Craig Toppere14c0f82014-03-12 04:55:44 +0000604 SemaDiagnosticBuilder diagnoseIncomplete(
605 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000606 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
607 << T << Cond->getSourceRange();
608 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000609
Craig Toppere14c0f82014-03-12 04:55:44 +0000610 SemaDiagnosticBuilder diagnoseExplicitConv(
611 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000612 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
613 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000614
Craig Toppere14c0f82014-03-12 04:55:44 +0000615 SemaDiagnosticBuilder noteExplicitConv(
616 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000617 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
618 << ConvTy->isEnumeralType() << ConvTy;
619 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000620
Craig Toppere14c0f82014-03-12 04:55:44 +0000621 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
622 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000623 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
624 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000625
Craig Toppere14c0f82014-03-12 04:55:44 +0000626 SemaDiagnosticBuilder noteAmbiguous(
627 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000628 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
629 << ConvTy->isEnumeralType() << ConvTy;
630 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000631
Craig Toppere14c0f82014-03-12 04:55:44 +0000632 SemaDiagnosticBuilder diagnoseConversion(
633 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000634 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000635 }
636 } SwitchDiagnoser(Cond);
637
Richard Smithccc11812013-05-21 19:05:48 +0000638 CondResult =
639 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000640 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000641 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
John McCall5939b162011-08-06 07:30:58 +0000643 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
644 CondResult = UsualUnaryConversions(Cond);
645 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000646 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000647
Meador Ingef0af05c2015-06-25 22:06:40 +0000648 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
649 if (CondResult.isInvalid())
650 return StmtError();
651 Cond = CondResult.get();
John McCalla95172b2010-08-01 00:26:45 +0000652
John McCallaab3e412010-08-25 08:40:02 +0000653 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
John McCallb268a282010-08-23 23:25:46 +0000655 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000656 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000657 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000658}
659
Gabor Greif16e02862010-10-01 22:05:14 +0000660static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000661 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000662 Val.setIsSigned(IsSigned);
663}
664
Richard Smith077d0832014-08-04 00:40:48 +0000665/// Check the specified case value is in range for the given unpromoted switch
666/// type.
667static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
668 unsigned UnpromotedWidth, bool UnpromotedSign) {
669 // If the case value was signed and negative and the switch expression is
670 // unsigned, don't bother to warn: this is implementation-defined behavior.
671 // FIXME: Introduce a second, default-ignored warning for this case?
672 if (UnpromotedWidth < Val.getBitWidth()) {
673 llvm::APSInt ConvVal(Val);
674 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
675 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
676 // FIXME: Use different diagnostics for overflow in conversion to promoted
677 // type versus "switch expression cannot have this value". Use proper
678 // IntRange checking rather than just looking at the unpromoted type here.
679 if (ConvVal != Val)
680 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
681 << ConvVal.toString(10);
682 }
683}
684
Alexis Hunt724f14e2014-11-28 00:53:20 +0000685typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
686
Dmitri Gribenko58683752013-12-05 22:52:07 +0000687/// Returns true if we should emit a diagnostic about this case expression not
688/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000689static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000690 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000691 const Expr *CaseExpr,
692 EnumValsTy::iterator &EI,
693 EnumValsTy::iterator &EIEnd,
694 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000695 if (const DeclRefExpr *DRE =
696 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000697 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000698 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000699 QualType EnumType = S.Context.getTypeDeclType(ED);
700 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
701 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000702 return false;
703 }
704 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000705
Richard Smith332653c2015-09-04 01:03:03 +0000706 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000707 return !S.IsValueInFlagEnum(ED, Val, false);
708 } else {
709 while (EI != EIEnd && EI->first < Val)
710 EI++;
711
712 if (EI != EIEnd && EI->first == Val)
713 return false;
714 }
715
Dmitri Gribenko58683752013-12-05 22:52:07 +0000716 return true;
717}
718
John McCalldadc5752010-08-24 06:29:42 +0000719StmtResult
John McCallb268a282010-08-23 23:25:46 +0000720Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
721 Stmt *BodyStmt) {
722 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000723 assert(SS == getCurFunction()->SwitchStack.back() &&
724 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000725
David Majnemer418ad3f2014-12-15 07:46:12 +0000726 getCurFunction()->SwitchStack.pop_back();
727
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000728 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000729 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000730
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000731 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000732 if (!CondExpr) return StmtError();
733
734 QualType CondType = CondExpr->getType();
735
John McCalld3dfbd62010-05-18 03:19:21 +0000736 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000737 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000738 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000739
Chris Lattnera96d4272009-10-16 16:45:22 +0000740 // C++ 6.4.2.p2:
741 // Integral promotions are performed (on the switch condition).
742 //
743 // A case value unrepresentable by the original switch condition
744 // type (before the promotion) doesn't make sense, even when it can
745 // be represented by the promoted type. Therefore we need to find
746 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000747 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000748 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000750 // appropriate type now, just return an error.
751 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000752 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000753
Chris Lattner4ebae652010-04-16 23:34:13 +0000754 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000755 // switch(bool_expr) {...} is often a programmer error, e.g.
756 // switch(n && mask) { ... } // Doh - should be "n & mask".
757 // One can always use an if statement instead of switch(bool_expr).
758 Diag(SwitchLoc, diag::warn_bool_switch_condition)
759 << CondExpr->getSourceRange();
760 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000761 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000762
Richard Smith077d0832014-08-04 00:40:48 +0000763 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000764 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000765 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000766 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000767 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
768 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
769
770 // Get the width and signedness that the condition might actually have, for
771 // warning purposes.
772 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
773 // type.
774 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000775 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000776 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000777 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000778
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000779 // Accumulate all of the case values in a vector so that we can sort them
780 // and detect duplicates. This vector contains the APInt for the case after
781 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000782 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000783 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000785 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000786 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
787 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000788
Craig Topperc3ec1492014-05-26 06:22:03 +0000789 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000790
Chris Lattner10cb5e52007-08-23 06:23:56 +0000791 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000792
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000793 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000794 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000795
Anders Carlsson51873c22007-07-22 07:07:56 +0000796 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000797 if (TheDefaultStmt) {
798 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000799 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000800
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000801 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000802 // we'll return a valid AST. This requires recursing down the AST and
803 // finding it, not something we are set up to do right now. For now,
804 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000805 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000806 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000807 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000809 } else {
810 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000811
Chris Lattnera65e1f32008-01-16 19:17:22 +0000812 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000813
814 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
815 HasDependentValue = true;
816 break;
817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Richard Smithf8379a02012-01-18 23:55:52 +0000819 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000820
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000821 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000822 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
823 // constant expression of the promoted type of the switch condition.
824 ExprResult ConvLo =
825 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
826 if (ConvLo.isInvalid()) {
827 CaseListIsErroneous = true;
828 continue;
829 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000830 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000831 } else {
832 // We already verified that the expression has a i-c-e value (C99
833 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000834 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000835
836 // If the LHS is not the same type as the condition, insert an implicit
837 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000838 Lo = DefaultLvalueConversion(Lo).get();
839 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000840 }
841
Richard Smith077d0832014-08-04 00:40:48 +0000842 // Check the unconverted value is within the range of possible values of
843 // the switch expression.
844 checkCaseValue(*this, Lo->getLocStart(), LoVal,
845 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
846
847 // Convert the value to the same width/sign as the condition.
848 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000849
Chris Lattnera65e1f32008-01-16 19:17:22 +0000850 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattner10cb5e52007-08-23 06:23:56 +0000852 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000853 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000854 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000855 CS->getRHS()->isValueDependent()) {
856 HasDependentValue = true;
857 break;
858 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000859 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000860 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000861 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000862 }
863 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000864
865 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000866 // If we don't have a default statement, check whether the
867 // condition is constant.
868 llvm::APSInt ConstantCondValue;
869 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000870 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000871 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
872 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000873 assert(!HasConstantCond ||
874 (ConstantCondValue.getBitWidth() == CondWidth &&
875 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000876 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000877 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000878
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000879 // Sort all the scalar case values so we can easily detect duplicates.
880 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
881
882 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000883 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
884 if (ShouldCheckConstantCond &&
885 CaseVals[i].first == ConstantCondValue)
886 ShouldCheckConstantCond = false;
887
888 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000889 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000890 // First, determine if either case value has a name
891 StringRef PrevString, CurrString;
892 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
893 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
894 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
895 PrevString = DeclRef->getDecl()->getName();
896 }
897 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
898 CurrString = DeclRef->getDecl()->getName();
899 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000900 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000901 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000902
903 if (PrevString == CurrString)
904 Diag(CaseVals[i].second->getLHS()->getLocStart(),
905 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000906 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000907 else
908 Diag(CaseVals[i].second->getLHS()->getLocStart(),
909 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000910 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
911 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000912 CaseValStr;
913
John McCalld3dfbd62010-05-18 03:19:21 +0000914 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000915 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000916 // FIXME: We really want to remove the bogus case stmt from the
917 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000918 CaseListIsErroneous = true;
919 }
920 }
921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000923 // Detect duplicate case ranges, which usually don't exist at all in
924 // the first place.
925 if (!CaseRanges.empty()) {
926 // Sort all the case ranges by their low value so we can easily detect
927 // overlaps between ranges.
928 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000929
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000930 // Scan the ranges, computing the high values and removing empty ranges.
931 std::vector<llvm::APSInt> HiVals;
932 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000933 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000934 CaseStmt *CR = CaseRanges[i].second;
935 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000936 llvm::APSInt HiVal;
937
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000938 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000939 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
940 // constant expression of the promoted type of the switch condition.
941 ExprResult ConvHi =
942 CheckConvertedConstantExpression(Hi, CondType, HiVal,
943 CCEK_CaseValue);
944 if (ConvHi.isInvalid()) {
945 CaseListIsErroneous = true;
946 continue;
947 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000948 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000949 } else {
950 HiVal = Hi->EvaluateKnownConstInt(Context);
951
952 // If the RHS is not the same type as the condition, insert an
953 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000954 Hi = DefaultLvalueConversion(Hi).get();
955 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000956 }
Mike Stump11289f42009-09-09 15:08:12 +0000957
Richard Smith077d0832014-08-04 00:40:48 +0000958 // Check the unconverted value is within the range of possible values of
959 // the switch expression.
960 checkCaseValue(*this, Hi->getLocStart(), HiVal,
961 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
962
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000963 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000964 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000965
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000966 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000968 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000969 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000970 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
971 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000972 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000973 CaseRanges.erase(CaseRanges.begin()+i);
974 --i, --e;
975 continue;
976 }
John McCalld3dfbd62010-05-18 03:19:21 +0000977
978 if (ShouldCheckConstantCond &&
979 LoVal <= ConstantCondValue &&
980 ConstantCondValue <= HiVal)
981 ShouldCheckConstantCond = false;
982
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000983 HiVals.push_back(HiVal);
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000986 // Rescan the ranges, looking for overlap with singleton values and other
987 // ranges. Since the range list is sorted, we only need to compare case
988 // ranges with their neighbors.
989 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
990 llvm::APSInt &CRLo = CaseRanges[i].first;
991 llvm::APSInt &CRHi = HiVals[i];
992 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000993
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000994 // Check to see whether the case range overlaps with any
995 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000996 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000997 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000999 // Find the smallest value >= the lower bound. If I is in the
1000 // case range, then we have overlap.
1001 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1002 CaseVals.end(), CRLo,
1003 CaseCompareFunctor());
1004 if (I != CaseVals.end() && I->first < CRHi) {
1005 OverlapVal = I->first; // Found overlap with scalar.
1006 OverlapStmt = I->second;
1007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001009 // Find the smallest value bigger than the upper bound.
1010 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1011 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1012 OverlapVal = (I-1)->first; // Found overlap with scalar.
1013 OverlapStmt = (I-1)->second;
1014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001016 // Check to see if this case stmt overlaps with the subsequent
1017 // case range.
1018 if (i && CRLo <= HiVals[i-1]) {
1019 OverlapVal = HiVals[i-1]; // Found overlap with range.
1020 OverlapStmt = CaseRanges[i-1].second;
1021 }
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001023 if (OverlapStmt) {
1024 // If we have a duplicate, report it.
1025 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1026 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001027 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001028 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001029 // FIXME: We really want to remove the bogus case stmt from the
1030 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001031 CaseListIsErroneous = true;
1032 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001033 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001034 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001035
John McCalld3dfbd62010-05-18 03:19:21 +00001036 // Complain if we have a constant condition and we didn't find a match.
1037 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1038 // TODO: it would be nice if we printed enums as enums, chars as
1039 // chars, etc.
1040 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1041 << ConstantCondValue.toString(10)
1042 << CondExpr->getSourceRange();
1043 }
1044
1045 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001046 // values. We only issue a warning if there is not 'default:', but
1047 // we still do the analysis to preserve this information in the AST
1048 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001049 //
Chris Lattner51679082010-09-16 17:09:42 +00001050 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001051
Douglas Gregorbd6839732010-02-08 22:24:16 +00001052 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001053 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001054 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001055 EnumValsTy EnumVals;
1056
John McCalld3dfbd62010-05-18 03:19:21 +00001057 // Gather all enum values, set their type and sort them,
1058 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001059 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001060 llvm::APSInt Val = EDI->getInitVal();
1061 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001062 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001063 }
1064 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001065 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001066 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001067
1068 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001069 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001070 CI != CaseVals.end(); CI++) {
1071 Expr *CaseExpr = CI->second->getLHS();
1072 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1073 CI->first))
1074 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1075 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001076 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001077
David Blaikiee476f972012-01-22 02:31:55 +00001078 // See which of case ranges aren't in enum
1079 EI = EnumVals.begin();
1080 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001081 RI != CaseRanges.end(); RI++) {
1082 Expr *CaseExpr = RI->second->getLHS();
1083 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1084 RI->first))
1085 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1086 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001087
Chad Rosier02a84392012-08-10 17:56:09 +00001088 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001089 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1090 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001091
1092 CaseExpr = RI->second->getRHS();
1093 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1094 Hi))
1095 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1096 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Ted Kremenekc42f3452010-09-09 00:05:53 +00001099 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001100 auto CI = CaseVals.begin();
1101 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001102 bool hasCasesNotInSwitch = false;
1103
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001104 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Alexis Hunt724f14e2014-11-28 00:53:20 +00001106 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001107 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001108 while (CI != CaseVals.end() && CI->first < EI->first)
1109 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
Douglas Gregorbd6839732010-02-08 22:24:16 +00001111 if (CI != CaseVals.end() && CI->first == EI->first)
1112 continue;
1113
Ted Kremenekc42f3452010-09-09 00:05:53 +00001114 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001115 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001116 llvm::APSInt Hi =
1117 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001118 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001119 if (EI->first <= Hi)
1120 break;
1121 }
1122
Ted Kremenekc42f3452010-09-09 00:05:53 +00001123 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001124 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001125 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001126 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128
David Blaikie60ac6382012-01-23 04:46:12 +00001129 if (TheDefaultStmt && UnhandledNames.empty())
1130 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001131
Chris Lattner51679082010-09-16 17:09:42 +00001132 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001133 if (!UnhandledNames.empty()) {
1134 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1135 TheDefaultStmt ? diag::warn_def_missing_case
1136 : diag::warn_missing_case)
1137 << (int)UnhandledNames.size();
1138
1139 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1140 I != E; ++I)
1141 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001142 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001143
1144 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001145 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001146 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001147 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001148
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001149 if (BodyStmt)
1150 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1151 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001152
Mike Stump87c57ac2009-05-16 07:39:55 +00001153 // FIXME: If the case list was broken is some way, we don't have a good system
1154 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001155 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001156 return StmtError();
1157
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001158 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001159}
1160
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001161void
1162Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1163 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001164 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001165 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001166
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001167 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001168 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001169 SrcType->isIntegerType()) {
1170 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1171 SrcExpr->isIntegerConstantExpr(Context)) {
1172 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001173 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001174 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1175
1176 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001177 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001178 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001179
Alexis Hunt724f14e2014-11-28 00:53:20 +00001180 if (ED->hasAttr<FlagEnumAttr>()) {
1181 if (!IsValueInFlagEnum(ED, RhsVal, true))
1182 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001183 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001184 } else {
1185 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1186 EnumValsTy;
1187 EnumValsTy EnumVals;
1188
1189 // Gather all enum values, set their type and sort them,
1190 // allowing easier comparison with rhs constant.
1191 for (auto *EDI : ED->enumerators()) {
1192 llvm::APSInt Val = EDI->getInitVal();
1193 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1194 EnumVals.push_back(std::make_pair(Val, EDI));
1195 }
1196 if (EnumVals.empty())
1197 return;
1198 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1199 EnumValsTy::iterator EIend =
1200 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1201
1202 // See which values aren't in the enum.
1203 EnumValsTy::const_iterator EI = EnumVals.begin();
1204 while (EI != EIend && EI->first < RhsVal)
1205 EI++;
1206 if (EI == EIend || EI->first != RhsVal) {
1207 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1208 << DstType.getUnqualifiedType();
1209 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001210 }
1211 }
1212 }
1213}
1214
John McCalldadc5752010-08-24 06:29:42 +00001215StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001216Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001217 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001218 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001219
Craig Topperc3ec1492014-05-26 06:22:03 +00001220 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001221 if (CondVar) {
1222 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001223 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001224 CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001225 if (CondResult.isInvalid())
1226 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001227 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001228 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001229 if (!ConditionExpr)
1230 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001231 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001232
John McCallb268a282010-08-23 23:25:46 +00001233 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001234
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001235 if (isa<NullStmt>(Body))
1236 getCurCompoundScope().setHasEmptyLoopBodies();
1237
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001238 return new (Context)
1239 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001240}
1241
John McCalldadc5752010-08-24 06:29:42 +00001242StmtResult
John McCallb268a282010-08-23 23:25:46 +00001243Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001244 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001245 Expr *Cond, SourceLocation CondRParen) {
1246 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001247
Serge Pavlov09f99242014-01-23 15:05:00 +00001248 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001249 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001250 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001251 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001252 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001253
Richard Smith945f8d32013-01-14 22:39:08 +00001254 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001255 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001256 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001257 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258
John McCallb268a282010-08-23 23:25:46 +00001259 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001260
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001261 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001262}
1263
Richard Trieu451a5db2012-04-30 18:01:30 +00001264namespace {
1265 // This visitor will traverse a conditional statement and store all
1266 // the evaluated decls into a vector. Simple is set to true if none
1267 // of the excluded constructs are used.
1268 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001269 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001270 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001271 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001272 public:
1273 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001274
Craig Topper4dd9b432014-08-17 23:49:53 +00001275 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001276 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001277 Inherited(S.Context),
1278 Decls(Decls),
1279 Ranges(Ranges),
1280 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001281
Richard Trieu9d228802013-05-31 22:46:45 +00001282 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001283
Richard Trieu9d228802013-05-31 22:46:45 +00001284 // Replaces the method in EvaluatedExprVisitor.
1285 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001286 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001287 }
1288
1289 // Any Stmt not whitelisted will cause the condition to be marked complex.
1290 void VisitStmt(Stmt *S) {
1291 Simple = false;
1292 }
1293
1294 void VisitBinaryOperator(BinaryOperator *E) {
1295 Visit(E->getLHS());
1296 Visit(E->getRHS());
1297 }
1298
1299 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001300 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001301 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001302
Richard Trieu9d228802013-05-31 22:46:45 +00001303 void VisitUnaryOperator(UnaryOperator *E) {
1304 // Skip checking conditionals with derefernces.
1305 if (E->getOpcode() == UO_Deref)
1306 Simple = false;
1307 else
1308 Visit(E->getSubExpr());
1309 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001310
Richard Trieu9d228802013-05-31 22:46:45 +00001311 void VisitConditionalOperator(ConditionalOperator *E) {
1312 Visit(E->getCond());
1313 Visit(E->getTrueExpr());
1314 Visit(E->getFalseExpr());
1315 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001316
Richard Trieu9d228802013-05-31 22:46:45 +00001317 void VisitParenExpr(ParenExpr *E) {
1318 Visit(E->getSubExpr());
1319 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001320
Richard Trieu9d228802013-05-31 22:46:45 +00001321 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1322 Visit(E->getOpaqueValue()->getSourceExpr());
1323 Visit(E->getFalseExpr());
1324 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001325
Richard Trieu9d228802013-05-31 22:46:45 +00001326 void VisitIntegerLiteral(IntegerLiteral *E) { }
1327 void VisitFloatingLiteral(FloatingLiteral *E) { }
1328 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1329 void VisitCharacterLiteral(CharacterLiteral *E) { }
1330 void VisitGNUNullExpr(GNUNullExpr *E) { }
1331 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001332
Richard Trieu9d228802013-05-31 22:46:45 +00001333 void VisitDeclRefExpr(DeclRefExpr *E) {
1334 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1335 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001336
Richard Trieu9d228802013-05-31 22:46:45 +00001337 Ranges.push_back(E->getSourceRange());
1338
1339 Decls.insert(VD);
1340 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001341
1342 }; // end class DeclExtractor
1343
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001344 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001345 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001346 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001347 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001348 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001349
Richard Trieu9d228802013-05-31 22:46:45 +00001350 public:
1351 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001352
Craig Topper4dd9b432014-08-17 23:49:53 +00001353 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001354 Stmt *Statement) :
1355 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1356 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001357
Richard Trieu9d228802013-05-31 22:46:45 +00001358 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001359 }
1360
Richard Trieu9d228802013-05-31 22:46:45 +00001361 void VisitReturnStmt(ReturnStmt *S) {
1362 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001363 }
1364
Richard Trieu9d228802013-05-31 22:46:45 +00001365 void VisitBreakStmt(BreakStmt *S) {
1366 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001367 }
1368
Richard Trieu9d228802013-05-31 22:46:45 +00001369 void VisitGotoStmt(GotoStmt *S) {
1370 FoundDecl = true;
1371 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001372
Richard Trieu9d228802013-05-31 22:46:45 +00001373 void VisitCastExpr(CastExpr *E) {
1374 if (E->getCastKind() == CK_LValueToRValue)
1375 CheckLValueToRValueCast(E->getSubExpr());
1376 else
1377 Visit(E->getSubExpr());
1378 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001379
Richard Trieu9d228802013-05-31 22:46:45 +00001380 void CheckLValueToRValueCast(Expr *E) {
1381 E = E->IgnoreParenImpCasts();
1382
1383 if (isa<DeclRefExpr>(E)) {
1384 return;
1385 }
1386
1387 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1388 Visit(CO->getCond());
1389 CheckLValueToRValueCast(CO->getTrueExpr());
1390 CheckLValueToRValueCast(CO->getFalseExpr());
1391 return;
1392 }
1393
1394 if (BinaryConditionalOperator *BCO =
1395 dyn_cast<BinaryConditionalOperator>(E)) {
1396 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1397 CheckLValueToRValueCast(BCO->getFalseExpr());
1398 return;
1399 }
1400
1401 Visit(E);
1402 }
1403
1404 void VisitDeclRefExpr(DeclRefExpr *E) {
1405 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1406 if (Decls.count(VD))
1407 FoundDecl = true;
1408 }
1409
1410 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001411
1412 }; // end class DeclMatcher
1413
1414 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1415 Expr *Third, Stmt *Body) {
1416 // Condition is empty
1417 if (!Second) return;
1418
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001419 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1420 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001421 return;
1422
1423 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1424 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001425 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001426 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001427 DE.Visit(Second);
1428
1429 // Don't analyze complex conditionals.
1430 if (!DE.isSimple()) return;
1431
1432 // No decls found.
1433 if (Decls.size() == 0) return;
1434
Richard Trieu0030f1d2012-05-04 03:01:54 +00001435 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001436 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1437 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001438 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001439 if ((*I)->getType().isVolatileQualified() ||
1440 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001441
1442 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1443 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1444 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1445 return;
1446
1447 // Load decl names into diagnostic.
1448 if (Decls.size() > 4)
1449 PDiag << 0;
1450 else {
1451 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001452 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1453 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001454 I != E; ++I)
1455 PDiag << (*I)->getDeclName();
1456 }
1457
1458 // Load SourceRanges into diagnostic if there is room.
1459 // Otherwise, load the SourceRange of the conditional expression.
1460 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001461 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001462 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001463 I != E; ++I)
1464 PDiag << *I;
1465 else
1466 PDiag << Second->getSourceRange();
1467
1468 S.Diag(Ranges.begin()->getBegin(), PDiag);
1469 }
1470
Richard Trieu4e7c9622013-08-06 21:31:54 +00001471 // If Statement is an incemement or decrement, return true and sets the
1472 // variables Increment and DRE.
1473 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1474 DeclRefExpr *&DRE) {
1475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1476 switch (UO->getOpcode()) {
1477 default: return false;
1478 case UO_PostInc:
1479 case UO_PreInc:
1480 Increment = true;
1481 break;
1482 case UO_PostDec:
1483 case UO_PreDec:
1484 Increment = false;
1485 break;
1486 }
1487 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1488 return DRE;
1489 }
1490
1491 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1492 FunctionDecl *FD = Call->getDirectCallee();
1493 if (!FD || !FD->isOverloadedOperator()) return false;
1494 switch (FD->getOverloadedOperator()) {
1495 default: return false;
1496 case OO_PlusPlus:
1497 Increment = true;
1498 break;
1499 case OO_MinusMinus:
1500 Increment = false;
1501 break;
1502 }
1503 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1504 return DRE;
1505 }
1506
1507 return false;
1508 }
1509
Serge Pavlov09f99242014-01-23 15:05:00 +00001510 // A visitor to determine if a continue or break statement is a
1511 // subexpression.
1512 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1513 SourceLocation BreakLoc;
1514 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001515 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001516 BreakContinueFinder(Sema &S, Stmt* Body) :
1517 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001518 Visit(Body);
1519 }
1520
Serge Pavlov09f99242014-01-23 15:05:00 +00001521 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001522
1523 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001524 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001525 }
1526
Serge Pavlov09f99242014-01-23 15:05:00 +00001527 void VisitBreakStmt(BreakStmt* E) {
1528 BreakLoc = E->getBreakLoc();
1529 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001530
Serge Pavlov09f99242014-01-23 15:05:00 +00001531 bool ContinueFound() { return ContinueLoc.isValid(); }
1532 bool BreakFound() { return BreakLoc.isValid(); }
1533 SourceLocation GetContinueLoc() { return ContinueLoc; }
1534 SourceLocation GetBreakLoc() { return BreakLoc; }
1535
1536 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001537
1538 // Emit a warning when a loop increment/decrement appears twice per loop
1539 // iteration. The conditions which trigger this warning are:
1540 // 1) The last statement in the loop body and the third expression in the
1541 // for loop are both increment or both decrement of the same variable
1542 // 2) No continue statements in the loop body.
1543 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1544 // Return when there is nothing to check.
1545 if (!Body || !Third) return;
1546
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001547 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1548 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001549 return;
1550
1551 // Get the last statement from the loop body.
1552 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1553 if (!CS || CS->body_empty()) return;
1554 Stmt *LastStmt = CS->body_back();
1555 if (!LastStmt) return;
1556
1557 bool LoopIncrement, LastIncrement;
1558 DeclRefExpr *LoopDRE, *LastDRE;
1559
1560 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1561 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1562
1563 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001564 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001565 if (LoopIncrement != LastIncrement ||
1566 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1567
Serge Pavlov09f99242014-01-23 15:05:00 +00001568 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001569
1570 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1571 << LastDRE->getDecl() << LastIncrement;
1572 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1573 << LoopIncrement;
1574 }
1575
Richard Trieu451a5db2012-04-30 18:01:30 +00001576} // end namespace
1577
Serge Pavlov09f99242014-01-23 15:05:00 +00001578
1579void Sema::CheckBreakContinueBinding(Expr *E) {
1580 if (!E || getLangOpts().CPlusPlus)
1581 return;
1582 BreakContinueFinder BCFinder(*this, E);
1583 Scope *BreakParent = CurScope->getBreakParent();
1584 if (BCFinder.BreakFound() && BreakParent) {
1585 if (BreakParent->getFlags() & Scope::SwitchScope) {
1586 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1587 } else {
1588 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1589 << "break";
1590 }
1591 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1592 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1593 << "continue";
1594 }
1595}
1596
John McCalldadc5752010-08-24 06:29:42 +00001597StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001598Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001599 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001600 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001601 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001602 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001603 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001604 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1605 // declare identifiers for objects having storage class 'auto' or
1606 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001607 for (auto *DI : DS->decls()) {
1608 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001609 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001610 VD = nullptr;
1611 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001612 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1613 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001614 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001615 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001616 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001617 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001618
Serge Pavlov09f99242014-01-23 15:05:00 +00001619 CheckBreakContinueBinding(second.get());
1620 CheckBreakContinueBinding(third.get());
1621
Richard Trieu451a5db2012-04-30 18:01:30 +00001622 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001623 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001624
John McCalldadc5752010-08-24 06:29:42 +00001625 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001626 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001627 if (secondVar) {
1628 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001629 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001630 SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001631 if (SecondResult.isInvalid())
1632 return StmtError();
1633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001635 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001636
Anders Carlsson1682af52009-08-01 01:39:59 +00001637 DiagnoseUnusedExprResult(First);
1638 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001639 DiagnoseUnusedExprResult(Body);
1640
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001641 if (isa<NullStmt>(Body))
1642 getCurCompoundScope().setHasEmptyLoopBodies();
1643
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001644 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1645 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001646}
1647
John McCall34376a62010-12-04 03:47:34 +00001648/// In an Objective C collection iteration statement:
1649/// for (x in y)
1650/// x can be an arbitrary l-value expression. Bind it up as a
1651/// full-expression.
1652StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001653 // Reduce placeholder expressions here. Note that this rejects the
1654 // use of pseudo-object l-values in this position.
1655 ExprResult result = CheckPlaceholderExpr(E);
1656 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001657 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001658
Richard Smith945f8d32013-01-14 22:39:08 +00001659 ExprResult FullExpr = ActOnFinishFullExpr(E);
1660 if (FullExpr.isInvalid())
1661 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001662 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001663}
1664
John McCall53848232011-07-27 01:07:15 +00001665ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001666Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1667 if (!collection)
1668 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001669
Kaelyn Takata15867822014-11-21 18:48:04 +00001670 ExprResult result = CorrectDelayedTyposInExpr(collection);
1671 if (!result.isUsable())
1672 return ExprError();
1673 collection = result.get();
1674
John McCall53848232011-07-27 01:07:15 +00001675 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001676 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001677
1678 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001679 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001680 if (result.isInvalid())
1681 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001682 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001683
1684 // The operand needs to have object-pointer type.
1685 // TODO: should we do a contextual conversion?
1686 const ObjCObjectPointerType *pointerType =
1687 collection->getType()->getAs<ObjCObjectPointerType>();
1688 if (!pointerType)
1689 return Diag(forLoc, diag::err_collection_expr_type)
1690 << collection->getType() << collection->getSourceRange();
1691
1692 // Check that the operand provides
1693 // - countByEnumeratingWithState:objects:count:
1694 const ObjCObjectType *objectType = pointerType->getObjectType();
1695 ObjCInterfaceDecl *iface = objectType->getInterface();
1696
1697 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001698 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001699 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001700 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001701 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001702 ? diag::err_arc_collection_forward
1703 : 0,
1704 collection)) {
John McCall53848232011-07-27 01:07:15 +00001705 // Otherwise, if we have any useful type information, check that
1706 // the type declares the appropriate method.
1707 } else if (iface || !objectType->qual_empty()) {
1708 IdentifierInfo *selectorIdents[] = {
1709 &Context.Idents.get("countByEnumeratingWithState"),
1710 &Context.Idents.get("objects"),
1711 &Context.Idents.get("count")
1712 };
1713 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1714
Craig Topperc3ec1492014-05-26 06:22:03 +00001715 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001716
1717 // If there's an interface, look in both the public and private APIs.
1718 if (iface) {
1719 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001720 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001721 }
1722
1723 // Also check protocol qualifiers.
1724 if (!method)
1725 method = LookupMethodInQualifiedType(selector, pointerType,
1726 /*instance*/ true);
1727
1728 // If we didn't find it anywhere, give up.
1729 if (!method) {
1730 Diag(forLoc, diag::warn_collection_expr_type)
1731 << collection->getType() << selector << collection->getSourceRange();
1732 }
1733
1734 // TODO: check for an incompatible signature?
1735 }
1736
1737 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001738 return collection;
John McCall53848232011-07-27 01:07:15 +00001739}
1740
John McCalldadc5752010-08-24 06:29:42 +00001741StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001742Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001743 Stmt *First, Expr *collection,
1744 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001745
1746 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001747 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001748
Fariborz Jahanian93977672008-01-10 20:33:58 +00001749 if (First) {
1750 QualType FirstType;
1751 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001752 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001753 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1754 diag::err_toomany_element_decls));
1755
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001756 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1757 if (!D || D->isInvalidDecl())
1758 return StmtError();
1759
John McCall31168b02011-06-15 23:02:42 +00001760 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001761 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1762 // declare identifiers for objects having storage class 'auto' or
1763 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001764 if (!D->hasLocalStorage())
1765 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001766 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001767
1768 // If the type contained 'auto', deduce the 'auto' to 'id'.
1769 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001770 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1771 VK_RValue);
1772 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001773 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1774 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001775 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001776 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001777 D->setInvalidDecl();
1778 return StmtError();
1779 }
1780
Richard Smith061f1e22013-04-30 21:23:01 +00001781 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001782
1783 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001784 SourceLocation Loc =
1785 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001786 Diag(Loc, diag::warn_auto_var_is_id)
1787 << D->getDeclName();
1788 }
1789 }
1790
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001791 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001792 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001793 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001794 return StmtError(Diag(First->getLocStart(),
1795 diag::err_selector_element_not_lvalue)
1796 << First->getSourceRange());
1797
Mike Stump11289f42009-09-09 15:08:12 +00001798 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001799 if (FirstType.isConstQualified())
1800 Diag(ForLoc, diag::err_selector_element_const_type)
1801 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001802 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001803 if (!FirstType->isDependentType() &&
1804 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001805 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001806 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1807 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001808 }
Chad Rosier02a84392012-08-10 17:56:09 +00001809
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001810 if (CollectionExprResult.isInvalid())
1811 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001812
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001813 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001814 if (CollectionExprResult.isInvalid())
1815 return StmtError();
1816
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001817 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1818 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001819}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001820
Richard Smith02e85f32011-04-14 22:09:26 +00001821/// Finish building a variable declaration for a for-range statement.
1822/// \return true if an error occurs.
1823static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001824 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001825 if (Decl->getType()->isUndeducedType()) {
1826 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1827 if (!Res.isUsable()) {
1828 Decl->setInvalidDecl();
1829 return true;
1830 }
1831 Init = Res.get();
1832 }
1833
Richard Smith02e85f32011-04-14 22:09:26 +00001834 // Deduce the type for the iterator variable now rather than leaving it to
1835 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001836 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001837 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001838 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001839 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001840 SemaRef.Diag(Loc, DiagID) << Init->getType();
1841 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001842 Decl->setInvalidDecl();
1843 return true;
1844 }
Richard Smith061f1e22013-04-30 21:23:01 +00001845 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001846
John McCall31168b02011-06-15 23:02:42 +00001847 // In ARC, infer lifetime.
1848 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1849 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001850 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001851 SemaRef.inferObjCARCLifetime(Decl))
1852 Decl->setInvalidDecl();
1853
Richard Smith02e85f32011-04-14 22:09:26 +00001854 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1855 /*TypeMayContainAuto=*/false);
1856 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001857 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001858 return false;
1859}
1860
Sam Panzer0f384432012-08-21 00:52:01 +00001861namespace {
1862
Richard Smith02e85f32011-04-14 22:09:26 +00001863/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001864/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001865/// nor from the diagnostics produced when analysing the implicit expressions
1866/// required in a for-range statement.
1867void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001868 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001869 CallExpr *CE = dyn_cast<CallExpr>(E);
1870 if (!CE)
1871 return;
1872 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1873 if (!D)
1874 return;
1875 SourceLocation Loc = D->getLocation();
1876
1877 std::string Description;
1878 bool IsTemplate = false;
1879 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1880 Description = SemaRef.getTemplateArgumentBindingsText(
1881 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1882 IsTemplate = true;
1883 }
1884
1885 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1886 << BEF << IsTemplate << Description << E->getType();
1887}
1888
Sam Panzer0f384432012-08-21 00:52:01 +00001889/// Build a variable declaration for a for-range statement.
1890VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1891 QualType Type, const char *Name) {
1892 DeclContext *DC = SemaRef.CurContext;
1893 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1894 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1895 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001896 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001897 Decl->setImplicit();
1898 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001899}
1900
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001901}
Richard Smith02e85f32011-04-14 22:09:26 +00001902
Fariborz Jahanian00213472012-07-06 19:04:04 +00001903static bool ObjCEnumerationCollection(Expr *Collection) {
1904 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001905 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001906}
1907
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001908/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001909///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001910/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001911/// A range-based for statement is equivalent to
1912///
1913/// {
1914/// auto && __range = range-init;
1915/// for ( auto __begin = begin-expr,
1916/// __end = end-expr;
1917/// __begin != __end;
1918/// ++__begin ) {
1919/// for-range-declaration = *__begin;
1920/// statement
1921/// }
1922/// }
1923///
1924/// The body of the loop is not available yet, since it cannot be analysed until
1925/// we have determined the type of the for-range-declaration.
1926StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00001927Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001928 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001929 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001930 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001931 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001932
Richard Smith3249fed2013-08-21 01:40:36 +00001933 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001934 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001935
1936 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1937 assert(DS && "first part of for range not a decl stmt");
1938
1939 if (!DS->isSingleDecl()) {
1940 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1941 return StmtError();
1942 }
Richard Smith02e85f32011-04-14 22:09:26 +00001943
Richard Smith3249fed2013-08-21 01:40:36 +00001944 Decl *LoopVar = DS->getSingleDecl();
1945 if (LoopVar->isInvalidDecl() || !Range ||
1946 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1947 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001948 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001949 }
Richard Smith02e85f32011-04-14 22:09:26 +00001950
Richard Smithcfd53b42015-10-22 06:13:50 +00001951 // Coroutines: 'for co_await' implicitly co_awaits its range.
1952 if (CoawaitLoc.isValid()) {
1953 ExprResult Coawait = ActOnCoawaitExpr(CoawaitLoc, Range);
1954 if (Coawait.isInvalid()) return StmtError();
1955 Range = Coawait.get();
1956 }
1957
Richard Smith02e85f32011-04-14 22:09:26 +00001958 // Build auto && __range = range-init
1959 SourceLocation RangeLoc = Range->getLocStart();
1960 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1961 Context.getAutoRRefDeductType(),
1962 "__range");
1963 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001964 diag::err_for_range_deduction_failure)) {
1965 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001966 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001967 }
Richard Smith02e85f32011-04-14 22:09:26 +00001968
1969 // Claim the type doesn't contain auto: we've already done the checking.
1970 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001971 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001972 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001973 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001974 if (RangeDecl.isInvalid()) {
1975 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001976 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001977 }
Richard Smith02e85f32011-04-14 22:09:26 +00001978
Richard Smithcfd53b42015-10-22 06:13:50 +00001979 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001980 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1981 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001982}
1983
1984/// \brief Create the initialization, compare, and increment steps for
1985/// the range-based for loop expression.
1986/// This function does not handle array-based for loops,
1987/// which are created in Sema::BuildCXXForRangeStmt.
1988///
1989/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1990/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1991/// CandidateSet and BEF are set and some non-success value is returned on
1992/// failure.
1993static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1994 Expr *BeginRange, Expr *EndRange,
1995 QualType RangeType,
1996 VarDecl *BeginVar,
1997 VarDecl *EndVar,
1998 SourceLocation ColonLoc,
1999 OverloadCandidateSet *CandidateSet,
2000 ExprResult *BeginExpr,
2001 ExprResult *EndExpr,
2002 Sema::BeginEndFunction *BEF) {
2003 DeclarationNameInfo BeginNameInfo(
2004 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2005 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2006 ColonLoc);
2007
2008 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2009 Sema::LookupMemberName);
2010 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2011
2012 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2013 // - if _RangeT is a class type, the unqualified-ids begin and end are
2014 // looked up in the scope of class _RangeT as if by class member access
2015 // lookup (3.4.5), and if either (or both) finds at least one
2016 // declaration, begin-expr and end-expr are __range.begin() and
2017 // __range.end(), respectively;
2018 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2019 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2020
2021 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2022 SourceLocation RangeLoc = BeginVar->getLocation();
2023 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2024
2025 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2026 << RangeLoc << BeginRange->getType() << *BEF;
2027 return Sema::FRS_DiagnosticIssued;
2028 }
2029 } else {
2030 // - otherwise, begin-expr and end-expr are begin(__range) and
2031 // end(__range), respectively, where begin and end are looked up with
2032 // argument-dependent lookup (3.4.2). For the purposes of this name
2033 // lookup, namespace std is an associated namespace.
2034
2035 }
2036
2037 *BEF = Sema::BEF_begin;
2038 Sema::ForRangeStatus RangeStatus =
2039 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2040 Sema::BEF_begin, BeginNameInfo,
2041 BeginMemberLookup, CandidateSet,
2042 BeginRange, BeginExpr);
2043
2044 if (RangeStatus != Sema::FRS_Success)
2045 return RangeStatus;
2046 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2047 diag::err_for_range_iter_deduction_failure)) {
2048 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2049 return Sema::FRS_DiagnosticIssued;
2050 }
2051
2052 *BEF = Sema::BEF_end;
2053 RangeStatus =
2054 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2055 Sema::BEF_end, EndNameInfo,
2056 EndMemberLookup, CandidateSet,
2057 EndRange, EndExpr);
2058 if (RangeStatus != Sema::FRS_Success)
2059 return RangeStatus;
2060 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2061 diag::err_for_range_iter_deduction_failure)) {
2062 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2063 return Sema::FRS_DiagnosticIssued;
2064 }
2065 return Sema::FRS_Success;
2066}
2067
2068/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002069/// If the attempt fails, this function will return a valid, null StmtResult
2070/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002071static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2072 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002073 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002074 Stmt *LoopVarDecl,
2075 SourceLocation ColonLoc,
2076 Expr *Range,
2077 SourceLocation RangeLoc,
2078 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002079 // Determine whether we can rebuild the for-range statement with a
2080 // dereferenced range expression.
2081 ExprResult AdjustedRange;
2082 {
2083 Sema::SFINAETrap Trap(SemaRef);
2084
2085 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2086 if (AdjustedRange.isInvalid())
2087 return StmtResult();
2088
2089 StmtResult SR =
Richard Smithcfd53b42015-10-22 06:13:50 +00002090 SemaRef.ActOnCXXForRangeStmt(ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002091 AdjustedRange.get(), RParenLoc,
2092 Sema::BFRK_Check);
2093 if (SR.isInvalid())
2094 return StmtResult();
2095 }
2096
2097 // The attempt to dereference worked well enough that it could produce a valid
2098 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2099 // case there are any other (non-fatal) problems with it.
2100 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2101 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smithcfd53b42015-10-22 06:13:50 +00002102 return SemaRef.ActOnCXXForRangeStmt(ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002103 AdjustedRange.get(), RParenLoc,
2104 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002105}
2106
Richard Smith3249fed2013-08-21 01:40:36 +00002107namespace {
2108/// RAII object to automatically invalidate a declaration if an error occurs.
2109struct InvalidateOnErrorScope {
2110 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2111 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2112 ~InvalidateOnErrorScope() {
2113 if (Enabled && Trap.hasErrorOccurred())
2114 D->setInvalidDecl();
2115 }
2116
2117 DiagnosticErrorTrap Trap;
2118 Decl *D;
2119 bool Enabled;
2120};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002121}
Richard Smith3249fed2013-08-21 01:40:36 +00002122
Richard Smitha05b3b52012-09-20 21:52:32 +00002123/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002124StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002125Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2126 SourceLocation ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002127 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2128 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002129 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002130 Scope *S = getCurScope();
2131
2132 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2133 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2134 QualType RangeVarType = RangeVar->getType();
2135
2136 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2137 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2138
Richard Smith3249fed2013-08-21 01:40:36 +00002139 // If we hit any errors, mark the loop variable as invalid if its type
2140 // contains 'auto'.
2141 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2142 LoopVar->getType()->isUndeducedType());
2143
Richard Smith02e85f32011-04-14 22:09:26 +00002144 StmtResult BeginEndDecl = BeginEnd;
2145 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2146
Richard Smith27d807c2013-04-30 13:56:41 +00002147 if (RangeVarType->isDependentType()) {
2148 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002149 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002150
2151 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2152 // them in properly when we instantiate the loop.
2153 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2154 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2155 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002156 SourceLocation RangeLoc = RangeVar->getLocation();
2157
Ted Kremenekbed648e2011-10-10 22:36:28 +00002158 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2159
2160 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2161 VK_LValue, ColonLoc);
2162 if (BeginRangeRef.isInvalid())
2163 return StmtError();
2164
2165 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2166 VK_LValue, ColonLoc);
2167 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002168 return StmtError();
2169
2170 QualType AutoType = Context.getAutoDeductType();
2171 Expr *Range = RangeVar->getInit();
2172 if (!Range)
2173 return StmtError();
2174 QualType RangeType = Range->getType();
2175
2176 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002177 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002178 return StmtError();
2179
2180 // Build auto __begin = begin-expr, __end = end-expr.
2181 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2182 "__begin");
2183 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2184 "__end");
2185
2186 // Build begin-expr and end-expr and attach to __begin and __end variables.
2187 ExprResult BeginExpr, EndExpr;
2188 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2189 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2190 // __range + __bound, respectively, where __bound is the array bound. If
2191 // _RangeT is an array of unknown size or an array of incomplete type,
2192 // the program is ill-formed;
2193
2194 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002195 BeginExpr = BeginRangeRef;
2196 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002197 diag::err_for_range_iter_deduction_failure)) {
2198 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2199 return StmtError();
2200 }
2201
2202 // Find the array bound.
2203 ExprResult BoundExpr;
2204 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002205 BoundExpr = IntegerLiteral::Create(
2206 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002207 else if (const VariableArrayType *VAT =
2208 dyn_cast<VariableArrayType>(UnqAT))
2209 BoundExpr = VAT->getSizeExpr();
2210 else {
2211 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2212 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002213 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002214 }
2215
2216 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002217 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002218 BoundExpr.get());
2219 if (EndExpr.isInvalid())
2220 return StmtError();
2221 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2222 diag::err_for_range_iter_deduction_failure)) {
2223 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2224 return StmtError();
2225 }
2226 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002227 OverloadCandidateSet CandidateSet(RangeLoc,
2228 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002229 Sema::BeginEndFunction BEFFailure;
2230 ForRangeStatus RangeStatus =
2231 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2232 EndRangeRef.get(), RangeType,
2233 BeginVar, EndVar, ColonLoc, &CandidateSet,
2234 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002235
Richard Smitha05b3b52012-09-20 21:52:32 +00002236 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002237 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002238 // If the range is being built from an array parameter, emit a
2239 // a diagnostic that it is being treated as a pointer.
2240 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2241 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2242 QualType ArrayTy = PVD->getOriginalType();
2243 QualType PointerTy = PVD->getType();
2244 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2245 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2246 << RangeLoc << PVD << ArrayTy << PointerTy;
2247 Diag(PVD->getLocation(), diag::note_declared_at);
2248 return StmtError();
2249 }
2250 }
2251 }
2252
2253 // If building the range failed, try dereferencing the range expression
2254 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002255 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002256 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002257 LoopVarDecl, ColonLoc,
2258 Range, RangeLoc,
2259 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002260 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002261 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002262 }
2263
Sam Panzer0f384432012-08-21 00:52:01 +00002264 // Otherwise, emit diagnostics if we haven't already.
2265 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002266 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002267 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2268 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002269 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002270 }
2271 // Return an error if no fix was discovered.
2272 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002273 return StmtError();
2274 }
2275
Sam Panzer0f384432012-08-21 00:52:01 +00002276 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2277 "invalid range expression in for loop");
2278
2279 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002280 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2281 if (!Context.hasSameType(BeginType, EndType)) {
2282 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2283 << BeginType << EndType;
2284 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2285 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2286 }
2287
2288 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2289 // Claim the type doesn't contain auto: we've already done the checking.
2290 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002291 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002292 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002293 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2294
Ted Kremenekbed648e2011-10-10 22:36:28 +00002295 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2296 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002297 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002298 if (BeginRef.isInvalid())
2299 return StmtError();
2300
Richard Smith02e85f32011-04-14 22:09:26 +00002301 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2302 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002303 if (EndRef.isInvalid())
2304 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002305
2306 // Build and check __begin != __end expression.
2307 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2308 BeginRef.get(), EndRef.get());
2309 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2310 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2311 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002312 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2313 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002314 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2315 if (!Context.hasSameType(BeginType, EndType))
2316 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2317 return StmtError();
2318 }
2319
2320 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002321 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2322 VK_LValue, ColonLoc);
2323 if (BeginRef.isInvalid())
2324 return StmtError();
2325
Richard Smith02e85f32011-04-14 22:09:26 +00002326 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002327 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2328 IncrExpr = ActOnCoawaitExpr(CoawaitLoc, IncrExpr.get());
2329 if (!IncrExpr.isInvalid())
2330 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002331 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002332 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2333 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002334 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2335 return StmtError();
2336 }
2337
2338 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002339 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2340 VK_LValue, ColonLoc);
2341 if (BeginRef.isInvalid())
2342 return StmtError();
2343
Richard Smith02e85f32011-04-14 22:09:26 +00002344 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2345 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002346 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2347 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002348 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2349 return StmtError();
2350 }
2351
Richard Smitha05b3b52012-09-20 21:52:32 +00002352 // Attach *__begin as initializer for VD. Don't touch it if we're just
2353 // trying to determine whether this would be a valid range.
2354 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002355 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2356 /*TypeMayContainAuto=*/true);
2357 if (LoopVar->isInvalidDecl())
2358 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2359 }
2360 }
2361
Richard Smitha05b3b52012-09-20 21:52:32 +00002362 // Don't bother to actually allocate the result if we're just trying to
2363 // determine whether it would be valid.
2364 if (Kind == BFRK_Check)
2365 return StmtResult();
2366
Richard Smithcfd53b42015-10-22 06:13:50 +00002367 // FIXME: Pass in CoawaitLoc in the dependent case.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002368 return new (Context) CXXForRangeStmt(
2369 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2370 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002371}
2372
Chad Rosier02a84392012-08-10 17:56:09 +00002373/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002374/// statement.
2375StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2376 if (!S || !B)
2377 return StmtError();
2378 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002379
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002380 ForStmt->setBody(B);
2381 return S;
2382}
2383
Richard Trieu3e1d4832015-04-13 22:08:55 +00002384// Warn when the loop variable is a const reference that creates a copy.
2385// Suggest using the non-reference type for copies. If a copy can be prevented
2386// suggest the const reference type that would do so.
2387// For instance, given "for (const &Foo : Range)", suggest
2388// "for (const Foo : Range)" to denote a copy is made for the loop. If
2389// possible, also suggest "for (const &Bar : Range)" if this type prevents
2390// the copy altogether.
2391static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2392 const VarDecl *VD,
2393 QualType RangeInitType) {
2394 const Expr *InitExpr = VD->getInit();
2395 if (!InitExpr)
2396 return;
2397
2398 QualType VariableType = VD->getType();
2399
2400 const MaterializeTemporaryExpr *MTE =
2401 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2402
2403 // No copy made.
2404 if (!MTE)
2405 return;
2406
2407 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2408
2409 // Searching for either UnaryOperator for dereference of a pointer or
2410 // CXXOperatorCallExpr for handling iterators.
2411 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2412 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2413 E = CCE->getArg(0);
2414 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2415 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2416 E = ME->getBase();
2417 } else {
2418 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2419 E = MTE->GetTemporaryExpr();
2420 }
2421 E = E->IgnoreImpCasts();
2422 }
2423
2424 bool ReturnsReference = false;
2425 if (isa<UnaryOperator>(E)) {
2426 ReturnsReference = true;
2427 } else {
2428 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2429 const FunctionDecl *FD = Call->getDirectCallee();
2430 QualType ReturnType = FD->getReturnType();
2431 ReturnsReference = ReturnType->isReferenceType();
2432 }
2433
2434 if (ReturnsReference) {
2435 // Loop variable creates a temporary. Suggest either to go with
2436 // non-reference loop variable to indiciate a copy is made, or
2437 // the correct time to bind a const reference.
2438 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2439 << VD << VariableType << E->getType();
2440 QualType NonReferenceType = VariableType.getNonReferenceType();
2441 NonReferenceType.removeLocalConst();
2442 QualType NewReferenceType =
2443 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2444 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2445 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2446 } else {
2447 // The range always returns a copy, so a temporary is always created.
2448 // Suggest removing the reference from the loop variable.
2449 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2450 << VD << RangeInitType;
2451 QualType NonReferenceType = VariableType.getNonReferenceType();
2452 NonReferenceType.removeLocalConst();
2453 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2454 << NonReferenceType << VD->getSourceRange();
2455 }
2456}
2457
2458// Warns when the loop variable can be changed to a reference type to
2459// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2460// "for (const Foo &x : Range)" if this form does not make a copy.
2461static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2462 const VarDecl *VD) {
2463 const Expr *InitExpr = VD->getInit();
2464 if (!InitExpr)
2465 return;
2466
2467 QualType VariableType = VD->getType();
2468
2469 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2470 if (!CE->getConstructor()->isCopyConstructor())
2471 return;
2472 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2473 if (CE->getCastKind() != CK_LValueToRValue)
2474 return;
2475 } else {
2476 return;
2477 }
2478
2479 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2480 // should be emitted. Also, only ignore POD types with trivial copy
2481 // constructors.
2482 if (VariableType.isPODType(SemaRef.Context))
2483 return;
2484
2485 // Suggest changing from a const variable to a const reference variable
2486 // if doing so will prevent a copy.
2487 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2488 << VD << VariableType << InitExpr->getType();
2489 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2490 << SemaRef.Context.getLValueReferenceType(VariableType)
2491 << VD->getSourceRange();
2492}
2493
2494/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2495/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2496/// using "const foo x" to show that a copy is made
2497/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2498/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2499/// prevent the copy.
2500/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2501/// Suggest "const foo &x" to prevent the copy.
2502static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2503 const CXXForRangeStmt *ForStmt) {
2504 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2505 ForStmt->getLocStart()) &&
2506 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2507 ForStmt->getLocStart()) &&
2508 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2509 ForStmt->getLocStart())) {
2510 return;
2511 }
2512
2513 const VarDecl *VD = ForStmt->getLoopVariable();
2514 if (!VD)
2515 return;
2516
2517 QualType VariableType = VD->getType();
2518
2519 if (VariableType->isIncompleteType())
2520 return;
2521
2522 const Expr *InitExpr = VD->getInit();
2523 if (!InitExpr)
2524 return;
2525
2526 if (VariableType->isReferenceType()) {
2527 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2528 ForStmt->getRangeInit()->getType());
2529 } else if (VariableType.isConstQualified()) {
2530 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2531 }
2532}
2533
Richard Smith02e85f32011-04-14 22:09:26 +00002534/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2535/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2536/// body cannot be performed until after the type of the range variable is
2537/// determined.
2538StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2539 if (!S || !B)
2540 return StmtError();
2541
Fariborz Jahanian00213472012-07-06 19:04:04 +00002542 if (isa<ObjCForCollectionStmt>(S))
2543 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002544
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002545 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2546 ForStmt->setBody(B);
2547
2548 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2549 diag::warn_empty_range_based_for_body);
2550
Richard Trieu3e1d4832015-04-13 22:08:55 +00002551 DiagnoseForRangeVariableCopies(*this, ForStmt);
2552
Richard Smith02e85f32011-04-14 22:09:26 +00002553 return S;
2554}
2555
Chris Lattnercab02a62011-02-17 20:34:02 +00002556StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2557 SourceLocation LabelLoc,
2558 LabelDecl *TheDecl) {
2559 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002560 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002561 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002562}
Chris Lattner1c310502007-05-31 06:00:00 +00002563
John McCalldadc5752010-08-24 06:29:42 +00002564StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002565Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002566 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002567 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002568 if (!E->isTypeDependent()) {
2569 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002570 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002571 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002572 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002573 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2574 if (ExprRes.isInvalid())
2575 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002576 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002577 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002578 return StmtError();
2579 }
John McCalla95172b2010-08-01 00:26:45 +00002580
Richard Smith945f8d32013-01-14 22:39:08 +00002581 ExprResult ExprRes = ActOnFinishFullExpr(E);
2582 if (ExprRes.isInvalid())
2583 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002584 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002585
John McCallaab3e412010-08-25 08:40:02 +00002586 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002587
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002588 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002589}
2590
Nico Weberd64657f2015-03-09 02:47:59 +00002591static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2592 const Scope &DestScope) {
2593 if (!S.CurrentSEHFinally.empty() &&
2594 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2595 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2596 }
2597}
2598
John McCalldadc5752010-08-24 06:29:42 +00002599StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002600Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002601 Scope *S = CurScope->getContinueParent();
2602 if (!S) {
2603 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002604 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002605 }
Nico Weberd64657f2015-03-09 02:47:59 +00002606 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002607
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002608 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002609}
2610
John McCalldadc5752010-08-24 06:29:42 +00002611StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002612Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002613 Scope *S = CurScope->getBreakParent();
2614 if (!S) {
2615 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002616 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002617 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002618 if (S->isOpenMPLoopScope())
2619 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2620 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002621 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002622
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002623 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002624}
2625
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002626/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002627/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002628///
Douglas Gregor5d369002011-01-21 18:05:27 +00002629/// \param ReturnType If we're determining the copy elision candidate for
2630/// a return statement, this is the return type of the function. If we're
2631/// determining the copy elision candidate for a throw expression, this will
2632/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002633///
Douglas Gregor5d369002011-01-21 18:05:27 +00002634/// \param E The expression being returned from the function or block, or
2635/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002636///
Douglas Gregor86394412011-05-20 15:00:53 +00002637/// \param AllowFunctionParameter Whether we allow function parameters to
2638/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2639/// we re-use this logic to determine whether we should try to move as part of
2640/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002641///
2642/// \returns The NRVO candidate variable, if the return statement may use the
2643/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002644VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2645 Expr *E,
2646 bool AllowFunctionParameter) {
2647 if (!getLangOpts().CPlusPlus)
2648 return nullptr;
2649
2650 // - in a return statement in a function [where] ...
2651 // ... the expression is the name of a non-volatile automatic object ...
2652 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002653 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002654 return nullptr;
2655 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2656 if (!VD)
2657 return nullptr;
2658
2659 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2660 return VD;
2661 return nullptr;
2662}
2663
2664bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2665 bool AllowFunctionParameter) {
2666 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002667 // - in a return statement in a function with ...
2668 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002669 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002670 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002671 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002672 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002673 if (!VDType->isDependentType() &&
2674 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2675 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677
John McCall03318c12011-11-11 03:57:31 +00002678 // ...object (other than a function or catch-clause parameter)...
2679 if (VD->getKind() != Decl::Var &&
2680 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002681 return false;
2682 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683
John McCall03318c12011-11-11 03:57:31 +00002684 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002685 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002686
2687 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002688 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002689
2690 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002691 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002692
2693 // Variables with higher required alignment than their type's ABI
2694 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002695 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002696 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002697 return false;
John McCall03318c12011-11-11 03:57:31 +00002698
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002699 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002700}
2701
Douglas Gregor626fbed2011-01-21 21:08:57 +00002702/// \brief Perform the initialization of a potentially-movable value, which
2703/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002704///
2705/// This routine implements C++0x [class.copy]p33, which attempts to treat
2706/// returned lvalues as rvalues in certain cases (to prefer move construction),
2707/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002709Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2710 const VarDecl *NRVOCandidate,
2711 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002712 Expr *Value,
2713 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002714 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715 // When the criteria for elision of a copy operation are met or would
2716 // be met save for the fact that the source object is a function
2717 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002718 // overload resolution to select the constructor for the copy is first
2719 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002720 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002721 if (AllowNRVO &&
2722 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002723 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002724 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002725
Douglas Gregorf282a762011-01-21 19:38:21 +00002726 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002727 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002728 = InitializationKind::CreateCopy(Value->getLocStart(),
2729 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002730 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002731
2732 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002733 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002734 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002735 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002736 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002737 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2738 StepEnd = Seq.step_end();
2739 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002740 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002741 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002742
2743 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002744 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002745
Douglas Gregorf282a762011-01-21 19:38:21 +00002746 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002747 = Constructor->getParamDecl(0)->getType()
2748 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002749
Douglas Gregorf282a762011-01-21 19:38:21 +00002750 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002752 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2753 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002754 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002755
Douglas Gregorf282a762011-01-21 19:38:21 +00002756 // Promote "AsRvalue" to the heap, since we now need this
2757 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002758 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002759 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760
Douglas Gregorf282a762011-01-21 19:38:21 +00002761 // Complete type-checking the initialization of the return type
2762 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002763 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002764 }
2765 }
2766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767
Douglas Gregorf282a762011-01-21 19:38:21 +00002768 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002769 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002770 // (again) now with the return value expression as written.
2771 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002772 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773
Douglas Gregorf282a762011-01-21 19:38:21 +00002774 return Res;
2775}
2776
Richard Smith4db51c22013-09-25 05:02:54 +00002777/// \brief Determine whether the declared return type of the specified function
2778/// contains 'auto'.
2779static bool hasDeducedReturnType(FunctionDecl *FD) {
2780 const FunctionProtoType *FPT =
2781 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002782 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002783}
2784
Eli Friedman34b49062012-01-26 03:00:14 +00002785/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2786/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002787///
John McCalldadc5752010-08-24 06:29:42 +00002788StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002789Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2790 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002791 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002792 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002793 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002794 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002795
Richard Smith4db51c22013-09-25 05:02:54 +00002796 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2797 // In C++1y, the return type may involve 'auto'.
2798 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2799 FunctionDecl *FD = CurLambda->CallOperator;
2800 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002801 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002802
2803 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2804 assert(AT && "lost auto type from lambda return type");
2805 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2806 FD->setInvalidDecl();
2807 return StmtError();
2808 }
Alp Toker314cc812014-01-25 16:55:45 +00002809 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002810 } else if (CurCap->HasImplicitReturnType) {
2811 // For blocks/lambdas with implicit return types, we check each return
2812 // statement individually, and deduce the common return type when the block
2813 // or lambda is completed.
2814 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002815 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002816 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2817 if (Result.isInvalid())
2818 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002819 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002820
Richard Smith5a0e50c2014-12-19 22:10:51 +00002821 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2822 // when deducing a return type for a lambda-expression (or by extension
2823 // for a block). These rules differ from the stated C++11 rules only in
2824 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002825 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002826 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002827 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002828 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002829 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002830 if (RetValExp) {
2831 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2832 // initializer list, because it is not an expression (even
2833 // though we represent it as one). We still deduce 'void'.
2834 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2835 << RetValExp->getSourceRange();
2836 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002837
Jordan Rosed39e5f12012-07-02 21:19:23 +00002838 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002839 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002840
2841 // Although we'll properly infer the type of the block once it's completed,
2842 // make sure we provide a return type now for better error recovery.
2843 if (CurCap->ReturnType.isNull())
2844 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002845 }
Eli Friedman34b49062012-01-26 03:00:14 +00002846 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002847
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002848 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002849 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2850 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2851 return StmtError();
2852 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002853 } else if (CapturedRegionScopeInfo *CurRegion =
2854 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2855 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2856 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002857 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002858 assert(CurLambda && "unknown kind of captured scope");
2859 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2860 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002861 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2862 return StmtError();
2863 }
2864 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002865
Steve Naroffc540d662008-09-03 18:15:37 +00002866 // Otherwise, verify that this result type matches the previous one. We are
2867 // pickier with blocks than for normal functions because we don't have GCC
2868 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002869 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002870 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002871 // Delay processing for now. TODO: there are lots of dependent
2872 // types we can conclusively prove aren't void.
2873 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002874 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002875 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002876 (RetValExp->isTypeDependent() ||
2877 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002878 if (!getLangOpts().CPlusPlus &&
2879 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002880 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002881 else {
2882 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002883 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002884 }
Steve Naroffc540d662008-09-03 18:15:37 +00002885 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002886 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002887 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2888 } else if (!RetValExp->isTypeDependent()) {
2889 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002890
John McCall5500ef22011-08-17 22:09:46 +00002891 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2892 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2893 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002894
John McCall5500ef22011-08-17 22:09:46 +00002895 // In C++ the return statement is handled via a copy initialization.
2896 // the C version of which boils down to CheckSingleAssignmentConstraints.
2897 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2898 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2899 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002900 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002901 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2902 FnRetType, RetValExp);
2903 if (Res.isInvalid()) {
2904 // FIXME: Cleanup temporaries here, anyway?
2905 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002906 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002907 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002908 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002909 } else {
2910 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002911 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002912
John McCall75f92b52011-08-17 21:34:14 +00002913 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002914 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2915 if (ER.isInvalid())
2916 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002917 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002918 }
John McCall5500ef22011-08-17 22:09:46 +00002919 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2920 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002921
Jordan Rosed39e5f12012-07-02 21:19:23 +00002922 // If we need to check for the named return value optimization,
2923 // or if we need to infer the return type,
2924 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002925 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002926 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002928 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002929}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002930
Nico Weber72889432014-09-06 01:25:55 +00002931namespace {
2932/// \brief Marks all typedefs in all local classes in a type referenced.
2933///
2934/// In a function like
2935/// auto f() {
2936/// struct S { typedef int a; };
2937/// return S();
2938/// }
2939///
2940/// the local type escapes and could be referenced in some TUs but not in
2941/// others. Pretend that all local typedefs are always referenced, to not warn
2942/// on this. This isn't necessary if f has internal linkage, or the typedef
2943/// is private.
2944class LocalTypedefNameReferencer
2945 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2946public:
2947 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2948 bool VisitRecordType(const RecordType *RT);
2949private:
2950 Sema &S;
2951};
2952bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2953 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2954 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2955 R->isDependentType())
2956 return true;
2957 for (auto *TmpD : R->decls())
2958 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2959 if (T->getAccess() != AS_private || R->hasFriends())
2960 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2961 return true;
2962}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002963}
Nico Weber72889432014-09-06 01:25:55 +00002964
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002965TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002966 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002967 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2968 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002969 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002970}
2971
Richard Smith2a7d4812013-05-04 07:00:32 +00002972/// Deduce the return type for a function from a returned expression, per
2973/// C++1y [dcl.spec.auto]p6.
2974bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2975 SourceLocation ReturnLoc,
2976 Expr *&RetExpr,
2977 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002978 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002979 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002980
Richard Smithc58f38f2013-08-14 20:16:31 +00002981 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2982 // If the deduction is for a return statement and the initializer is
2983 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002984 Diag(RetExpr->getExprLoc(),
2985 getCurLambda() ? diag::err_lambda_return_init_list
2986 : diag::err_auto_fn_return_init_list)
2987 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002988 return true;
2989 }
2990
2991 if (FD->isDependentContext()) {
2992 // C++1y [dcl.spec.auto]p12:
2993 // Return type deduction [...] occurs when the definition is
2994 // instantiated even if the function body contains a return
2995 // statement with a non-type-dependent operand.
2996 assert(AT->isDeduced() && "should have deduced to dependent type");
2997 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00002998 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002999
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003000 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003001 // Otherwise, [...] deduce a value for U using the rules of template
3002 // argument deduction.
3003 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3004
3005 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3006 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3007 << OrigResultType.getType() << RetExpr->getType();
3008
3009 if (DAR != DAR_Succeeded)
3010 return true;
Nico Weber72889432014-09-06 01:25:55 +00003011
3012 // If a local type is part of the returned type, mark its fields as
3013 // referenced.
3014 LocalTypedefNameReferencer Referencer(*this);
3015 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003016 } else {
3017 // In the case of a return with no operand, the initializer is considered
3018 // to be void().
3019 //
3020 // Deduction here can only succeed if the return type is exactly 'cv auto'
3021 // or 'decltype(auto)', so just check for that case directly.
3022 if (!OrigResultType.getType()->getAs<AutoType>()) {
3023 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3024 << OrigResultType.getType();
3025 return true;
3026 }
3027 // We always deduce U = void in this case.
3028 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3029 if (Deduced.isNull())
3030 return true;
3031 }
3032
3033 // If a function with a declared return type that contains a placeholder type
3034 // has multiple return statements, the return type is deduced for each return
3035 // statement. [...] if the type deduced is not the same in each deduction,
3036 // the program is ill-formed.
3037 if (AT->isDeduced() && !FD->isInvalidDecl()) {
3038 AutoType *NewAT = Deduced->getContainedAutoType();
Douglas Gregora602a152015-10-01 20:20:47 +00003039 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3040 AT->getDeducedType());
3041 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3042 NewAT->getDeducedType());
3043 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003044 const LambdaScopeInfo *LambdaSI = getCurLambda();
3045 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3046 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3047 << NewAT->getDeducedType() << AT->getDeducedType()
3048 << true /*IsLambda*/;
3049 } else {
3050 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3051 << (AT->isDecltypeAuto() ? 1 : 0)
3052 << NewAT->getDeducedType() << AT->getDeducedType();
3053 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003054 return true;
3055 }
3056 } else if (!FD->isInvalidDecl()) {
3057 // Update all declarations of the function to have the deduced return type.
3058 Context.adjustDeducedFunctionResultType(FD, Deduced);
3059 }
3060
3061 return false;
3062}
3063
John McCalldadc5752010-08-24 06:29:42 +00003064StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003065Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3066 Scope *CurScope) {
3067 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3068 if (R.isInvalid()) {
3069 return R;
3070 }
3071
3072 if (VarDecl *VD =
3073 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3074 CurScope->addNRVOCandidate(VD);
3075 } else {
3076 CurScope->setNoNRVO();
3077 }
3078
Nico Weberd64657f2015-03-09 02:47:59 +00003079 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3080
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003081 return R;
3082}
3083
3084StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003085 // Check for unexpanded parameter packs.
3086 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3087 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003088
Eli Friedman34b49062012-01-26 03:00:14 +00003089 if (isa<CapturingScopeInfo>(getCurFunction()))
3090 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003091
Chris Lattner79413952008-12-04 23:50:19 +00003092 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003093 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003094 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003095 bool isObjCMethod = false;
3096
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003097 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003098 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003099 if (FD->hasAttrs())
3100 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003101 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003102 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003103 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003104 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003105 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003106 isObjCMethod = true;
3107 if (MD->hasAttrs())
3108 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003109 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3110 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003111 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003112 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003113 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3114 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003115 }
3116 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003117 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003118
Richard Smith2a7d4812013-05-04 07:00:32 +00003119 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3120 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003121 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003122 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3123 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003124 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003125 FD->setInvalidDecl();
3126 return StmtError();
3127 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003128 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003129 }
3130 }
3131 }
3132
Richard Smithc58f38f2013-08-14 20:16:31 +00003133 bool HasDependentReturnType = FnRetType->isDependentType();
3134
Craig Topperc3ec1492014-05-26 06:22:03 +00003135 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003136 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003137 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003138 if (isa<InitListExpr>(RetValExp)) {
3139 // We simply never allow init lists as the return value of void
3140 // functions. This is compatible because this was never allowed before,
3141 // so there's no legacy code to deal with.
3142 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3143 int FunctionKind = 0;
3144 if (isa<ObjCMethodDecl>(CurDecl))
3145 FunctionKind = 1;
3146 else if (isa<CXXConstructorDecl>(CurDecl))
3147 FunctionKind = 2;
3148 else if (isa<CXXDestructorDecl>(CurDecl))
3149 FunctionKind = 3;
3150
3151 Diag(ReturnLoc, diag::err_return_init_list)
3152 << CurDecl->getDeclName() << FunctionKind
3153 << RetValExp->getSourceRange();
3154
3155 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003156 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003157 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003158 // C99 6.8.6.4p1 (ext_ since GCC warns)
3159 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003160 if (RetValExp->getType()->isVoidType()) {
3161 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3162 if (isa<CXXConstructorDecl>(CurDecl) ||
3163 isa<CXXDestructorDecl>(CurDecl))
3164 D = diag::err_ctor_dtor_returns_void;
3165 else
3166 D = diag::ext_return_has_void_expr;
3167 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003168 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003169 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003170 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003171 if (Result.isInvalid())
3172 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003173 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003174 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003175 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003176 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003177 // return of void in constructor/destructor is illegal in C++.
3178 if (D == diag::err_ctor_dtor_returns_void) {
3179 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3180 Diag(ReturnLoc, D)
3181 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3182 << RetValExp->getSourceRange();
3183 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003184 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003185 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003186 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003187 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003188
3189 int FunctionKind = 0;
3190 if (isa<ObjCMethodDecl>(CurDecl))
3191 FunctionKind = 1;
3192 else if (isa<CXXConstructorDecl>(CurDecl))
3193 FunctionKind = 2;
3194 else if (isa<CXXDestructorDecl>(CurDecl))
3195 FunctionKind = 3;
3196
Nick Lewycky1be750a2011-06-01 07:44:31 +00003197 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003198 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003199 << RetValExp->getSourceRange();
3200 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
Sebastian Redleef474c2012-02-22 10:50:08 +00003203 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003204 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3205 if (ER.isInvalid())
3206 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003207 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003208 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
Craig Topperc3ec1492014-05-26 06:22:03 +00003211 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003212 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003213 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003214
David Majnemer2887ad32014-12-13 08:12:56 +00003215 unsigned DiagID;
3216 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3217 // C++11 [stmt.return]p2
3218 DiagID = diag::err_constexpr_return_missing_expr;
3219 FD->setInvalidDecl();
3220 } else if (getLangOpts().C99) {
3221 // C99 6.8.6.4p1 (ext_ since GCC warns)
3222 DiagID = diag::ext_return_missing_expr;
3223 } else {
3224 // C90 6.6.6.4p4
3225 DiagID = diag::warn_return_missing_expr;
3226 }
3227
3228 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003229 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003230 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003231 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003232
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003233 Result = new (Context) ReturnStmt(ReturnLoc);
3234 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003235 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003236 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003237
3238 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3239
3240 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3241 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3242 // function return.
3243
3244 // In C++ the return statement is handled via a copy initialization,
3245 // the C version of which boils down to CheckSingleAssignmentConstraints.
3246 if (RetValExp)
3247 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003248 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003249 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003251 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003252 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003254 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003255 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003256 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003257 return StmtError();
3258 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003259 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003260
3261 // If we have a related result type, we need to implicitly
3262 // convert back to the formal result type. We can't pretend to
3263 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003264 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003265 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003266 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3267 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003268 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3269 if (Res.isInvalid()) {
3270 // FIXME: Clean up temporaries here anyway?
3271 return StmtError();
3272 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003273 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003274 }
3275
Artyom Skrobov9f213442014-01-24 11:10:39 +00003276 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3277 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279
John McCallacf0ee52010-10-08 02:01:28 +00003280 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003281 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3282 if (ER.isInvalid())
3283 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003284 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003285 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003286 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288
3289 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003290 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003291 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003292 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003293
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003294 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003295}
3296
John McCalldadc5752010-08-24 06:29:42 +00003297StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003298Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003299 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003300 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003301 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003302 if (Var && Var->isInvalidDecl())
3303 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003305 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003306}
3307
John McCalldadc5752010-08-24 06:29:42 +00003308StmtResult
John McCallb268a282010-08-23 23:25:46 +00003309Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003310 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003311}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003312
John McCalldadc5752010-08-24 06:29:42 +00003313StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003315 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003316 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003317 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3318
John McCallaab3e412010-08-25 08:40:02 +00003319 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003320 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003321 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3322 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003323}
3324
John McCall0bd3e402012-05-08 21:41:25 +00003325StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003326 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003327 ExprResult Result = DefaultLvalueConversion(Throw);
3328 if (Result.isInvalid())
3329 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003330
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003331 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003332 if (Result.isInvalid())
3333 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003334 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003335
Douglas Gregor2900c162010-04-22 21:44:01 +00003336 QualType ThrowType = Throw->getType();
3337 // Make sure the expression type is an ObjC pointer or "void *".
3338 if (!ThrowType->isDependentType() &&
3339 !ThrowType->isObjCObjectPointerType()) {
3340 const PointerType *PT = ThrowType->getAs<PointerType>();
3341 if (!PT || !PT->getPointeeType()->isVoidType())
3342 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3343 << Throw->getType() << Throw->getSourceRange());
3344 }
3345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003347 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003348}
3349
John McCalldadc5752010-08-24 06:29:42 +00003350StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003351Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003352 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003353 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003354 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3355
John McCallb268a282010-08-23 23:25:46 +00003356 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003357 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003358 // in the context of an @catch clause).
3359 Scope *AtCatchParent = CurScope;
3360 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3361 AtCatchParent = AtCatchParent->getParent();
3362 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003363 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364 }
John McCallb268a282010-08-23 23:25:46 +00003365 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003366}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003367
John McCalld9bb7432011-07-27 21:50:02 +00003368ExprResult
3369Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3370 ExprResult result = DefaultLvalueConversion(operand);
3371 if (result.isInvalid())
3372 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003373 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003374
3375 // Make sure the expression type is an ObjC pointer or "void *".
3376 QualType type = operand->getType();
3377 if (!type->isDependentType() &&
3378 !type->isObjCObjectPointerType()) {
3379 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003380 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3381 if (getLangOpts().CPlusPlus) {
3382 if (RequireCompleteType(atLoc, type,
3383 diag::err_incomplete_receiver_type))
3384 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3385 << type << operand->getSourceRange();
3386
3387 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3388 if (!result.isUsable())
3389 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3390 << type << operand->getSourceRange();
3391
3392 operand = result.get();
3393 } else {
3394 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3395 << type << operand->getSourceRange();
3396 }
3397 }
John McCalld9bb7432011-07-27 21:50:02 +00003398 }
3399
3400 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003401 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003402}
3403
John McCalldadc5752010-08-24 06:29:42 +00003404StmtResult
John McCallb268a282010-08-23 23:25:46 +00003405Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3406 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003407 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003408 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003409 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003410}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003411
3412/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3413/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003414StmtResult
John McCall48871652010-08-21 09:40:31 +00003415Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003416 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003417 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003418 return new (Context)
3419 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003420}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003421
John McCall31168b02011-06-15 23:02:42 +00003422StmtResult
3423Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3424 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003425 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003426}
3427
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003428namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003429class CatchHandlerType {
3430 QualType QT;
3431 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003432
Aaron Ballman8aee642902015-04-08 00:05:29 +00003433 // This is a special constructor to be used only with DenseMapInfo's
3434 // getEmptyKey() and getTombstoneKey() functions.
3435 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3436 enum Unique { ForDenseMap };
3437 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3438
Sebastian Redl63c4da02009-07-29 17:15:45 +00003439public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003440 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003441 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003442 /// level pointer and cv-qualifiers.
3443 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3444 if (QT->isPointerType())
3445 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003446
Aaron Ballman8aee642902015-04-08 00:05:29 +00003447 if (IsPointer || QT->isReferenceType())
3448 QT = QT->getPointeeType();
3449 QT = QT.getUnqualifiedType();
3450 }
3451
3452 /// Used when creating a CatchHandlerType from a base class type; pretends the
3453 /// type passed in had the pointer qualifier, does not need to get an
3454 /// unqualified type.
3455 CatchHandlerType(QualType QT, bool IsPointer)
3456 : QT(QT), IsPointer(IsPointer) {}
3457
3458 QualType underlying() const { return QT; }
3459 bool isPointer() const { return IsPointer; }
3460
3461 friend bool operator==(const CatchHandlerType &LHS,
3462 const CatchHandlerType &RHS) {
3463 // If the pointer qualification does not match, we can return early.
3464 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003465 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003466 // Otherwise, check the underlying type without cv-qualifiers.
3467 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003468 }
3469};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003470} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003471
Aaron Ballman8aee642902015-04-08 00:05:29 +00003472namespace llvm {
3473template <> struct DenseMapInfo<CatchHandlerType> {
3474 static CatchHandlerType getEmptyKey() {
3475 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3476 CatchHandlerType::ForDenseMap);
3477 }
3478
3479 static CatchHandlerType getTombstoneKey() {
3480 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3481 CatchHandlerType::ForDenseMap);
3482 }
3483
3484 static unsigned getHashValue(const CatchHandlerType &Base) {
3485 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3486 }
3487
3488 static bool isEqual(const CatchHandlerType &LHS,
3489 const CatchHandlerType &RHS) {
3490 return LHS == RHS;
3491 }
3492};
3493
3494// It's OK to treat CatchHandlerType as a POD type.
3495template <> struct isPodLike<CatchHandlerType> {
3496 static const bool value = true;
3497};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003498}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003499
3500namespace {
3501class CatchTypePublicBases {
3502 ASTContext &Ctx;
3503 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3504 const bool CheckAgainstPointer;
3505
3506 CXXCatchStmt *FoundHandler;
3507 CanQualType FoundHandlerType;
3508
3509public:
3510 CatchTypePublicBases(
3511 ASTContext &Ctx,
3512 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3513 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3514 FoundHandler(nullptr) {}
3515
3516 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3517 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3518
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003519 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003520 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003521 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3522 auto M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003523 auto I = M.find(Check);
3524 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003525 FoundHandler = I->second;
3526 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003527 return true;
3528 }
3529 }
3530 return false;
3531 }
3532};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003533}
Dan Gohman28ade552010-07-26 21:25:24 +00003534
Sebastian Redl9b244a82008-12-22 21:35:02 +00003535/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3536/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003537StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3538 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003539 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003540 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003541 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003542 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003543
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003544 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3545 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3546
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003547 sema::FunctionScopeInfo *FSI = getCurFunction();
3548
Reid Klecknere7175912015-02-02 22:15:31 +00003549 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003550 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003551 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003552 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003553 }
3554
Robert Wilhelmcafda822013-08-22 09:20:03 +00003555 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003556 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003557 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003558
Aaron Ballman8aee642902015-04-08 00:05:29 +00003559 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003560 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003561 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003562
Aaron Ballman8aee642902015-04-08 00:05:29 +00003563 // Diagnose when the handler is a catch-all handler, but it isn't the last
3564 // handler for the try block. [except.handle]p5. Also, skip exception
3565 // declarations that are invalid, since we can't usefully report on them.
3566 if (!H->getExceptionDecl()) {
3567 if (i < NumHandlers - 1)
3568 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003569 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003570 } else if (H->getExceptionDecl()->isInvalidDecl())
3571 continue;
3572
3573 // Walk the type hierarchy to diagnose when this type has already been
3574 // handled (duplication), or cannot be handled (derivation inversion). We
3575 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003576 CatchHandlerType HandlerCHT =
3577 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003578
3579 // We can ignore whether the type is a reference or a pointer; we need the
3580 // underlying declaration type in order to get at the underlying record
3581 // decl, if there is one.
3582 QualType Underlying = HandlerCHT.underlying();
3583 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3584 if (!RD->hasDefinition())
3585 continue;
3586 // Check that none of the public, unambiguous base classes are in the
3587 // map ([except.handle]p1). Give the base classes the same pointer
3588 // qualification as the original type we are basing off of. This allows
3589 // comparison against the handler type using the same top-level pointer
3590 // as the original type.
3591 CXXBasePaths Paths;
3592 Paths.setOrigin(RD);
3593 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003594 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003595 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3596 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3597 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3598 diag::warn_exception_caught_by_earlier_handler)
3599 << H->getCaughtType();
3600 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3601 diag::note_previous_exception_handler)
3602 << Problem->getCaughtType();
3603 }
3604 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003605 }
Mike Stump11289f42009-09-09 15:08:12 +00003606
Aaron Ballman8aee642902015-04-08 00:05:29 +00003607 // Add the type the list of ones we have handled; diagnose if we've already
3608 // handled it.
3609 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3610 if (!R.second) {
3611 const CXXCatchStmt *Problem = R.first->second;
3612 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3613 diag::warn_exception_caught_by_earlier_handler)
3614 << H->getCaughtType();
3615 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3616 diag::note_previous_exception_handler)
3617 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003618 }
3619 }
Mike Stump11289f42009-09-09 15:08:12 +00003620
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003621 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003622
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003623 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003624}
John Wiegley1c0675e2011-04-28 01:08:34 +00003625
Reid Klecknere7175912015-02-02 22:15:31 +00003626StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3627 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003628 assert(TryBlock && Handler);
3629
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003630 sema::FunctionScopeInfo *FSI = getCurFunction();
3631
Reid Klecknere7175912015-02-02 22:15:31 +00003632 // SEH __try is incompatible with C++ try. Borland appears to support this,
3633 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003634 if (!getLangOpts().Borland) {
3635 if (FSI->FirstCXXTryLoc.isValid()) {
3636 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3637 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3638 }
Reid Klecknere7175912015-02-02 22:15:31 +00003639 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003640
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003641 FSI->setHasSEHTry(TryLoc);
3642
3643 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3644 // track if they use SEH.
3645 DeclContext *DC = CurContext;
3646 while (DC && !DC->isFunctionOrMethod())
3647 DC = DC->getParent();
3648 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3649 if (FD)
3650 FD->setUsesSEHTry(true);
3651 else
3652 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003653
Reid Kleckner8819a402015-07-10 00:16:25 +00003654 // Reject __try on unsupported targets.
3655 if (!Context.getTargetInfo().isSEHTrySupported())
3656 Diag(TryLoc, diag::err_seh_try_unsupported);
3657
Reid Klecknere7175912015-02-02 22:15:31 +00003658 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003659}
3660
3661StmtResult
3662Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3663 Expr *FilterExpr,
3664 Stmt *Block) {
3665 assert(FilterExpr && Block);
3666
3667 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003668 return StmtError(Diag(FilterExpr->getExprLoc(),
3669 diag::err_filter_expression_integral)
3670 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003671 }
3672
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003673 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003674}
3675
Nico Weberd64657f2015-03-09 02:47:59 +00003676void Sema::ActOnStartSEHFinallyBlock() {
3677 CurrentSEHFinally.push_back(CurScope);
3678}
3679
Nico Weberce903292015-03-09 03:17:15 +00003680void Sema::ActOnAbortSEHFinallyBlock() {
3681 CurrentSEHFinally.pop_back();
3682}
3683
Nico Weberd64657f2015-03-09 02:47:59 +00003684StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003685 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003686 CurrentSEHFinally.pop_back();
3687 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003688}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003689
Nico Weberc7d05962014-07-06 22:32:59 +00003690StmtResult
3691Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003692 Scope *SEHTryParent = CurScope;
3693 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3694 SEHTryParent = SEHTryParent->getParent();
3695 if (!SEHTryParent)
3696 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003697 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003698
Nico Weber9b982072014-07-07 00:12:30 +00003699 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003700}
3701
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003702StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3703 bool IsIfExists,
3704 NestedNameSpecifierLoc QualifierLoc,
3705 DeclarationNameInfo NameInfo,
3706 Stmt *Nested)
3707{
3708 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003709 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003710 cast<CompoundStmt>(Nested));
3711}
3712
3713
Chad Rosier02a84392012-08-10 17:56:09 +00003714StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003715 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003716 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003717 UnqualifiedId &Name,
3718 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003719 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003720 SS.getWithLocInContext(Context),
3721 GetNameFromUnqualifiedId(Name),
3722 Nested);
3723}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003724
3725RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003726Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3727 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003728 DeclContext *DC = CurContext;
3729 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3730 DC = DC->getParent();
3731
Craig Topperc3ec1492014-05-26 06:22:03 +00003732 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003733 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003734 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3735 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003736 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003737 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003738
Alexey Bataev330de032014-10-29 12:21:55 +00003739 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003740 DC->addDecl(RD);
3741 RD->setImplicit();
3742 RD->startDefinition();
3743
Alexey Bataev9959db52014-05-06 10:08:46 +00003744 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003745 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003746 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003747 return RD;
3748}
3749
3750static void buildCapturedStmtCaptureList(
3751 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3752 SmallVectorImpl<Expr *> &CaptureInits,
3753 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3754
3755 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3756 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3757
3758 if (Cap->isThisCapture()) {
3759 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3760 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003761 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003762 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003763 } else if (Cap->isVLATypeCapture()) {
3764 Captures.push_back(
3765 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3766 CaptureInits.push_back(nullptr);
3767 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003768 }
3769
3770 assert(Cap->isReferenceCapture() &&
3771 "non-reference capture not yet implemented");
3772
3773 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3774 CapturedStmt::VCK_ByRef,
3775 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003776 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003777 }
3778}
3779
3780void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003781 CapturedRegionKind Kind,
3782 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003783 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003784 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003785
Alexey Bataev9959db52014-05-06 10:08:46 +00003786 // Build the context parameter
3787 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3788 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3789 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3790 ImplicitParamDecl *Param
3791 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3792 DC->addDecl(Param);
3793
3794 CD->setContextParam(0, Param);
3795
3796 // Enter the capturing scope for this captured region.
3797 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3798
3799 if (CurScope)
3800 PushDeclContext(CurScope, CD);
3801 else
3802 CurContext = CD;
3803
3804 PushExpressionEvaluationContext(PotentiallyEvaluated);
3805}
3806
3807void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3808 CapturedRegionKind Kind,
3809 ArrayRef<CapturedParamNameType> Params) {
3810 CapturedDecl *CD = nullptr;
3811 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3812
3813 // Build the context parameter
3814 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3815 bool ContextIsFound = false;
3816 unsigned ParamNum = 0;
3817 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3818 E = Params.end();
3819 I != E; ++I, ++ParamNum) {
3820 if (I->second.isNull()) {
3821 assert(!ContextIsFound &&
3822 "null type has been found already for '__context' parameter");
3823 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3824 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3825 ImplicitParamDecl *Param
3826 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3827 DC->addDecl(Param);
3828 CD->setContextParam(ParamNum, Param);
3829 ContextIsFound = true;
3830 } else {
3831 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3832 ImplicitParamDecl *Param
3833 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3834 DC->addDecl(Param);
3835 CD->setParam(ParamNum, Param);
3836 }
3837 }
3838 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003839 if (!ContextIsFound) {
3840 // Add __context implicitly if it is not specified.
3841 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3842 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3843 ImplicitParamDecl *Param =
3844 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3845 DC->addDecl(Param);
3846 CD->setContextParam(ParamNum, Param);
3847 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003848 // Enter the capturing scope for this captured region.
3849 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3850
3851 if (CurScope)
3852 PushDeclContext(CurScope, CD);
3853 else
3854 CurContext = CD;
3855
3856 PushExpressionEvaluationContext(PotentiallyEvaluated);
3857}
3858
Wei Pan17fbf6e2013-05-04 03:59:06 +00003859void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003860 DiscardCleanupsInEvaluationContext();
3861 PopExpressionEvaluationContext();
3862
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003863 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3864 RecordDecl *Record = RSI->TheRecordDecl;
3865 Record->setInvalidDecl();
3866
Aaron Ballman62e47c42014-03-10 13:43:55 +00003867 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003868 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3869 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003870
Wei Pan17fbf6e2013-05-04 03:59:06 +00003871 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003872 PopFunctionScopeInfo();
3873}
3874
3875StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3876 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3877
3878 SmallVector<CapturedStmt::Capture, 4> Captures;
3879 SmallVector<Expr *, 4> CaptureInits;
3880 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3881
3882 CapturedDecl *CD = RSI->TheCapturedDecl;
3883 RecordDecl *RD = RSI->TheRecordDecl;
3884
Wei Pan17fbf6e2013-05-04 03:59:06 +00003885 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3886 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003887 CaptureInits, CD, RD);
3888
3889 CD->setBody(Res->getCapturedStmt());
3890 RD->completeDefinition();
3891
Wei Pan17fbf6e2013-05-04 03:59:06 +00003892 DiscardCleanupsInEvaluationContext();
3893 PopExpressionEvaluationContext();
3894
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003895 PopDeclContext();
3896 PopFunctionScopeInfo();
3897
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003898 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003899}