blob: 33c71318b638a084691e86a143b2257b142537c7 [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 Klecknerddd40962015-04-28 22:19:32 +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) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000486 // If the condition was invalid, discard the if statement. We could recover
487 // better by replacing it with a valid expr, but don't do that yet.
488 if (!CondVal.get() && !CondVar) {
489 getCurFunction()->setHasDroppedStmt();
490 return StmtError();
491 }
492
John McCalldadc5752010-08-24 06:29:42 +0000493 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000494
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000496 if (CondVar) {
497 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000498 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000499 if (CondResult.isInvalid())
500 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000501 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000502 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000503 if (!ConditionExpr)
504 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000505
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000506 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000507
John McCallb268a282010-08-23 23:25:46 +0000508 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000509 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
510 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000511 }
512
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000513 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000514
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000515 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
516 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000517}
Steve Naroff86272ea2007-05-29 02:14:17 +0000518
Chris Lattner67998452007-08-23 18:29:20 +0000519namespace {
520 struct CaseCompareFunctor {
521 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
522 const llvm::APSInt &RHS) {
523 return LHS.first < RHS;
524 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000525 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
526 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
527 return LHS.first < RHS.first;
528 }
Chris Lattner67998452007-08-23 18:29:20 +0000529 bool operator()(const llvm::APSInt &LHS,
530 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
531 return LHS < RHS.first;
532 }
533 };
534}
535
Chris Lattner4b2ff022007-09-21 18:15:22 +0000536/// CmpCaseVals - Comparison predicate for sorting case values.
537///
538static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
539 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
540 if (lhs.first < rhs.first)
541 return true;
542
543 if (lhs.first == rhs.first &&
544 lhs.second->getCaseLoc().getRawEncoding()
545 < rhs.second->getCaseLoc().getRawEncoding())
546 return true;
547 return false;
548}
549
Douglas Gregorbd6839732010-02-08 22:24:16 +0000550/// CmpEnumVals - Comparison predicate for sorting enumeration values.
551///
552static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
553 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
554{
555 return lhs.first < rhs.first;
556}
557
558/// EqEnumVals - Comparison preficate for uniqing enumeration values.
559///
560static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
561 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
562{
563 return lhs.first == rhs.first;
564}
565
Chris Lattnera96d4272009-10-16 16:45:22 +0000566/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
567/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000568static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
569 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
570 expr = cleanups->getSubExpr();
571 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
572 if (impcast->getCastKind() != CK_IntegralCast) break;
573 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000574 }
575 return expr->getType();
576}
577
John McCalldadc5752010-08-24 06:29:42 +0000578StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000580 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000581 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000582
Craig Topperc3ec1492014-05-26 06:22:03 +0000583 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000584 if (CondVar) {
585 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000586 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
587 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000588 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000590 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
John McCallb268a282010-08-23 23:25:46 +0000593 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000594 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregore2b37442012-05-04 22:38:52 +0000596 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
597 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000598
Douglas Gregore2b37442012-05-04 22:38:52 +0000599 public:
600 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000601 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
602 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000603
Craig Toppere14c0f82014-03-12 04:55:44 +0000604 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
605 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000606 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
607 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000608
Craig Toppere14c0f82014-03-12 04:55:44 +0000609 SemaDiagnosticBuilder diagnoseIncomplete(
610 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000611 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
612 << T << Cond->getSourceRange();
613 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000614
Craig Toppere14c0f82014-03-12 04:55:44 +0000615 SemaDiagnosticBuilder diagnoseExplicitConv(
616 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000617 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
618 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000619
Craig Toppere14c0f82014-03-12 04:55:44 +0000620 SemaDiagnosticBuilder noteExplicitConv(
621 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000622 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
623 << ConvTy->isEnumeralType() << ConvTy;
624 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000625
Craig Toppere14c0f82014-03-12 04:55:44 +0000626 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
627 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000628 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
629 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000630
Craig Toppere14c0f82014-03-12 04:55:44 +0000631 SemaDiagnosticBuilder noteAmbiguous(
632 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000633 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
634 << ConvTy->isEnumeralType() << ConvTy;
635 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000636
Craig Toppere14c0f82014-03-12 04:55:44 +0000637 SemaDiagnosticBuilder diagnoseConversion(
638 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000639 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000640 }
641 } SwitchDiagnoser(Cond);
642
Richard Smithccc11812013-05-21 19:05:48 +0000643 CondResult =
644 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000645 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000646 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000647
John McCall5939b162011-08-06 07:30:58 +0000648 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
649 CondResult = UsualUnaryConversions(Cond);
650 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000651 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000652
John McCall48871652010-08-21 09:40:31 +0000653 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000654 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000655 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000656 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000657 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000658 }
John McCalla95172b2010-08-01 00:26:45 +0000659
John McCallaab3e412010-08-25 08:40:02 +0000660 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
John McCallb268a282010-08-23 23:25:46 +0000662 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000663 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000664 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000665}
666
Gabor Greif16e02862010-10-01 22:05:14 +0000667static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000668 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000669 Val.setIsSigned(IsSigned);
670}
671
Richard Smith077d0832014-08-04 00:40:48 +0000672/// Check the specified case value is in range for the given unpromoted switch
673/// type.
674static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
675 unsigned UnpromotedWidth, bool UnpromotedSign) {
676 // If the case value was signed and negative and the switch expression is
677 // unsigned, don't bother to warn: this is implementation-defined behavior.
678 // FIXME: Introduce a second, default-ignored warning for this case?
679 if (UnpromotedWidth < Val.getBitWidth()) {
680 llvm::APSInt ConvVal(Val);
681 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
682 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
683 // FIXME: Use different diagnostics for overflow in conversion to promoted
684 // type versus "switch expression cannot have this value". Use proper
685 // IntRange checking rather than just looking at the unpromoted type here.
686 if (ConvVal != Val)
687 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
688 << ConvVal.toString(10);
689 }
690}
691
Alexis Hunt724f14e2014-11-28 00:53:20 +0000692typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
693
Dmitri Gribenko58683752013-12-05 22:52:07 +0000694/// Returns true if we should emit a diagnostic about this case expression not
695/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000696static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000697 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000698 const Expr *CaseExpr,
699 EnumValsTy::iterator &EI,
700 EnumValsTy::iterator &EIEnd,
701 const llvm::APSInt &Val) {
702 bool FlagType = ED->hasAttr<FlagEnumAttr>();
703
704 if (const DeclRefExpr *DRE =
705 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000706 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000707 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000708 QualType EnumType = S.Context.getTypeDeclType(ED);
709 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
710 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000711 return false;
712 }
713 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000714
715 if (FlagType) {
716 return !S.IsValueInFlagEnum(ED, Val, false);
717 } else {
718 while (EI != EIEnd && EI->first < Val)
719 EI++;
720
721 if (EI != EIEnd && EI->first == Val)
722 return false;
723 }
724
Dmitri Gribenko58683752013-12-05 22:52:07 +0000725 return true;
726}
727
John McCalldadc5752010-08-24 06:29:42 +0000728StmtResult
John McCallb268a282010-08-23 23:25:46 +0000729Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
730 Stmt *BodyStmt) {
731 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000732 assert(SS == getCurFunction()->SwitchStack.back() &&
733 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000734
David Majnemer418ad3f2014-12-15 07:46:12 +0000735 getCurFunction()->SwitchStack.pop_back();
736
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000737 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000738 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000739
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000740 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000741 if (!CondExpr) return StmtError();
742
743 QualType CondType = CondExpr->getType();
744
John McCalld3dfbd62010-05-18 03:19:21 +0000745 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000746 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000747 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000748
Chris Lattnera96d4272009-10-16 16:45:22 +0000749 // C++ 6.4.2.p2:
750 // Integral promotions are performed (on the switch condition).
751 //
752 // A case value unrepresentable by the original switch condition
753 // type (before the promotion) doesn't make sense, even when it can
754 // be represented by the promoted type. Therefore we need to find
755 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000756 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000757 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000759 // appropriate type now, just return an error.
760 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000761 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000762
Chris Lattner4ebae652010-04-16 23:34:13 +0000763 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000764 // switch(bool_expr) {...} is often a programmer error, e.g.
765 // switch(n && mask) { ... } // Doh - should be "n & mask".
766 // One can always use an if statement instead of switch(bool_expr).
767 Diag(SwitchLoc, diag::warn_bool_switch_condition)
768 << CondExpr->getSourceRange();
769 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000770 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000771
Richard Smith077d0832014-08-04 00:40:48 +0000772 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000773 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000774 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000775 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000776 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
777 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
778
779 // Get the width and signedness that the condition might actually have, for
780 // warning purposes.
781 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
782 // type.
783 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000784 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000785 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000786 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000787
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000788 // Accumulate all of the case values in a vector so that we can sort them
789 // and detect duplicates. This vector contains the APInt for the case after
790 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000791 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000792 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000794 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000795 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
796 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattner10cb5e52007-08-23 06:23:56 +0000800 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000802 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000803 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000804
Anders Carlsson51873c22007-07-22 07:07:56 +0000805 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000806 if (TheDefaultStmt) {
807 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000808 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000809
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000810 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000811 // we'll return a valid AST. This requires recursing down the AST and
812 // finding it, not something we are set up to do right now. For now,
813 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000814 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000815 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000816 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000818 } else {
819 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattnera65e1f32008-01-16 19:17:22 +0000821 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000822
823 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
824 HasDependentValue = true;
825 break;
826 }
Mike Stump11289f42009-09-09 15:08:12 +0000827
Richard Smithf8379a02012-01-18 23:55:52 +0000828 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000829
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000830 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000831 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
832 // constant expression of the promoted type of the switch condition.
833 ExprResult ConvLo =
834 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
835 if (ConvLo.isInvalid()) {
836 CaseListIsErroneous = true;
837 continue;
838 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000839 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000840 } else {
841 // We already verified that the expression has a i-c-e value (C99
842 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000843 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000844
845 // If the LHS is not the same type as the condition, insert an implicit
846 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000847 Lo = DefaultLvalueConversion(Lo).get();
848 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000849 }
850
Richard Smith077d0832014-08-04 00:40:48 +0000851 // Check the unconverted value is within the range of possible values of
852 // the switch expression.
853 checkCaseValue(*this, Lo->getLocStart(), LoVal,
854 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
855
856 // Convert the value to the same width/sign as the condition.
857 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000858
Chris Lattnera65e1f32008-01-16 19:17:22 +0000859 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner10cb5e52007-08-23 06:23:56 +0000861 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000862 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000863 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000864 CS->getRHS()->isValueDependent()) {
865 HasDependentValue = true;
866 break;
867 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000868 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000869 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000870 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000871 }
872 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000873
874 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000875 // If we don't have a default statement, check whether the
876 // condition is constant.
877 llvm::APSInt ConstantCondValue;
878 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000879 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000880 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
881 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000882 assert(!HasConstantCond ||
883 (ConstantCondValue.getBitWidth() == CondWidth &&
884 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000885 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000886 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000887
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000888 // Sort all the scalar case values so we can easily detect duplicates.
889 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
890
891 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000892 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
893 if (ShouldCheckConstantCond &&
894 CaseVals[i].first == ConstantCondValue)
895 ShouldCheckConstantCond = false;
896
897 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000898 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000899 // First, determine if either case value has a name
900 StringRef PrevString, CurrString;
901 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
902 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
903 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
904 PrevString = DeclRef->getDecl()->getName();
905 }
906 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
907 CurrString = DeclRef->getDecl()->getName();
908 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000909 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000910 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000911
912 if (PrevString == CurrString)
913 Diag(CaseVals[i].second->getLHS()->getLocStart(),
914 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000915 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000916 else
917 Diag(CaseVals[i].second->getLHS()->getLocStart(),
918 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000919 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
920 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000921 CaseValStr;
922
John McCalld3dfbd62010-05-18 03:19:21 +0000923 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000924 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000925 // FIXME: We really want to remove the bogus case stmt from the
926 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000927 CaseListIsErroneous = true;
928 }
929 }
930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000932 // Detect duplicate case ranges, which usually don't exist at all in
933 // the first place.
934 if (!CaseRanges.empty()) {
935 // Sort all the case ranges by their low value so we can easily detect
936 // overlaps between ranges.
937 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000938
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000939 // Scan the ranges, computing the high values and removing empty ranges.
940 std::vector<llvm::APSInt> HiVals;
941 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000942 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000943 CaseStmt *CR = CaseRanges[i].second;
944 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000945 llvm::APSInt HiVal;
946
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000947 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000948 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
949 // constant expression of the promoted type of the switch condition.
950 ExprResult ConvHi =
951 CheckConvertedConstantExpression(Hi, CondType, HiVal,
952 CCEK_CaseValue);
953 if (ConvHi.isInvalid()) {
954 CaseListIsErroneous = true;
955 continue;
956 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000957 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000958 } else {
959 HiVal = Hi->EvaluateKnownConstInt(Context);
960
961 // If the RHS is not the same type as the condition, insert an
962 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000963 Hi = DefaultLvalueConversion(Hi).get();
964 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000965 }
Mike Stump11289f42009-09-09 15:08:12 +0000966
Richard Smith077d0832014-08-04 00:40:48 +0000967 // Check the unconverted value is within the range of possible values of
968 // the switch expression.
969 checkCaseValue(*this, Hi->getLocStart(), HiVal,
970 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
971
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000972 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000973 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000975 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000976
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000977 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000978 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000979 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
980 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000981 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000982 CaseRanges.erase(CaseRanges.begin()+i);
983 --i, --e;
984 continue;
985 }
John McCalld3dfbd62010-05-18 03:19:21 +0000986
987 if (ShouldCheckConstantCond &&
988 LoVal <= ConstantCondValue &&
989 ConstantCondValue <= HiVal)
990 ShouldCheckConstantCond = false;
991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 HiVals.push_back(HiVal);
993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 // Rescan the ranges, looking for overlap with singleton values and other
996 // ranges. Since the range list is sorted, we only need to compare case
997 // ranges with their neighbors.
998 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
999 llvm::APSInt &CRLo = CaseRanges[i].first;
1000 llvm::APSInt &CRHi = HiVals[i];
1001 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 // Check to see whether the case range overlaps with any
1004 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001005 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001006 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001007
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001008 // Find the smallest value >= the lower bound. If I is in the
1009 // case range, then we have overlap.
1010 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1011 CaseVals.end(), CRLo,
1012 CaseCompareFunctor());
1013 if (I != CaseVals.end() && I->first < CRHi) {
1014 OverlapVal = I->first; // Found overlap with scalar.
1015 OverlapStmt = I->second;
1016 }
Mike Stump11289f42009-09-09 15:08:12 +00001017
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001018 // Find the smallest value bigger than the upper bound.
1019 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1020 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1021 OverlapVal = (I-1)->first; // Found overlap with scalar.
1022 OverlapStmt = (I-1)->second;
1023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001025 // Check to see if this case stmt overlaps with the subsequent
1026 // case range.
1027 if (i && CRLo <= HiVals[i-1]) {
1028 OverlapVal = HiVals[i-1]; // Found overlap with range.
1029 OverlapStmt = CaseRanges[i-1].second;
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001032 if (OverlapStmt) {
1033 // If we have a duplicate, report it.
1034 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1035 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001036 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001038 // FIXME: We really want to remove the bogus case stmt from the
1039 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001040 CaseListIsErroneous = true;
1041 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001042 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001043 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001044
John McCalld3dfbd62010-05-18 03:19:21 +00001045 // Complain if we have a constant condition and we didn't find a match.
1046 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1047 // TODO: it would be nice if we printed enums as enums, chars as
1048 // chars, etc.
1049 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1050 << ConstantCondValue.toString(10)
1051 << CondExpr->getSourceRange();
1052 }
1053
1054 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001055 // values. We only issue a warning if there is not 'default:', but
1056 // we still do the analysis to preserve this information in the AST
1057 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001058 //
Chris Lattner51679082010-09-16 17:09:42 +00001059 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001060
Douglas Gregorbd6839732010-02-08 22:24:16 +00001061 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001062 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001063 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001064 EnumValsTy EnumVals;
1065
John McCalld3dfbd62010-05-18 03:19:21 +00001066 // Gather all enum values, set their type and sort them,
1067 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001068 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001069 llvm::APSInt Val = EDI->getInitVal();
1070 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001071 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001072 }
1073 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001074 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001075 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001076
1077 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001078 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001079 CI != CaseVals.end(); CI++) {
1080 Expr *CaseExpr = CI->second->getLHS();
1081 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1082 CI->first))
1083 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1084 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001085 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001086
David Blaikiee476f972012-01-22 02:31:55 +00001087 // See which of case ranges aren't in enum
1088 EI = EnumVals.begin();
1089 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001090 RI != CaseRanges.end(); RI++) {
1091 Expr *CaseExpr = RI->second->getLHS();
1092 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1093 RI->first))
1094 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1095 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001096
Chad Rosier02a84392012-08-10 17:56:09 +00001097 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001098 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1099 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001100
1101 CaseExpr = RI->second->getRHS();
1102 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1103 Hi))
1104 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1105 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Ted Kremenekc42f3452010-09-09 00:05:53 +00001108 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001109 auto CI = CaseVals.begin();
1110 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001111 bool hasCasesNotInSwitch = false;
1112
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001113 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001114
Alexis Hunt724f14e2014-11-28 00:53:20 +00001115 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001116 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001117 while (CI != CaseVals.end() && CI->first < EI->first)
1118 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001119
Douglas Gregorbd6839732010-02-08 22:24:16 +00001120 if (CI != CaseVals.end() && CI->first == EI->first)
1121 continue;
1122
Ted Kremenekc42f3452010-09-09 00:05:53 +00001123 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001124 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001125 llvm::APSInt Hi =
1126 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001127 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001128 if (EI->first <= Hi)
1129 break;
1130 }
1131
Ted Kremenekc42f3452010-09-09 00:05:53 +00001132 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001133 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001134 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001135 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
David Blaikie60ac6382012-01-23 04:46:12 +00001138 if (TheDefaultStmt && UnhandledNames.empty())
1139 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001140
Chris Lattner51679082010-09-16 17:09:42 +00001141 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001142 if (!UnhandledNames.empty()) {
1143 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1144 TheDefaultStmt ? diag::warn_def_missing_case
1145 : diag::warn_missing_case)
1146 << (int)UnhandledNames.size();
1147
1148 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1149 I != E; ++I)
1150 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001151 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001152
1153 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001154 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001155 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001156 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001157
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001158 if (BodyStmt)
1159 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1160 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001161
Mike Stump87c57ac2009-05-16 07:39:55 +00001162 // FIXME: If the case list was broken is some way, we don't have a good system
1163 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001164 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001165 return StmtError();
1166
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001167 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001168}
1169
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001170void
1171Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1172 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001173 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001174 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001175
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001176 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001177 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001178 SrcType->isIntegerType()) {
1179 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1180 SrcExpr->isIntegerConstantExpr(Context)) {
1181 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001182 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001183 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1184
1185 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001186 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001187 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001188
Alexis Hunt724f14e2014-11-28 00:53:20 +00001189 if (ED->hasAttr<FlagEnumAttr>()) {
1190 if (!IsValueInFlagEnum(ED, RhsVal, true))
1191 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001192 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001193 } else {
1194 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1195 EnumValsTy;
1196 EnumValsTy EnumVals;
1197
1198 // Gather all enum values, set their type and sort them,
1199 // allowing easier comparison with rhs constant.
1200 for (auto *EDI : ED->enumerators()) {
1201 llvm::APSInt Val = EDI->getInitVal();
1202 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1203 EnumVals.push_back(std::make_pair(Val, EDI));
1204 }
1205 if (EnumVals.empty())
1206 return;
1207 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1208 EnumValsTy::iterator EIend =
1209 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1210
1211 // See which values aren't in the enum.
1212 EnumValsTy::const_iterator EI = EnumVals.begin();
1213 while (EI != EIend && EI->first < RhsVal)
1214 EI++;
1215 if (EI == EIend || EI->first != RhsVal) {
1216 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1217 << DstType.getUnqualifiedType();
1218 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001219 }
1220 }
1221 }
1222}
1223
John McCalldadc5752010-08-24 06:29:42 +00001224StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001226 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001227 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228
Craig Topperc3ec1492014-05-26 06:22:03 +00001229 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001230 if (CondVar) {
1231 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001232 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001233 if (CondResult.isInvalid())
1234 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001235 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001236 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001237 if (!ConditionExpr)
1238 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001239 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240
John McCallb268a282010-08-23 23:25:46 +00001241 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001242
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001243 if (isa<NullStmt>(Body))
1244 getCurCompoundScope().setHasEmptyLoopBodies();
1245
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001246 return new (Context)
1247 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001248}
1249
John McCalldadc5752010-08-24 06:29:42 +00001250StmtResult
John McCallb268a282010-08-23 23:25:46 +00001251Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001252 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001253 Expr *Cond, SourceLocation CondRParen) {
1254 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001255
Serge Pavlov09f99242014-01-23 15:05:00 +00001256 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001257 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001258 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001259 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001260 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001261
Richard Smith945f8d32013-01-14 22:39:08 +00001262 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001263 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001264 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001265 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
John McCallb268a282010-08-23 23:25:46 +00001267 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001268
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001269 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001270}
1271
Richard Trieu451a5db2012-04-30 18:01:30 +00001272namespace {
1273 // This visitor will traverse a conditional statement and store all
1274 // the evaluated decls into a vector. Simple is set to true if none
1275 // of the excluded constructs are used.
1276 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001277 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001278 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001279 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001280 public:
1281 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001282
Craig Topper4dd9b432014-08-17 23:49:53 +00001283 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001284 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001285 Inherited(S.Context),
1286 Decls(Decls),
1287 Ranges(Ranges),
1288 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001289
Richard Trieu9d228802013-05-31 22:46:45 +00001290 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001291
Richard Trieu9d228802013-05-31 22:46:45 +00001292 // Replaces the method in EvaluatedExprVisitor.
1293 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001294 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001295 }
1296
1297 // Any Stmt not whitelisted will cause the condition to be marked complex.
1298 void VisitStmt(Stmt *S) {
1299 Simple = false;
1300 }
1301
1302 void VisitBinaryOperator(BinaryOperator *E) {
1303 Visit(E->getLHS());
1304 Visit(E->getRHS());
1305 }
1306
1307 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001308 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001309 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001310
Richard Trieu9d228802013-05-31 22:46:45 +00001311 void VisitUnaryOperator(UnaryOperator *E) {
1312 // Skip checking conditionals with derefernces.
1313 if (E->getOpcode() == UO_Deref)
1314 Simple = false;
1315 else
1316 Visit(E->getSubExpr());
1317 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001318
Richard Trieu9d228802013-05-31 22:46:45 +00001319 void VisitConditionalOperator(ConditionalOperator *E) {
1320 Visit(E->getCond());
1321 Visit(E->getTrueExpr());
1322 Visit(E->getFalseExpr());
1323 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001324
Richard Trieu9d228802013-05-31 22:46:45 +00001325 void VisitParenExpr(ParenExpr *E) {
1326 Visit(E->getSubExpr());
1327 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001328
Richard Trieu9d228802013-05-31 22:46:45 +00001329 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1330 Visit(E->getOpaqueValue()->getSourceExpr());
1331 Visit(E->getFalseExpr());
1332 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001333
Richard Trieu9d228802013-05-31 22:46:45 +00001334 void VisitIntegerLiteral(IntegerLiteral *E) { }
1335 void VisitFloatingLiteral(FloatingLiteral *E) { }
1336 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1337 void VisitCharacterLiteral(CharacterLiteral *E) { }
1338 void VisitGNUNullExpr(GNUNullExpr *E) { }
1339 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001340
Richard Trieu9d228802013-05-31 22:46:45 +00001341 void VisitDeclRefExpr(DeclRefExpr *E) {
1342 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1343 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001344
Richard Trieu9d228802013-05-31 22:46:45 +00001345 Ranges.push_back(E->getSourceRange());
1346
1347 Decls.insert(VD);
1348 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001349
1350 }; // end class DeclExtractor
1351
1352 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001353 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001354 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001355 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001356 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001357
Richard Trieu9d228802013-05-31 22:46:45 +00001358 public:
1359 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001360
Craig Topper4dd9b432014-08-17 23:49:53 +00001361 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001362 Stmt *Statement) :
1363 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1364 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001365
Richard Trieu9d228802013-05-31 22:46:45 +00001366 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001367 }
1368
Richard Trieu9d228802013-05-31 22:46:45 +00001369 void VisitReturnStmt(ReturnStmt *S) {
1370 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001371 }
1372
Richard Trieu9d228802013-05-31 22:46:45 +00001373 void VisitBreakStmt(BreakStmt *S) {
1374 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001375 }
1376
Richard Trieu9d228802013-05-31 22:46:45 +00001377 void VisitGotoStmt(GotoStmt *S) {
1378 FoundDecl = true;
1379 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001380
Richard Trieu9d228802013-05-31 22:46:45 +00001381 void VisitCastExpr(CastExpr *E) {
1382 if (E->getCastKind() == CK_LValueToRValue)
1383 CheckLValueToRValueCast(E->getSubExpr());
1384 else
1385 Visit(E->getSubExpr());
1386 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001387
Richard Trieu9d228802013-05-31 22:46:45 +00001388 void CheckLValueToRValueCast(Expr *E) {
1389 E = E->IgnoreParenImpCasts();
1390
1391 if (isa<DeclRefExpr>(E)) {
1392 return;
1393 }
1394
1395 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1396 Visit(CO->getCond());
1397 CheckLValueToRValueCast(CO->getTrueExpr());
1398 CheckLValueToRValueCast(CO->getFalseExpr());
1399 return;
1400 }
1401
1402 if (BinaryConditionalOperator *BCO =
1403 dyn_cast<BinaryConditionalOperator>(E)) {
1404 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1405 CheckLValueToRValueCast(BCO->getFalseExpr());
1406 return;
1407 }
1408
1409 Visit(E);
1410 }
1411
1412 void VisitDeclRefExpr(DeclRefExpr *E) {
1413 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1414 if (Decls.count(VD))
1415 FoundDecl = true;
1416 }
1417
1418 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001419
1420 }; // end class DeclMatcher
1421
1422 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1423 Expr *Third, Stmt *Body) {
1424 // Condition is empty
1425 if (!Second) return;
1426
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001427 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1428 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001429 return;
1430
1431 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1432 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001433 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001434 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001435 DE.Visit(Second);
1436
1437 // Don't analyze complex conditionals.
1438 if (!DE.isSimple()) return;
1439
1440 // No decls found.
1441 if (Decls.size() == 0) return;
1442
Richard Trieu0030f1d2012-05-04 03:01:54 +00001443 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001444 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1445 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001446 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001447 if ((*I)->getType().isVolatileQualified() ||
1448 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001449
1450 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1451 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1452 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1453 return;
1454
1455 // Load decl names into diagnostic.
1456 if (Decls.size() > 4)
1457 PDiag << 0;
1458 else {
1459 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001460 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1461 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001462 I != E; ++I)
1463 PDiag << (*I)->getDeclName();
1464 }
1465
1466 // Load SourceRanges into diagnostic if there is room.
1467 // Otherwise, load the SourceRange of the conditional expression.
1468 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001469 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001470 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001471 I != E; ++I)
1472 PDiag << *I;
1473 else
1474 PDiag << Second->getSourceRange();
1475
1476 S.Diag(Ranges.begin()->getBegin(), PDiag);
1477 }
1478
Richard Trieu4e7c9622013-08-06 21:31:54 +00001479 // If Statement is an incemement or decrement, return true and sets the
1480 // variables Increment and DRE.
1481 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1482 DeclRefExpr *&DRE) {
1483 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1484 switch (UO->getOpcode()) {
1485 default: return false;
1486 case UO_PostInc:
1487 case UO_PreInc:
1488 Increment = true;
1489 break;
1490 case UO_PostDec:
1491 case UO_PreDec:
1492 Increment = false;
1493 break;
1494 }
1495 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1496 return DRE;
1497 }
1498
1499 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1500 FunctionDecl *FD = Call->getDirectCallee();
1501 if (!FD || !FD->isOverloadedOperator()) return false;
1502 switch (FD->getOverloadedOperator()) {
1503 default: return false;
1504 case OO_PlusPlus:
1505 Increment = true;
1506 break;
1507 case OO_MinusMinus:
1508 Increment = false;
1509 break;
1510 }
1511 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1512 return DRE;
1513 }
1514
1515 return false;
1516 }
1517
Serge Pavlov09f99242014-01-23 15:05:00 +00001518 // A visitor to determine if a continue or break statement is a
1519 // subexpression.
1520 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1521 SourceLocation BreakLoc;
1522 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001523 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001524 BreakContinueFinder(Sema &S, Stmt* Body) :
1525 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001526 Visit(Body);
1527 }
1528
Serge Pavlov09f99242014-01-23 15:05:00 +00001529 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001530
1531 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001532 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001533 }
1534
Serge Pavlov09f99242014-01-23 15:05:00 +00001535 void VisitBreakStmt(BreakStmt* E) {
1536 BreakLoc = E->getBreakLoc();
1537 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001538
Serge Pavlov09f99242014-01-23 15:05:00 +00001539 bool ContinueFound() { return ContinueLoc.isValid(); }
1540 bool BreakFound() { return BreakLoc.isValid(); }
1541 SourceLocation GetContinueLoc() { return ContinueLoc; }
1542 SourceLocation GetBreakLoc() { return BreakLoc; }
1543
1544 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001545
1546 // Emit a warning when a loop increment/decrement appears twice per loop
1547 // iteration. The conditions which trigger this warning are:
1548 // 1) The last statement in the loop body and the third expression in the
1549 // for loop are both increment or both decrement of the same variable
1550 // 2) No continue statements in the loop body.
1551 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1552 // Return when there is nothing to check.
1553 if (!Body || !Third) return;
1554
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001555 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1556 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001557 return;
1558
1559 // Get the last statement from the loop body.
1560 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1561 if (!CS || CS->body_empty()) return;
1562 Stmt *LastStmt = CS->body_back();
1563 if (!LastStmt) return;
1564
1565 bool LoopIncrement, LastIncrement;
1566 DeclRefExpr *LoopDRE, *LastDRE;
1567
1568 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1569 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1570
1571 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001572 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001573 if (LoopIncrement != LastIncrement ||
1574 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1575
Serge Pavlov09f99242014-01-23 15:05:00 +00001576 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001577
1578 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1579 << LastDRE->getDecl() << LastIncrement;
1580 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1581 << LoopIncrement;
1582 }
1583
Richard Trieu451a5db2012-04-30 18:01:30 +00001584} // end namespace
1585
Serge Pavlov09f99242014-01-23 15:05:00 +00001586
1587void Sema::CheckBreakContinueBinding(Expr *E) {
1588 if (!E || getLangOpts().CPlusPlus)
1589 return;
1590 BreakContinueFinder BCFinder(*this, E);
1591 Scope *BreakParent = CurScope->getBreakParent();
1592 if (BCFinder.BreakFound() && BreakParent) {
1593 if (BreakParent->getFlags() & Scope::SwitchScope) {
1594 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1595 } else {
1596 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1597 << "break";
1598 }
1599 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1600 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1601 << "continue";
1602 }
1603}
1604
John McCalldadc5752010-08-24 06:29:42 +00001605StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001606Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001607 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001608 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001609 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001610 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001611 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001612 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1613 // declare identifiers for objects having storage class 'auto' or
1614 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001615 for (auto *DI : DS->decls()) {
1616 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001617 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001618 VD = nullptr;
1619 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001620 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1621 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001622 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001623 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001624 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001625 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001626
Serge Pavlov09f99242014-01-23 15:05:00 +00001627 CheckBreakContinueBinding(second.get());
1628 CheckBreakContinueBinding(third.get());
1629
Richard Trieu451a5db2012-04-30 18:01:30 +00001630 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001631 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001632
John McCalldadc5752010-08-24 06:29:42 +00001633 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001634 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001635 if (secondVar) {
1636 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001637 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001638 if (SecondResult.isInvalid())
1639 return StmtError();
1640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001641
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001642 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643
Anders Carlsson1682af52009-08-01 01:39:59 +00001644 DiagnoseUnusedExprResult(First);
1645 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001646 DiagnoseUnusedExprResult(Body);
1647
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001648 if (isa<NullStmt>(Body))
1649 getCurCompoundScope().setHasEmptyLoopBodies();
1650
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001651 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1652 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001653}
1654
John McCall34376a62010-12-04 03:47:34 +00001655/// In an Objective C collection iteration statement:
1656/// for (x in y)
1657/// x can be an arbitrary l-value expression. Bind it up as a
1658/// full-expression.
1659StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001660 // Reduce placeholder expressions here. Note that this rejects the
1661 // use of pseudo-object l-values in this position.
1662 ExprResult result = CheckPlaceholderExpr(E);
1663 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001664 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001665
Richard Smith945f8d32013-01-14 22:39:08 +00001666 ExprResult FullExpr = ActOnFinishFullExpr(E);
1667 if (FullExpr.isInvalid())
1668 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001669 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001670}
1671
John McCall53848232011-07-27 01:07:15 +00001672ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001673Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1674 if (!collection)
1675 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001676
Kaelyn Takata15867822014-11-21 18:48:04 +00001677 ExprResult result = CorrectDelayedTyposInExpr(collection);
1678 if (!result.isUsable())
1679 return ExprError();
1680 collection = result.get();
1681
John McCall53848232011-07-27 01:07:15 +00001682 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001683 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001684
1685 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001686 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001687 if (result.isInvalid())
1688 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001689 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001690
1691 // The operand needs to have object-pointer type.
1692 // TODO: should we do a contextual conversion?
1693 const ObjCObjectPointerType *pointerType =
1694 collection->getType()->getAs<ObjCObjectPointerType>();
1695 if (!pointerType)
1696 return Diag(forLoc, diag::err_collection_expr_type)
1697 << collection->getType() << collection->getSourceRange();
1698
1699 // Check that the operand provides
1700 // - countByEnumeratingWithState:objects:count:
1701 const ObjCObjectType *objectType = pointerType->getObjectType();
1702 ObjCInterfaceDecl *iface = objectType->getInterface();
1703
1704 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001705 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001706 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001707 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001708 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001709 ? diag::err_arc_collection_forward
1710 : 0,
1711 collection)) {
John McCall53848232011-07-27 01:07:15 +00001712 // Otherwise, if we have any useful type information, check that
1713 // the type declares the appropriate method.
1714 } else if (iface || !objectType->qual_empty()) {
1715 IdentifierInfo *selectorIdents[] = {
1716 &Context.Idents.get("countByEnumeratingWithState"),
1717 &Context.Idents.get("objects"),
1718 &Context.Idents.get("count")
1719 };
1720 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1721
Craig Topperc3ec1492014-05-26 06:22:03 +00001722 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001723
1724 // If there's an interface, look in both the public and private APIs.
1725 if (iface) {
1726 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001727 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001728 }
1729
1730 // Also check protocol qualifiers.
1731 if (!method)
1732 method = LookupMethodInQualifiedType(selector, pointerType,
1733 /*instance*/ true);
1734
1735 // If we didn't find it anywhere, give up.
1736 if (!method) {
1737 Diag(forLoc, diag::warn_collection_expr_type)
1738 << collection->getType() << selector << collection->getSourceRange();
1739 }
1740
1741 // TODO: check for an incompatible signature?
1742 }
1743
1744 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001745 return collection;
John McCall53848232011-07-27 01:07:15 +00001746}
1747
John McCalldadc5752010-08-24 06:29:42 +00001748StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001749Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001750 Stmt *First, Expr *collection,
1751 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001752
1753 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001754 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001755
Fariborz Jahanian93977672008-01-10 20:33:58 +00001756 if (First) {
1757 QualType FirstType;
1758 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001759 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001760 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1761 diag::err_toomany_element_decls));
1762
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001763 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1764 if (!D || D->isInvalidDecl())
1765 return StmtError();
1766
John McCall31168b02011-06-15 23:02:42 +00001767 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001768 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1769 // declare identifiers for objects having storage class 'auto' or
1770 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001771 if (!D->hasLocalStorage())
1772 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001773 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001774
1775 // If the type contained 'auto', deduce the 'auto' to 'id'.
1776 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001777 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1778 VK_RValue);
1779 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001780 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1781 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001782 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001783 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001784 D->setInvalidDecl();
1785 return StmtError();
1786 }
1787
Richard Smith061f1e22013-04-30 21:23:01 +00001788 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001789
1790 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001791 SourceLocation Loc =
1792 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001793 Diag(Loc, diag::warn_auto_var_is_id)
1794 << D->getDeclName();
1795 }
1796 }
1797
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001798 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001799 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001800 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001801 return StmtError(Diag(First->getLocStart(),
1802 diag::err_selector_element_not_lvalue)
1803 << First->getSourceRange());
1804
Mike Stump11289f42009-09-09 15:08:12 +00001805 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001806 if (FirstType.isConstQualified())
1807 Diag(ForLoc, diag::err_selector_element_const_type)
1808 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001809 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001810 if (!FirstType->isDependentType() &&
1811 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001812 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001813 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1814 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001815 }
Chad Rosier02a84392012-08-10 17:56:09 +00001816
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001817 if (CollectionExprResult.isInvalid())
1818 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001819
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001820 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001821 if (CollectionExprResult.isInvalid())
1822 return StmtError();
1823
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001824 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1825 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001826}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001827
Richard Smith02e85f32011-04-14 22:09:26 +00001828/// Finish building a variable declaration for a for-range statement.
1829/// \return true if an error occurs.
1830static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001831 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001832 // Deduce the type for the iterator variable now rather than leaving it to
1833 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001834 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001835 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001836 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001837 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001838 SemaRef.Diag(Loc, DiagID) << Init->getType();
1839 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001840 Decl->setInvalidDecl();
1841 return true;
1842 }
Richard Smith061f1e22013-04-30 21:23:01 +00001843 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001844
John McCall31168b02011-06-15 23:02:42 +00001845 // In ARC, infer lifetime.
1846 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1847 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001848 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001849 SemaRef.inferObjCARCLifetime(Decl))
1850 Decl->setInvalidDecl();
1851
Richard Smith02e85f32011-04-14 22:09:26 +00001852 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1853 /*TypeMayContainAuto=*/false);
1854 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001855 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001856 return false;
1857}
1858
Sam Panzer0f384432012-08-21 00:52:01 +00001859namespace {
1860
Richard Smith02e85f32011-04-14 22:09:26 +00001861/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001862/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001863/// nor from the diagnostics produced when analysing the implicit expressions
1864/// required in a for-range statement.
1865void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001866 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001867 CallExpr *CE = dyn_cast<CallExpr>(E);
1868 if (!CE)
1869 return;
1870 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1871 if (!D)
1872 return;
1873 SourceLocation Loc = D->getLocation();
1874
1875 std::string Description;
1876 bool IsTemplate = false;
1877 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1878 Description = SemaRef.getTemplateArgumentBindingsText(
1879 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1880 IsTemplate = true;
1881 }
1882
1883 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1884 << BEF << IsTemplate << Description << E->getType();
1885}
1886
Sam Panzer0f384432012-08-21 00:52:01 +00001887/// Build a variable declaration for a for-range statement.
1888VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1889 QualType Type, const char *Name) {
1890 DeclContext *DC = SemaRef.CurContext;
1891 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1892 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1893 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001894 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001895 Decl->setImplicit();
1896 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001897}
1898
1899}
1900
Fariborz Jahanian00213472012-07-06 19:04:04 +00001901static bool ObjCEnumerationCollection(Expr *Collection) {
1902 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001903 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001904}
1905
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001906/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001907///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001908/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001909/// A range-based for statement is equivalent to
1910///
1911/// {
1912/// auto && __range = range-init;
1913/// for ( auto __begin = begin-expr,
1914/// __end = end-expr;
1915/// __begin != __end;
1916/// ++__begin ) {
1917/// for-range-declaration = *__begin;
1918/// statement
1919/// }
1920/// }
1921///
1922/// The body of the loop is not available yet, since it cannot be analysed until
1923/// we have determined the type of the for-range-declaration.
1924StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001925Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001926 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001927 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001928 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001929 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001930
Richard Smith3249fed2013-08-21 01:40:36 +00001931 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001932 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001933
1934 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1935 assert(DS && "first part of for range not a decl stmt");
1936
1937 if (!DS->isSingleDecl()) {
1938 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1939 return StmtError();
1940 }
Richard Smith02e85f32011-04-14 22:09:26 +00001941
Richard Smith3249fed2013-08-21 01:40:36 +00001942 Decl *LoopVar = DS->getSingleDecl();
1943 if (LoopVar->isInvalidDecl() || !Range ||
1944 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1945 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001946 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001947 }
Richard Smith02e85f32011-04-14 22:09:26 +00001948
1949 // Build auto && __range = range-init
1950 SourceLocation RangeLoc = Range->getLocStart();
1951 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1952 Context.getAutoRRefDeductType(),
1953 "__range");
1954 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001955 diag::err_for_range_deduction_failure)) {
1956 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001957 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001958 }
Richard Smith02e85f32011-04-14 22:09:26 +00001959
1960 // Claim the type doesn't contain auto: we've already done the checking.
1961 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001962 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001963 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001964 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001965 if (RangeDecl.isInvalid()) {
1966 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001967 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001968 }
Richard Smith02e85f32011-04-14 22:09:26 +00001969
1970 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001971 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1972 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001973}
1974
1975/// \brief Create the initialization, compare, and increment steps for
1976/// the range-based for loop expression.
1977/// This function does not handle array-based for loops,
1978/// which are created in Sema::BuildCXXForRangeStmt.
1979///
1980/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1981/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1982/// CandidateSet and BEF are set and some non-success value is returned on
1983/// failure.
1984static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1985 Expr *BeginRange, Expr *EndRange,
1986 QualType RangeType,
1987 VarDecl *BeginVar,
1988 VarDecl *EndVar,
1989 SourceLocation ColonLoc,
1990 OverloadCandidateSet *CandidateSet,
1991 ExprResult *BeginExpr,
1992 ExprResult *EndExpr,
1993 Sema::BeginEndFunction *BEF) {
1994 DeclarationNameInfo BeginNameInfo(
1995 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1996 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1997 ColonLoc);
1998
1999 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2000 Sema::LookupMemberName);
2001 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2002
2003 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2004 // - if _RangeT is a class type, the unqualified-ids begin and end are
2005 // looked up in the scope of class _RangeT as if by class member access
2006 // lookup (3.4.5), and if either (or both) finds at least one
2007 // declaration, begin-expr and end-expr are __range.begin() and
2008 // __range.end(), respectively;
2009 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2010 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2011
2012 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2013 SourceLocation RangeLoc = BeginVar->getLocation();
2014 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2015
2016 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2017 << RangeLoc << BeginRange->getType() << *BEF;
2018 return Sema::FRS_DiagnosticIssued;
2019 }
2020 } else {
2021 // - otherwise, begin-expr and end-expr are begin(__range) and
2022 // end(__range), respectively, where begin and end are looked up with
2023 // argument-dependent lookup (3.4.2). For the purposes of this name
2024 // lookup, namespace std is an associated namespace.
2025
2026 }
2027
2028 *BEF = Sema::BEF_begin;
2029 Sema::ForRangeStatus RangeStatus =
2030 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2031 Sema::BEF_begin, BeginNameInfo,
2032 BeginMemberLookup, CandidateSet,
2033 BeginRange, BeginExpr);
2034
2035 if (RangeStatus != Sema::FRS_Success)
2036 return RangeStatus;
2037 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2038 diag::err_for_range_iter_deduction_failure)) {
2039 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2040 return Sema::FRS_DiagnosticIssued;
2041 }
2042
2043 *BEF = Sema::BEF_end;
2044 RangeStatus =
2045 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2046 Sema::BEF_end, EndNameInfo,
2047 EndMemberLookup, CandidateSet,
2048 EndRange, EndExpr);
2049 if (RangeStatus != Sema::FRS_Success)
2050 return RangeStatus;
2051 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2052 diag::err_for_range_iter_deduction_failure)) {
2053 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2054 return Sema::FRS_DiagnosticIssued;
2055 }
2056 return Sema::FRS_Success;
2057}
2058
2059/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002060/// If the attempt fails, this function will return a valid, null StmtResult
2061/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002062static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2063 SourceLocation ForLoc,
2064 Stmt *LoopVarDecl,
2065 SourceLocation ColonLoc,
2066 Expr *Range,
2067 SourceLocation RangeLoc,
2068 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002069 // Determine whether we can rebuild the for-range statement with a
2070 // dereferenced range expression.
2071 ExprResult AdjustedRange;
2072 {
2073 Sema::SFINAETrap Trap(SemaRef);
2074
2075 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2076 if (AdjustedRange.isInvalid())
2077 return StmtResult();
2078
2079 StmtResult SR =
2080 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2081 AdjustedRange.get(), RParenLoc,
2082 Sema::BFRK_Check);
2083 if (SR.isInvalid())
2084 return StmtResult();
2085 }
2086
2087 // The attempt to dereference worked well enough that it could produce a valid
2088 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2089 // case there are any other (non-fatal) problems with it.
2090 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2091 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2092 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2093 AdjustedRange.get(), RParenLoc,
2094 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002095}
2096
Richard Smith3249fed2013-08-21 01:40:36 +00002097namespace {
2098/// RAII object to automatically invalidate a declaration if an error occurs.
2099struct InvalidateOnErrorScope {
2100 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2101 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2102 ~InvalidateOnErrorScope() {
2103 if (Enabled && Trap.hasErrorOccurred())
2104 D->setInvalidDecl();
2105 }
2106
2107 DiagnosticErrorTrap Trap;
2108 Decl *D;
2109 bool Enabled;
2110};
2111}
2112
Richard Smitha05b3b52012-09-20 21:52:32 +00002113/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002114StmtResult
2115Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2116 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2117 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002118 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002119 Scope *S = getCurScope();
2120
2121 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2122 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2123 QualType RangeVarType = RangeVar->getType();
2124
2125 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2126 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2127
Richard Smith3249fed2013-08-21 01:40:36 +00002128 // If we hit any errors, mark the loop variable as invalid if its type
2129 // contains 'auto'.
2130 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2131 LoopVar->getType()->isUndeducedType());
2132
Richard Smith02e85f32011-04-14 22:09:26 +00002133 StmtResult BeginEndDecl = BeginEnd;
2134 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2135
Richard Smith27d807c2013-04-30 13:56:41 +00002136 if (RangeVarType->isDependentType()) {
2137 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002138 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002139
2140 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2141 // them in properly when we instantiate the loop.
2142 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2143 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2144 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002145 SourceLocation RangeLoc = RangeVar->getLocation();
2146
Ted Kremenekbed648e2011-10-10 22:36:28 +00002147 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2148
2149 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2150 VK_LValue, ColonLoc);
2151 if (BeginRangeRef.isInvalid())
2152 return StmtError();
2153
2154 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2155 VK_LValue, ColonLoc);
2156 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002157 return StmtError();
2158
2159 QualType AutoType = Context.getAutoDeductType();
2160 Expr *Range = RangeVar->getInit();
2161 if (!Range)
2162 return StmtError();
2163 QualType RangeType = Range->getType();
2164
2165 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002166 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002167 return StmtError();
2168
2169 // Build auto __begin = begin-expr, __end = end-expr.
2170 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2171 "__begin");
2172 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2173 "__end");
2174
2175 // Build begin-expr and end-expr and attach to __begin and __end variables.
2176 ExprResult BeginExpr, EndExpr;
2177 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2178 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2179 // __range + __bound, respectively, where __bound is the array bound. If
2180 // _RangeT is an array of unknown size or an array of incomplete type,
2181 // the program is ill-formed;
2182
2183 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002184 BeginExpr = BeginRangeRef;
2185 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002186 diag::err_for_range_iter_deduction_failure)) {
2187 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2188 return StmtError();
2189 }
2190
2191 // Find the array bound.
2192 ExprResult BoundExpr;
2193 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002194 BoundExpr = IntegerLiteral::Create(
2195 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002196 else if (const VariableArrayType *VAT =
2197 dyn_cast<VariableArrayType>(UnqAT))
2198 BoundExpr = VAT->getSizeExpr();
2199 else {
2200 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2201 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002202 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002203 }
2204
2205 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002206 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002207 BoundExpr.get());
2208 if (EndExpr.isInvalid())
2209 return StmtError();
2210 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2211 diag::err_for_range_iter_deduction_failure)) {
2212 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2213 return StmtError();
2214 }
2215 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002216 OverloadCandidateSet CandidateSet(RangeLoc,
2217 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002218 Sema::BeginEndFunction BEFFailure;
2219 ForRangeStatus RangeStatus =
2220 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2221 EndRangeRef.get(), RangeType,
2222 BeginVar, EndVar, ColonLoc, &CandidateSet,
2223 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002224
Richard Smitha05b3b52012-09-20 21:52:32 +00002225 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002226 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002227 // If the range is being built from an array parameter, emit a
2228 // a diagnostic that it is being treated as a pointer.
2229 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2230 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2231 QualType ArrayTy = PVD->getOriginalType();
2232 QualType PointerTy = PVD->getType();
2233 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2234 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2235 << RangeLoc << PVD << ArrayTy << PointerTy;
2236 Diag(PVD->getLocation(), diag::note_declared_at);
2237 return StmtError();
2238 }
2239 }
2240 }
2241
2242 // If building the range failed, try dereferencing the range expression
2243 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002244 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2245 LoopVarDecl, ColonLoc,
2246 Range, RangeLoc,
2247 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002248 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002249 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002250 }
2251
Sam Panzer0f384432012-08-21 00:52:01 +00002252 // Otherwise, emit diagnostics if we haven't already.
2253 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002254 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002255 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2256 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002257 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002258 }
2259 // Return an error if no fix was discovered.
2260 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002261 return StmtError();
2262 }
2263
Sam Panzer0f384432012-08-21 00:52:01 +00002264 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2265 "invalid range expression in for loop");
2266
2267 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002268 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2269 if (!Context.hasSameType(BeginType, EndType)) {
2270 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2271 << BeginType << EndType;
2272 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2273 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2274 }
2275
2276 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2277 // Claim the type doesn't contain auto: we've already done the checking.
2278 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002279 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002280 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002281 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2282
Ted Kremenekbed648e2011-10-10 22:36:28 +00002283 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2284 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002285 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002286 if (BeginRef.isInvalid())
2287 return StmtError();
2288
Richard Smith02e85f32011-04-14 22:09:26 +00002289 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2290 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002291 if (EndRef.isInvalid())
2292 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002293
2294 // Build and check __begin != __end expression.
2295 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2296 BeginRef.get(), EndRef.get());
2297 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2298 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2299 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002300 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2301 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002302 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2303 if (!Context.hasSameType(BeginType, EndType))
2304 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2305 return StmtError();
2306 }
2307
2308 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002309 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2310 VK_LValue, ColonLoc);
2311 if (BeginRef.isInvalid())
2312 return StmtError();
2313
Richard Smith02e85f32011-04-14 22:09:26 +00002314 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2315 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2316 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002317 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2318 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002319 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2320 return StmtError();
2321 }
2322
2323 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002324 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2325 VK_LValue, ColonLoc);
2326 if (BeginRef.isInvalid())
2327 return StmtError();
2328
Richard Smith02e85f32011-04-14 22:09:26 +00002329 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2330 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002331 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2332 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002333 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2334 return StmtError();
2335 }
2336
Richard Smitha05b3b52012-09-20 21:52:32 +00002337 // Attach *__begin as initializer for VD. Don't touch it if we're just
2338 // trying to determine whether this would be a valid range.
2339 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002340 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2341 /*TypeMayContainAuto=*/true);
2342 if (LoopVar->isInvalidDecl())
2343 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2344 }
2345 }
2346
Richard Smitha05b3b52012-09-20 21:52:32 +00002347 // Don't bother to actually allocate the result if we're just trying to
2348 // determine whether it would be valid.
2349 if (Kind == BFRK_Check)
2350 return StmtResult();
2351
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002352 return new (Context) CXXForRangeStmt(
2353 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2354 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002355}
2356
Chad Rosier02a84392012-08-10 17:56:09 +00002357/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002358/// statement.
2359StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2360 if (!S || !B)
2361 return StmtError();
2362 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002363
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002364 ForStmt->setBody(B);
2365 return S;
2366}
2367
Richard Trieu3e1d4832015-04-13 22:08:55 +00002368// Warn when the loop variable is a const reference that creates a copy.
2369// Suggest using the non-reference type for copies. If a copy can be prevented
2370// suggest the const reference type that would do so.
2371// For instance, given "for (const &Foo : Range)", suggest
2372// "for (const Foo : Range)" to denote a copy is made for the loop. If
2373// possible, also suggest "for (const &Bar : Range)" if this type prevents
2374// the copy altogether.
2375static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2376 const VarDecl *VD,
2377 QualType RangeInitType) {
2378 const Expr *InitExpr = VD->getInit();
2379 if (!InitExpr)
2380 return;
2381
2382 QualType VariableType = VD->getType();
2383
2384 const MaterializeTemporaryExpr *MTE =
2385 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2386
2387 // No copy made.
2388 if (!MTE)
2389 return;
2390
2391 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2392
2393 // Searching for either UnaryOperator for dereference of a pointer or
2394 // CXXOperatorCallExpr for handling iterators.
2395 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2396 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2397 E = CCE->getArg(0);
2398 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2399 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2400 E = ME->getBase();
2401 } else {
2402 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2403 E = MTE->GetTemporaryExpr();
2404 }
2405 E = E->IgnoreImpCasts();
2406 }
2407
2408 bool ReturnsReference = false;
2409 if (isa<UnaryOperator>(E)) {
2410 ReturnsReference = true;
2411 } else {
2412 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2413 const FunctionDecl *FD = Call->getDirectCallee();
2414 QualType ReturnType = FD->getReturnType();
2415 ReturnsReference = ReturnType->isReferenceType();
2416 }
2417
2418 if (ReturnsReference) {
2419 // Loop variable creates a temporary. Suggest either to go with
2420 // non-reference loop variable to indiciate a copy is made, or
2421 // the correct time to bind a const reference.
2422 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2423 << VD << VariableType << E->getType();
2424 QualType NonReferenceType = VariableType.getNonReferenceType();
2425 NonReferenceType.removeLocalConst();
2426 QualType NewReferenceType =
2427 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2428 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2429 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2430 } else {
2431 // The range always returns a copy, so a temporary is always created.
2432 // Suggest removing the reference from the loop variable.
2433 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2434 << VD << RangeInitType;
2435 QualType NonReferenceType = VariableType.getNonReferenceType();
2436 NonReferenceType.removeLocalConst();
2437 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2438 << NonReferenceType << VD->getSourceRange();
2439 }
2440}
2441
2442// Warns when the loop variable can be changed to a reference type to
2443// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2444// "for (const Foo &x : Range)" if this form does not make a copy.
2445static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2446 const VarDecl *VD) {
2447 const Expr *InitExpr = VD->getInit();
2448 if (!InitExpr)
2449 return;
2450
2451 QualType VariableType = VD->getType();
2452
2453 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2454 if (!CE->getConstructor()->isCopyConstructor())
2455 return;
2456 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2457 if (CE->getCastKind() != CK_LValueToRValue)
2458 return;
2459 } else {
2460 return;
2461 }
2462
2463 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2464 // should be emitted. Also, only ignore POD types with trivial copy
2465 // constructors.
2466 if (VariableType.isPODType(SemaRef.Context))
2467 return;
2468
2469 // Suggest changing from a const variable to a const reference variable
2470 // if doing so will prevent a copy.
2471 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2472 << VD << VariableType << InitExpr->getType();
2473 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2474 << SemaRef.Context.getLValueReferenceType(VariableType)
2475 << VD->getSourceRange();
2476}
2477
2478/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2479/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2480/// using "const foo x" to show that a copy is made
2481/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2482/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2483/// prevent the copy.
2484/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2485/// Suggest "const foo &x" to prevent the copy.
2486static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2487 const CXXForRangeStmt *ForStmt) {
2488 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2489 ForStmt->getLocStart()) &&
2490 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2491 ForStmt->getLocStart()) &&
2492 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2493 ForStmt->getLocStart())) {
2494 return;
2495 }
2496
2497 const VarDecl *VD = ForStmt->getLoopVariable();
2498 if (!VD)
2499 return;
2500
2501 QualType VariableType = VD->getType();
2502
2503 if (VariableType->isIncompleteType())
2504 return;
2505
2506 const Expr *InitExpr = VD->getInit();
2507 if (!InitExpr)
2508 return;
2509
2510 if (VariableType->isReferenceType()) {
2511 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2512 ForStmt->getRangeInit()->getType());
2513 } else if (VariableType.isConstQualified()) {
2514 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2515 }
2516}
2517
Richard Smith02e85f32011-04-14 22:09:26 +00002518/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2519/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2520/// body cannot be performed until after the type of the range variable is
2521/// determined.
2522StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2523 if (!S || !B)
2524 return StmtError();
2525
Fariborz Jahanian00213472012-07-06 19:04:04 +00002526 if (isa<ObjCForCollectionStmt>(S))
2527 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002528
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002529 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2530 ForStmt->setBody(B);
2531
2532 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2533 diag::warn_empty_range_based_for_body);
2534
Richard Trieu3e1d4832015-04-13 22:08:55 +00002535 DiagnoseForRangeVariableCopies(*this, ForStmt);
2536
Richard Smith02e85f32011-04-14 22:09:26 +00002537 return S;
2538}
2539
Chris Lattnercab02a62011-02-17 20:34:02 +00002540StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2541 SourceLocation LabelLoc,
2542 LabelDecl *TheDecl) {
2543 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002544 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002545 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002546}
Chris Lattner1c310502007-05-31 06:00:00 +00002547
John McCalldadc5752010-08-24 06:29:42 +00002548StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002549Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002550 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002551 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002552 if (!E->isTypeDependent()) {
2553 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002554 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002555 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002556 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002557 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2558 if (ExprRes.isInvalid())
2559 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002560 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002561 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002562 return StmtError();
2563 }
John McCalla95172b2010-08-01 00:26:45 +00002564
Richard Smith945f8d32013-01-14 22:39:08 +00002565 ExprResult ExprRes = ActOnFinishFullExpr(E);
2566 if (ExprRes.isInvalid())
2567 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002568 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002569
John McCallaab3e412010-08-25 08:40:02 +00002570 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002571
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002572 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002573}
2574
Nico Weberd64657f2015-03-09 02:47:59 +00002575static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2576 const Scope &DestScope) {
2577 if (!S.CurrentSEHFinally.empty() &&
2578 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2579 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2580 }
2581}
2582
John McCalldadc5752010-08-24 06:29:42 +00002583StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002584Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002585 Scope *S = CurScope->getContinueParent();
2586 if (!S) {
2587 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002588 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002589 }
Nico Weberd64657f2015-03-09 02:47:59 +00002590 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002591
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002592 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002593}
2594
John McCalldadc5752010-08-24 06:29:42 +00002595StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002596Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002597 Scope *S = CurScope->getBreakParent();
2598 if (!S) {
2599 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002600 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002601 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002602 if (S->isOpenMPLoopScope())
2603 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2604 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002605 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002606
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002607 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002608}
2609
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002610/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002611/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002612///
Douglas Gregor5d369002011-01-21 18:05:27 +00002613/// \param ReturnType If we're determining the copy elision candidate for
2614/// a return statement, this is the return type of the function. If we're
2615/// determining the copy elision candidate for a throw expression, this will
2616/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002617///
Douglas Gregor5d369002011-01-21 18:05:27 +00002618/// \param E The expression being returned from the function or block, or
2619/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002620///
Douglas Gregor86394412011-05-20 15:00:53 +00002621/// \param AllowFunctionParameter Whether we allow function parameters to
2622/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2623/// we re-use this logic to determine whether we should try to move as part of
2624/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002625///
2626/// \returns The NRVO candidate variable, if the return statement may use the
2627/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002628VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2629 Expr *E,
2630 bool AllowFunctionParameter) {
2631 if (!getLangOpts().CPlusPlus)
2632 return nullptr;
2633
2634 // - in a return statement in a function [where] ...
2635 // ... the expression is the name of a non-volatile automatic object ...
2636 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002637 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002638 return nullptr;
2639 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2640 if (!VD)
2641 return nullptr;
2642
2643 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2644 return VD;
2645 return nullptr;
2646}
2647
2648bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2649 bool AllowFunctionParameter) {
2650 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002651 // - in a return statement in a function with ...
2652 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002653 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002654 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002655 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002656 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002657 if (!VDType->isDependentType() &&
2658 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2659 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002660 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661
John McCall03318c12011-11-11 03:57:31 +00002662 // ...object (other than a function or catch-clause parameter)...
2663 if (VD->getKind() != Decl::Var &&
2664 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002665 return false;
2666 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002667
John McCall03318c12011-11-11 03:57:31 +00002668 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002669 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002670
2671 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002672 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002673
2674 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002675 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002676
2677 // Variables with higher required alignment than their type's ABI
2678 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002679 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002680 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002681 return false;
John McCall03318c12011-11-11 03:57:31 +00002682
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002683 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002684}
2685
Douglas Gregor626fbed2011-01-21 21:08:57 +00002686/// \brief Perform the initialization of a potentially-movable value, which
2687/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002688///
2689/// This routine implements C++0x [class.copy]p33, which attempts to treat
2690/// returned lvalues as rvalues in certain cases (to prefer move construction),
2691/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002692ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002693Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2694 const VarDecl *NRVOCandidate,
2695 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002696 Expr *Value,
2697 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002698 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002699 // When the criteria for elision of a copy operation are met or would
2700 // be met save for the fact that the source object is a function
2701 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002702 // overload resolution to select the constructor for the copy is first
2703 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002704 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002705 if (AllowNRVO &&
2706 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002708 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709
Douglas Gregorf282a762011-01-21 19:38:21 +00002710 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002712 = InitializationKind::CreateCopy(Value->getLocStart(),
2713 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002714 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715
2716 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002717 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002718 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002719 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002720 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002721 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2722 StepEnd = Seq.step_end();
2723 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002724 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002725 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726
2727 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002728 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002729
Douglas Gregorf282a762011-01-21 19:38:21 +00002730 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002731 = Constructor->getParamDecl(0)->getType()
2732 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002733
Douglas Gregorf282a762011-01-21 19:38:21 +00002734 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002735 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002736 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2737 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002738 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739
Douglas Gregorf282a762011-01-21 19:38:21 +00002740 // Promote "AsRvalue" to the heap, since we now need this
2741 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002742 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002743 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002744
Douglas Gregorf282a762011-01-21 19:38:21 +00002745 // Complete type-checking the initialization of the return type
2746 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002747 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002748 }
2749 }
2750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751
Douglas Gregorf282a762011-01-21 19:38:21 +00002752 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002754 // (again) now with the return value expression as written.
2755 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002756 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002757
Douglas Gregorf282a762011-01-21 19:38:21 +00002758 return Res;
2759}
2760
Richard Smith4db51c22013-09-25 05:02:54 +00002761/// \brief Determine whether the declared return type of the specified function
2762/// contains 'auto'.
2763static bool hasDeducedReturnType(FunctionDecl *FD) {
2764 const FunctionProtoType *FPT =
2765 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002766 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002767}
2768
Eli Friedman34b49062012-01-26 03:00:14 +00002769/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2770/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002771///
John McCalldadc5752010-08-24 06:29:42 +00002772StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002773Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2774 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002775 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002776 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002777 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002778 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002779
Richard Smith4db51c22013-09-25 05:02:54 +00002780 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2781 // In C++1y, the return type may involve 'auto'.
2782 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2783 FunctionDecl *FD = CurLambda->CallOperator;
2784 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002785 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002786
2787 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2788 assert(AT && "lost auto type from lambda return type");
2789 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2790 FD->setInvalidDecl();
2791 return StmtError();
2792 }
Alp Toker314cc812014-01-25 16:55:45 +00002793 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002794 } else if (CurCap->HasImplicitReturnType) {
2795 // For blocks/lambdas with implicit return types, we check each return
2796 // statement individually, and deduce the common return type when the block
2797 // or lambda is completed.
2798 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002799 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002800 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2801 if (Result.isInvalid())
2802 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002803 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002804
Richard Smith5a0e50c2014-12-19 22:10:51 +00002805 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2806 // when deducing a return type for a lambda-expression (or by extension
2807 // for a block). These rules differ from the stated C++11 rules only in
2808 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002809 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002810 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002811 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002812 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002813 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002814 if (RetValExp) {
2815 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2816 // initializer list, because it is not an expression (even
2817 // though we represent it as one). We still deduce 'void'.
2818 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2819 << RetValExp->getSourceRange();
2820 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002821
Jordan Rosed39e5f12012-07-02 21:19:23 +00002822 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002823 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002824
2825 // Although we'll properly infer the type of the block once it's completed,
2826 // make sure we provide a return type now for better error recovery.
2827 if (CurCap->ReturnType.isNull())
2828 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002829 }
Eli Friedman34b49062012-01-26 03:00:14 +00002830 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002831
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002832 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002833 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2834 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2835 return StmtError();
2836 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002837 } else if (CapturedRegionScopeInfo *CurRegion =
2838 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2839 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2840 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002841 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002842 assert(CurLambda && "unknown kind of captured scope");
2843 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2844 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002845 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2846 return StmtError();
2847 }
2848 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002849
Steve Naroffc540d662008-09-03 18:15:37 +00002850 // Otherwise, verify that this result type matches the previous one. We are
2851 // pickier with blocks than for normal functions because we don't have GCC
2852 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002853 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002854 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002855 // Delay processing for now. TODO: there are lots of dependent
2856 // types we can conclusively prove aren't void.
2857 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002858 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002859 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002860 (RetValExp->isTypeDependent() ||
2861 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002862 if (!getLangOpts().CPlusPlus &&
2863 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002864 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002865 else {
2866 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002867 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002868 }
Steve Naroffc540d662008-09-03 18:15:37 +00002869 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002870 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002871 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2872 } else if (!RetValExp->isTypeDependent()) {
2873 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002874
John McCall5500ef22011-08-17 22:09:46 +00002875 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2876 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2877 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002878
John McCall5500ef22011-08-17 22:09:46 +00002879 // In C++ the return statement is handled via a copy initialization.
2880 // the C version of which boils down to CheckSingleAssignmentConstraints.
2881 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2882 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2883 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002885 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2886 FnRetType, RetValExp);
2887 if (Res.isInvalid()) {
2888 // FIXME: Cleanup temporaries here, anyway?
2889 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002890 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002891 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002892 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002893 } else {
2894 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002895 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002896
John McCall75f92b52011-08-17 21:34:14 +00002897 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002898 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2899 if (ER.isInvalid())
2900 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002901 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002902 }
John McCall5500ef22011-08-17 22:09:46 +00002903 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2904 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002905
Jordan Rosed39e5f12012-07-02 21:19:23 +00002906 // If we need to check for the named return value optimization,
2907 // or if we need to infer the return type,
2908 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002909 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002910 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002912 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002913}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002914
Nico Weber72889432014-09-06 01:25:55 +00002915namespace {
2916/// \brief Marks all typedefs in all local classes in a type referenced.
2917///
2918/// In a function like
2919/// auto f() {
2920/// struct S { typedef int a; };
2921/// return S();
2922/// }
2923///
2924/// the local type escapes and could be referenced in some TUs but not in
2925/// others. Pretend that all local typedefs are always referenced, to not warn
2926/// on this. This isn't necessary if f has internal linkage, or the typedef
2927/// is private.
2928class LocalTypedefNameReferencer
2929 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2930public:
2931 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2932 bool VisitRecordType(const RecordType *RT);
2933private:
2934 Sema &S;
2935};
2936bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2937 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2938 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2939 R->isDependentType())
2940 return true;
2941 for (auto *TmpD : R->decls())
2942 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2943 if (T->getAccess() != AS_private || R->hasFriends())
2944 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2945 return true;
2946}
2947}
2948
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002949TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002950 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002951 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2952 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002953 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002954}
2955
Richard Smith2a7d4812013-05-04 07:00:32 +00002956/// Deduce the return type for a function from a returned expression, per
2957/// C++1y [dcl.spec.auto]p6.
2958bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2959 SourceLocation ReturnLoc,
2960 Expr *&RetExpr,
2961 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002962 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002963 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002964
Richard Smithc58f38f2013-08-14 20:16:31 +00002965 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2966 // If the deduction is for a return statement and the initializer is
2967 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002968 Diag(RetExpr->getExprLoc(),
2969 getCurLambda() ? diag::err_lambda_return_init_list
2970 : diag::err_auto_fn_return_init_list)
2971 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002972 return true;
2973 }
2974
2975 if (FD->isDependentContext()) {
2976 // C++1y [dcl.spec.auto]p12:
2977 // Return type deduction [...] occurs when the definition is
2978 // instantiated even if the function body contains a return
2979 // statement with a non-type-dependent operand.
2980 assert(AT->isDeduced() && "should have deduced to dependent type");
2981 return false;
2982 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002983 // If the deduction is for a return statement and the initializer is
2984 // a braced-init-list, the program is ill-formed.
2985 if (isa<InitListExpr>(RetExpr)) {
2986 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2987 return true;
2988 }
2989
2990 // Otherwise, [...] deduce a value for U using the rules of template
2991 // argument deduction.
2992 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2993
2994 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2995 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2996 << OrigResultType.getType() << RetExpr->getType();
2997
2998 if (DAR != DAR_Succeeded)
2999 return true;
Nico Weber72889432014-09-06 01:25:55 +00003000
3001 // If a local type is part of the returned type, mark its fields as
3002 // referenced.
3003 LocalTypedefNameReferencer Referencer(*this);
3004 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003005 } else {
3006 // In the case of a return with no operand, the initializer is considered
3007 // to be void().
3008 //
3009 // Deduction here can only succeed if the return type is exactly 'cv auto'
3010 // or 'decltype(auto)', so just check for that case directly.
3011 if (!OrigResultType.getType()->getAs<AutoType>()) {
3012 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3013 << OrigResultType.getType();
3014 return true;
3015 }
3016 // We always deduce U = void in this case.
3017 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3018 if (Deduced.isNull())
3019 return true;
3020 }
3021
3022 // If a function with a declared return type that contains a placeholder type
3023 // has multiple return statements, the return type is deduced for each return
3024 // statement. [...] if the type deduced is not the same in each deduction,
3025 // the program is ill-formed.
3026 if (AT->isDeduced() && !FD->isInvalidDecl()) {
3027 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00003028 if (!FD->isDependentContext() &&
3029 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00003030 const LambdaScopeInfo *LambdaSI = getCurLambda();
3031 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3032 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3033 << NewAT->getDeducedType() << AT->getDeducedType()
3034 << true /*IsLambda*/;
3035 } else {
3036 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3037 << (AT->isDecltypeAuto() ? 1 : 0)
3038 << NewAT->getDeducedType() << AT->getDeducedType();
3039 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003040 return true;
3041 }
3042 } else if (!FD->isInvalidDecl()) {
3043 // Update all declarations of the function to have the deduced return type.
3044 Context.adjustDeducedFunctionResultType(FD, Deduced);
3045 }
3046
3047 return false;
3048}
3049
John McCalldadc5752010-08-24 06:29:42 +00003050StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003051Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3052 Scope *CurScope) {
3053 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3054 if (R.isInvalid()) {
3055 return R;
3056 }
3057
3058 if (VarDecl *VD =
3059 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3060 CurScope->addNRVOCandidate(VD);
3061 } else {
3062 CurScope->setNoNRVO();
3063 }
3064
Nico Weberd64657f2015-03-09 02:47:59 +00003065 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3066
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003067 return R;
3068}
3069
3070StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003071 // Check for unexpanded parameter packs.
3072 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3073 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003074
Eli Friedman34b49062012-01-26 03:00:14 +00003075 if (isa<CapturingScopeInfo>(getCurFunction()))
3076 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003077
Chris Lattner79413952008-12-04 23:50:19 +00003078 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003079 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003080 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003081 bool isObjCMethod = false;
3082
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003083 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003084 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003085 if (FD->hasAttrs())
3086 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003087 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003088 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003089 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003090 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003091 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003092 isObjCMethod = true;
3093 if (MD->hasAttrs())
3094 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003095 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3096 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003097 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003098 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003099 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3100 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003101 }
3102 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003103 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003104
Richard Smith2a7d4812013-05-04 07:00:32 +00003105 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3106 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003107 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003108 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3109 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003110 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003111 FD->setInvalidDecl();
3112 return StmtError();
3113 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003114 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003115 }
3116 }
3117 }
3118
Richard Smithc58f38f2013-08-14 20:16:31 +00003119 bool HasDependentReturnType = FnRetType->isDependentType();
3120
Craig Topperc3ec1492014-05-26 06:22:03 +00003121 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003122 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003123 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003124 if (isa<InitListExpr>(RetValExp)) {
3125 // We simply never allow init lists as the return value of void
3126 // functions. This is compatible because this was never allowed before,
3127 // so there's no legacy code to deal with.
3128 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3129 int FunctionKind = 0;
3130 if (isa<ObjCMethodDecl>(CurDecl))
3131 FunctionKind = 1;
3132 else if (isa<CXXConstructorDecl>(CurDecl))
3133 FunctionKind = 2;
3134 else if (isa<CXXDestructorDecl>(CurDecl))
3135 FunctionKind = 3;
3136
3137 Diag(ReturnLoc, diag::err_return_init_list)
3138 << CurDecl->getDeclName() << FunctionKind
3139 << RetValExp->getSourceRange();
3140
3141 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003142 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003143 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003144 // C99 6.8.6.4p1 (ext_ since GCC warns)
3145 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003146 if (RetValExp->getType()->isVoidType()) {
3147 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3148 if (isa<CXXConstructorDecl>(CurDecl) ||
3149 isa<CXXDestructorDecl>(CurDecl))
3150 D = diag::err_ctor_dtor_returns_void;
3151 else
3152 D = diag::ext_return_has_void_expr;
3153 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003154 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003155 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003156 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003157 if (Result.isInvalid())
3158 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003159 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003160 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003161 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003162 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003163 // return of void in constructor/destructor is illegal in C++.
3164 if (D == diag::err_ctor_dtor_returns_void) {
3165 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3166 Diag(ReturnLoc, D)
3167 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3168 << RetValExp->getSourceRange();
3169 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003170 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003171 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003172 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003173 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003174
3175 int FunctionKind = 0;
3176 if (isa<ObjCMethodDecl>(CurDecl))
3177 FunctionKind = 1;
3178 else if (isa<CXXConstructorDecl>(CurDecl))
3179 FunctionKind = 2;
3180 else if (isa<CXXDestructorDecl>(CurDecl))
3181 FunctionKind = 3;
3182
Nick Lewycky1be750a2011-06-01 07:44:31 +00003183 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003184 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003185 << RetValExp->getSourceRange();
3186 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003187 }
Mike Stump11289f42009-09-09 15:08:12 +00003188
Sebastian Redleef474c2012-02-22 10:50:08 +00003189 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003190 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3191 if (ER.isInvalid())
3192 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003193 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003194 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
Craig Topperc3ec1492014-05-26 06:22:03 +00003197 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003198 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003199 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003200
David Majnemer2887ad32014-12-13 08:12:56 +00003201 unsigned DiagID;
3202 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3203 // C++11 [stmt.return]p2
3204 DiagID = diag::err_constexpr_return_missing_expr;
3205 FD->setInvalidDecl();
3206 } else if (getLangOpts().C99) {
3207 // C99 6.8.6.4p1 (ext_ since GCC warns)
3208 DiagID = diag::ext_return_missing_expr;
3209 } else {
3210 // C90 6.6.6.4p4
3211 DiagID = diag::warn_return_missing_expr;
3212 }
3213
3214 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003215 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003216 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003217 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003218
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003219 Result = new (Context) ReturnStmt(ReturnLoc);
3220 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003221 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003222 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003223
3224 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3225
3226 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3227 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3228 // function return.
3229
3230 // In C++ the return statement is handled via a copy initialization,
3231 // the C version of which boils down to CheckSingleAssignmentConstraints.
3232 if (RetValExp)
3233 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003234 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003235 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003237 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003238 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003240 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003241 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003242 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003243 return StmtError();
3244 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003245 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003246
3247 // If we have a related result type, we need to implicitly
3248 // convert back to the formal result type. We can't pretend to
3249 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003250 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003251 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003252 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3253 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003254 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3255 if (Res.isInvalid()) {
3256 // FIXME: Clean up temporaries here anyway?
3257 return StmtError();
3258 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003259 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003260 }
3261
Artyom Skrobov9f213442014-01-24 11:10:39 +00003262 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3263 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003264 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
John McCallacf0ee52010-10-08 02:01:28 +00003266 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003267 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3268 if (ER.isInvalid())
3269 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003271 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003272 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274
3275 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003276 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003277 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003278 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003279
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003280 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003281}
3282
John McCalldadc5752010-08-24 06:29:42 +00003283StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003284Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003285 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003286 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003287 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003288 if (Var && Var->isInvalidDecl())
3289 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003291 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003292}
3293
John McCalldadc5752010-08-24 06:29:42 +00003294StmtResult
John McCallb268a282010-08-23 23:25:46 +00003295Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003296 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003297}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003298
John McCalldadc5752010-08-24 06:29:42 +00003299StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003301 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003302 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003303 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3304
John McCallaab3e412010-08-25 08:40:02 +00003305 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003306 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003307 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3308 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003309}
3310
John McCall0bd3e402012-05-08 21:41:25 +00003311StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003312 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003313 ExprResult Result = DefaultLvalueConversion(Throw);
3314 if (Result.isInvalid())
3315 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003316
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003317 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003318 if (Result.isInvalid())
3319 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003320 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003321
Douglas Gregor2900c162010-04-22 21:44:01 +00003322 QualType ThrowType = Throw->getType();
3323 // Make sure the expression type is an ObjC pointer or "void *".
3324 if (!ThrowType->isDependentType() &&
3325 !ThrowType->isObjCObjectPointerType()) {
3326 const PointerType *PT = ThrowType->getAs<PointerType>();
3327 if (!PT || !PT->getPointeeType()->isVoidType())
3328 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3329 << Throw->getType() << Throw->getSourceRange());
3330 }
3331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003333 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003334}
3335
John McCalldadc5752010-08-24 06:29:42 +00003336StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003338 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003339 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003340 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3341
John McCallb268a282010-08-23 23:25:46 +00003342 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003343 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003344 // in the context of an @catch clause).
3345 Scope *AtCatchParent = CurScope;
3346 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3347 AtCatchParent = AtCatchParent->getParent();
3348 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003349 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 }
John McCallb268a282010-08-23 23:25:46 +00003351 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003352}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003353
John McCalld9bb7432011-07-27 21:50:02 +00003354ExprResult
3355Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3356 ExprResult result = DefaultLvalueConversion(operand);
3357 if (result.isInvalid())
3358 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003359 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003360
3361 // Make sure the expression type is an ObjC pointer or "void *".
3362 QualType type = operand->getType();
3363 if (!type->isDependentType() &&
3364 !type->isObjCObjectPointerType()) {
3365 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003366 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3367 if (getLangOpts().CPlusPlus) {
3368 if (RequireCompleteType(atLoc, type,
3369 diag::err_incomplete_receiver_type))
3370 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3371 << type << operand->getSourceRange();
3372
3373 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3374 if (!result.isUsable())
3375 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3376 << type << operand->getSourceRange();
3377
3378 operand = result.get();
3379 } else {
3380 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3381 << type << operand->getSourceRange();
3382 }
3383 }
John McCalld9bb7432011-07-27 21:50:02 +00003384 }
3385
3386 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003387 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003388}
3389
John McCalldadc5752010-08-24 06:29:42 +00003390StmtResult
John McCallb268a282010-08-23 23:25:46 +00003391Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3392 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003393 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003394 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003395 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003396}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003397
3398/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3399/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003400StmtResult
John McCall48871652010-08-21 09:40:31 +00003401Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003402 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003403 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003404 return new (Context)
3405 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003406}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003407
John McCall31168b02011-06-15 23:02:42 +00003408StmtResult
3409Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3410 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003411 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003412}
3413
Aaron Ballman8aee642902015-04-08 00:05:29 +00003414class CatchHandlerType {
3415 QualType QT;
3416 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003417
Aaron Ballman8aee642902015-04-08 00:05:29 +00003418 // This is a special constructor to be used only with DenseMapInfo's
3419 // getEmptyKey() and getTombstoneKey() functions.
3420 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3421 enum Unique { ForDenseMap };
3422 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3423
Sebastian Redl63c4da02009-07-29 17:15:45 +00003424public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003425 /// Used when creating a CatchHandlerType from a handler type; will determine
3426 /// whether the type is a pointer or reference and will strip off the the top
3427 /// level pointer and cv-qualifiers.
3428 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3429 if (QT->isPointerType())
3430 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003431
Aaron Ballman8aee642902015-04-08 00:05:29 +00003432 if (IsPointer || QT->isReferenceType())
3433 QT = QT->getPointeeType();
3434 QT = QT.getUnqualifiedType();
3435 }
3436
3437 /// Used when creating a CatchHandlerType from a base class type; pretends the
3438 /// type passed in had the pointer qualifier, does not need to get an
3439 /// unqualified type.
3440 CatchHandlerType(QualType QT, bool IsPointer)
3441 : QT(QT), IsPointer(IsPointer) {}
3442
3443 QualType underlying() const { return QT; }
3444 bool isPointer() const { return IsPointer; }
3445
3446 friend bool operator==(const CatchHandlerType &LHS,
3447 const CatchHandlerType &RHS) {
3448 // If the pointer qualification does not match, we can return early.
3449 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003450 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003451 // Otherwise, check the underlying type without cv-qualifiers.
3452 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003453 }
3454};
3455
Aaron Ballman8aee642902015-04-08 00:05:29 +00003456namespace llvm {
3457template <> struct DenseMapInfo<CatchHandlerType> {
3458 static CatchHandlerType getEmptyKey() {
3459 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3460 CatchHandlerType::ForDenseMap);
3461 }
3462
3463 static CatchHandlerType getTombstoneKey() {
3464 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3465 CatchHandlerType::ForDenseMap);
3466 }
3467
3468 static unsigned getHashValue(const CatchHandlerType &Base) {
3469 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3470 }
3471
3472 static bool isEqual(const CatchHandlerType &LHS,
3473 const CatchHandlerType &RHS) {
3474 return LHS == RHS;
3475 }
3476};
3477
3478// It's OK to treat CatchHandlerType as a POD type.
3479template <> struct isPodLike<CatchHandlerType> {
3480 static const bool value = true;
3481};
3482}
3483
3484namespace {
3485class CatchTypePublicBases {
3486 ASTContext &Ctx;
3487 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3488 const bool CheckAgainstPointer;
3489
3490 CXXCatchStmt *FoundHandler;
3491 CanQualType FoundHandlerType;
3492
3493public:
3494 CatchTypePublicBases(
3495 ASTContext &Ctx,
3496 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3497 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3498 FoundHandler(nullptr) {}
3499
3500 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3501 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3502
3503 static bool FindPublicBasesOfType(const CXXBaseSpecifier *S, CXXBasePath &,
3504 void *User) {
3505 auto &PBOT = *reinterpret_cast<CatchTypePublicBases *>(User);
3506 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3507 CatchHandlerType Check(S->getType(), PBOT.CheckAgainstPointer);
3508 auto M = PBOT.TypesToCheck;
3509 auto I = M.find(Check);
3510 if (I != M.end()) {
3511 PBOT.FoundHandler = I->second;
3512 PBOT.FoundHandlerType = PBOT.Ctx.getCanonicalType(S->getType());
3513 return true;
3514 }
3515 }
3516 return false;
3517 }
3518};
Dan Gohman28ade552010-07-26 21:25:24 +00003519}
3520
Sebastian Redl9b244a82008-12-22 21:35:02 +00003521/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3522/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003523StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3524 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003525 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003526 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003527 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003528 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003529
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003530 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3531 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3532
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003533 sema::FunctionScopeInfo *FSI = getCurFunction();
3534
Reid Klecknere7175912015-02-02 22:15:31 +00003535 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003536 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003537 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003538 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003539 }
3540
Robert Wilhelmcafda822013-08-22 09:20:03 +00003541 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003542 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003543 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003544
Aaron Ballman8aee642902015-04-08 00:05:29 +00003545 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003546 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003547 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003548
Aaron Ballman8aee642902015-04-08 00:05:29 +00003549 // Diagnose when the handler is a catch-all handler, but it isn't the last
3550 // handler for the try block. [except.handle]p5. Also, skip exception
3551 // declarations that are invalid, since we can't usefully report on them.
3552 if (!H->getExceptionDecl()) {
3553 if (i < NumHandlers - 1)
3554 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003555 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003556 } else if (H->getExceptionDecl()->isInvalidDecl())
3557 continue;
3558
3559 // Walk the type hierarchy to diagnose when this type has already been
3560 // handled (duplication), or cannot be handled (derivation inversion). We
3561 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003562 CatchHandlerType HandlerCHT =
3563 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003564
3565 // We can ignore whether the type is a reference or a pointer; we need the
3566 // underlying declaration type in order to get at the underlying record
3567 // decl, if there is one.
3568 QualType Underlying = HandlerCHT.underlying();
3569 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3570 if (!RD->hasDefinition())
3571 continue;
3572 // Check that none of the public, unambiguous base classes are in the
3573 // map ([except.handle]p1). Give the base classes the same pointer
3574 // qualification as the original type we are basing off of. This allows
3575 // comparison against the handler type using the same top-level pointer
3576 // as the original type.
3577 CXXBasePaths Paths;
3578 Paths.setOrigin(RD);
3579 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3580 if (RD->lookupInBases(CatchTypePublicBases::FindPublicBasesOfType, &CTPB,
3581 Paths)) {
3582 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3583 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3584 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3585 diag::warn_exception_caught_by_earlier_handler)
3586 << H->getCaughtType();
3587 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3588 diag::note_previous_exception_handler)
3589 << Problem->getCaughtType();
3590 }
3591 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003592 }
Mike Stump11289f42009-09-09 15:08:12 +00003593
Aaron Ballman8aee642902015-04-08 00:05:29 +00003594 // Add the type the list of ones we have handled; diagnose if we've already
3595 // handled it.
3596 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3597 if (!R.second) {
3598 const CXXCatchStmt *Problem = R.first->second;
3599 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3600 diag::warn_exception_caught_by_earlier_handler)
3601 << H->getCaughtType();
3602 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3603 diag::note_previous_exception_handler)
3604 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003605 }
3606 }
Mike Stump11289f42009-09-09 15:08:12 +00003607
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003608 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003609
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003610 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003611}
John Wiegley1c0675e2011-04-28 01:08:34 +00003612
Reid Klecknere7175912015-02-02 22:15:31 +00003613StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3614 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003615 assert(TryBlock && Handler);
3616
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003617 sema::FunctionScopeInfo *FSI = getCurFunction();
3618
Reid Klecknere7175912015-02-02 22:15:31 +00003619 // SEH __try is incompatible with C++ try. Borland appears to support this,
3620 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003621 if (!getLangOpts().Borland) {
3622 if (FSI->FirstCXXTryLoc.isValid()) {
3623 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3624 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3625 }
Reid Klecknere7175912015-02-02 22:15:31 +00003626 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003627
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003628 FSI->setHasSEHTry(TryLoc);
3629
3630 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3631 // track if they use SEH.
3632 DeclContext *DC = CurContext;
3633 while (DC && !DC->isFunctionOrMethod())
3634 DC = DC->getParent();
3635 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3636 if (FD)
3637 FD->setUsesSEHTry(true);
3638 else
3639 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003640
Reid Klecknerddd40962015-04-28 22:19:32 +00003641 // Reject __try on unsupported targets.
3642 if (!Context.getTargetInfo().isSEHTrySupported())
3643 Diag(TryLoc, diag::err_seh_try_unsupported);
3644
Reid Klecknere7175912015-02-02 22:15:31 +00003645 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003646}
3647
3648StmtResult
3649Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3650 Expr *FilterExpr,
3651 Stmt *Block) {
3652 assert(FilterExpr && Block);
3653
3654 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003655 return StmtError(Diag(FilterExpr->getExprLoc(),
3656 diag::err_filter_expression_integral)
3657 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003658 }
3659
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003660 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003661}
3662
Nico Weberd64657f2015-03-09 02:47:59 +00003663void Sema::ActOnStartSEHFinallyBlock() {
3664 CurrentSEHFinally.push_back(CurScope);
3665}
3666
Nico Weberce903292015-03-09 03:17:15 +00003667void Sema::ActOnAbortSEHFinallyBlock() {
3668 CurrentSEHFinally.pop_back();
3669}
3670
Nico Weberd64657f2015-03-09 02:47:59 +00003671StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003672 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003673 CurrentSEHFinally.pop_back();
3674 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003675}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003676
Nico Weberc7d05962014-07-06 22:32:59 +00003677StmtResult
3678Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003679 Scope *SEHTryParent = CurScope;
3680 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3681 SEHTryParent = SEHTryParent->getParent();
3682 if (!SEHTryParent)
3683 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003684 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003685
Nico Weber9b982072014-07-07 00:12:30 +00003686 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003687}
3688
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003689StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3690 bool IsIfExists,
3691 NestedNameSpecifierLoc QualifierLoc,
3692 DeclarationNameInfo NameInfo,
3693 Stmt *Nested)
3694{
3695 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003696 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003697 cast<CompoundStmt>(Nested));
3698}
3699
3700
Chad Rosier02a84392012-08-10 17:56:09 +00003701StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003702 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003703 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003704 UnqualifiedId &Name,
3705 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003706 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003707 SS.getWithLocInContext(Context),
3708 GetNameFromUnqualifiedId(Name),
3709 Nested);
3710}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003711
3712RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003713Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3714 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003715 DeclContext *DC = CurContext;
3716 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3717 DC = DC->getParent();
3718
Craig Topperc3ec1492014-05-26 06:22:03 +00003719 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003720 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003721 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3722 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003723 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003724 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003725
Alexey Bataev330de032014-10-29 12:21:55 +00003726 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003727 DC->addDecl(RD);
3728 RD->setImplicit();
3729 RD->startDefinition();
3730
Alexey Bataev9959db52014-05-06 10:08:46 +00003731 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003732 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003733 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003734 return RD;
3735}
3736
3737static void buildCapturedStmtCaptureList(
3738 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3739 SmallVectorImpl<Expr *> &CaptureInits,
3740 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3741
3742 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3743 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3744
3745 if (Cap->isThisCapture()) {
3746 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3747 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003748 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003749 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003750 } else if (Cap->isVLATypeCapture()) {
3751 Captures.push_back(
3752 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3753 CaptureInits.push_back(nullptr);
3754 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003755 }
3756
3757 assert(Cap->isReferenceCapture() &&
3758 "non-reference capture not yet implemented");
3759
3760 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3761 CapturedStmt::VCK_ByRef,
3762 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003763 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003764 }
3765}
3766
3767void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003768 CapturedRegionKind Kind,
3769 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003770 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003771 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003772
Alexey Bataev9959db52014-05-06 10:08:46 +00003773 // Build the context parameter
3774 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3775 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3776 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3777 ImplicitParamDecl *Param
3778 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3779 DC->addDecl(Param);
3780
3781 CD->setContextParam(0, Param);
3782
3783 // Enter the capturing scope for this captured region.
3784 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3785
3786 if (CurScope)
3787 PushDeclContext(CurScope, CD);
3788 else
3789 CurContext = CD;
3790
3791 PushExpressionEvaluationContext(PotentiallyEvaluated);
3792}
3793
3794void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3795 CapturedRegionKind Kind,
3796 ArrayRef<CapturedParamNameType> Params) {
3797 CapturedDecl *CD = nullptr;
3798 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3799
3800 // Build the context parameter
3801 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3802 bool ContextIsFound = false;
3803 unsigned ParamNum = 0;
3804 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3805 E = Params.end();
3806 I != E; ++I, ++ParamNum) {
3807 if (I->second.isNull()) {
3808 assert(!ContextIsFound &&
3809 "null type has been found already for '__context' parameter");
3810 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3811 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3812 ImplicitParamDecl *Param
3813 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3814 DC->addDecl(Param);
3815 CD->setContextParam(ParamNum, Param);
3816 ContextIsFound = true;
3817 } else {
3818 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3819 ImplicitParamDecl *Param
3820 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3821 DC->addDecl(Param);
3822 CD->setParam(ParamNum, Param);
3823 }
3824 }
3825 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003826 if (!ContextIsFound) {
3827 // Add __context implicitly if it is not specified.
3828 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3829 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3830 ImplicitParamDecl *Param =
3831 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3832 DC->addDecl(Param);
3833 CD->setContextParam(ParamNum, Param);
3834 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003835 // Enter the capturing scope for this captured region.
3836 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3837
3838 if (CurScope)
3839 PushDeclContext(CurScope, CD);
3840 else
3841 CurContext = CD;
3842
3843 PushExpressionEvaluationContext(PotentiallyEvaluated);
3844}
3845
Wei Pan17fbf6e2013-05-04 03:59:06 +00003846void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003847 DiscardCleanupsInEvaluationContext();
3848 PopExpressionEvaluationContext();
3849
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003850 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3851 RecordDecl *Record = RSI->TheRecordDecl;
3852 Record->setInvalidDecl();
3853
Aaron Ballman62e47c42014-03-10 13:43:55 +00003854 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003855 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3856 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003857
Wei Pan17fbf6e2013-05-04 03:59:06 +00003858 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003859 PopFunctionScopeInfo();
3860}
3861
3862StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3863 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3864
3865 SmallVector<CapturedStmt::Capture, 4> Captures;
3866 SmallVector<Expr *, 4> CaptureInits;
3867 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3868
3869 CapturedDecl *CD = RSI->TheCapturedDecl;
3870 RecordDecl *RD = RSI->TheRecordDecl;
3871
Wei Pan17fbf6e2013-05-04 03:59:06 +00003872 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3873 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003874 CaptureInits, CD, RD);
3875
3876 CD->setBody(Res->getCapturedStmt());
3877 RD->completeDefinition();
3878
Wei Pan17fbf6e2013-05-04 03:59:06 +00003879 DiscardCleanupsInEvaluationContext();
3880 PopExpressionEvaluationContext();
3881
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003882 PopDeclContext();
3883 PopFunctionScopeInfo();
3884
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003885 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003886}