blob: b738793ef963a2b1de2ec4423ed7755a26503b46 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall1cd76e82011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000022#include "clang/AST/StmtCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/AST/StmtObjC.h"
John McCall209acbd2010-04-06 22:24:14 +000024#include "clang/AST/TypeLoc.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000038
John McCall60d7b3a2010-08-24 06:29:42 +000039StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000040 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000041 if (!E) // FIXME: FullExprArg has no error state?
42 return StmtError();
43
Chris Lattner834a72a2008-07-25 23:18:17 +000044 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
45 // void expression for its side effects. Conversion to void allows any
46 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000047
Chris Lattner834a72a2008-07-25 23:18:17 +000048 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000049 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
52
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000053StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000054 bool HasLeadingEmptyMacro) {
55 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000056}
57
Chris Lattner337e5502011-02-18 01:27:55 +000058StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
59 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000060 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner20401692009-04-12 20:13:14 +000062 // If we have an invalid decl, just return an error.
63 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattner24e1e702009-03-04 04:23:07 +000065 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000066}
67
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000068void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
69 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000070
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000071 // If we have an invalid decl, just return.
72 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000073 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
74
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000075 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000076 var->setUsed();
77
John McCall7acddac2011-06-17 06:42:21 +000078 // foreach variables are never actually initialized in the way that
79 // the parser came up with.
80 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000081
John McCall7acddac2011-06-17 06:42:21 +000082 // In ARC, we don't need to retain the iteration variable of a fast
83 // enumeration loop. Rather than actually trying to catch that
84 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000085 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000086 QualType type = var->getType();
87
88 // Only do this if we inferred the lifetime. Inferred lifetime
89 // will show up as a local qualifier because explicit lifetime
90 // should have shown up as an AttributedType instead.
91 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
92 // Add 'const' and mark the variable as pseudo-strong.
93 var->setType(type.withConst());
94 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000095 }
96 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000097}
98
Chandler Carruthec8058f2011-08-17 09:34:37 +000099/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000100///
101/// Adding a cast to void (or other expression wrappers) will prevent the
102/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000103static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000104 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000105 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000106
107 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
108 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000109 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000111 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000112 IsNotEqual = Op->getOpcode() == BO_NE;
113 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000114 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
115 if (Op->getOperator() != OO_EqualEqual &&
116 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000117 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000119 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000120 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
121 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122 } else {
123 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000124 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000125 }
126
127 // Suppress warnings when the operator, suspicious as it may be, comes from
128 // a macro expansion.
129 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000130 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000131
Chandler Carruthec8058f2011-08-17 09:34:37 +0000132 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000133 << (unsigned)IsNotEqual << E->getSourceRange();
134
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000135 // If the LHS is a plausible entity to assign to, provide a fixit hint to
136 // correct common typos.
137 if (CanAssign) {
138 if (IsNotEqual)
139 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
140 << FixItHint::CreateReplacement(Loc, "|=");
141 else
142 S.Diag(Loc, diag::note_equality_comparison_to_assign)
143 << FixItHint::CreateReplacement(Loc, "=");
144 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000145
146 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000147}
148
Anders Carlsson636463e2009-07-30 22:17:18 +0000149void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000150 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
151 return DiagnoseUnusedExprResult(Label->getSubStmt());
152
Anders Carlsson75443112009-07-30 22:39:03 +0000153 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000154 if (!E)
155 return;
156
Eli Friedmana6115062012-05-24 00:47:05 +0000157 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000158 SourceLocation Loc;
159 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000160 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000161 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000162 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner06b3a062012-08-31 22:39:21 +0000164 // If this is a GNU statement expression expanded from a macro, it is probably
165 // unused because it is a function-like macro that can be used as either an
166 // expression or statement. Don't warn, because it is almost certainly a
167 // false positive.
168 if (isa<StmtExpr>(E) && Loc.isMacroID())
169 return;
170
Chris Lattner419cfb32009-08-16 16:57:27 +0000171 // Okay, we have an unused result. Depending on what the base expression is,
172 // we might want to make a more specific diagnostic. Check for one of these
173 // cases now.
174 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000175 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000176 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000177 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
178 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000179
Chandler Carruthec8058f2011-08-17 09:34:37 +0000180 if (DiagnoseUnusedComparison(*this, E))
181 return;
182
Eli Friedmana6115062012-05-24 00:47:05 +0000183 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000184 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000185 if (E->getType()->isVoidType())
186 return;
187
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000188 // If the callee has attribute pure, const, or warn_unused_result, warn with
189 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000190 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000191 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000192 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000193 return;
194 }
195 if (FD->getAttr<PureAttr>()) {
196 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
197 return;
198 }
199 if (FD->getAttr<ConstAttr>()) {
200 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
201 return;
202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203 }
John McCall12f78a62010-12-02 01:19:52 +0000204 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000205 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000206 Diag(Loc, diag::err_arc_unused_init_message) << R1;
207 return;
208 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000209 const ObjCMethodDecl *MD = ME->getMethodDecl();
210 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000211 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000212 return;
213 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000214 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
215 const Expr *Source = POE->getSyntacticForm();
216 if (isa<ObjCSubscriptRefExpr>(Source))
217 DiagID = diag::warn_unused_container_subscript_expr;
218 else
219 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000220 } else if (const CXXFunctionalCastExpr *FC
221 = dyn_cast<CXXFunctionalCastExpr>(E)) {
222 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
223 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
224 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000225 }
John McCall209acbd2010-04-06 22:24:14 +0000226 // Diagnose "(void*) blah" as a typo for "(void) blah".
227 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
228 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
229 QualType T = TI->getType();
230
231 // We really do want to use the non-canonical type here.
232 if (T == Context.VoidPtrTy) {
233 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
234
235 Diag(Loc, diag::warn_unused_voidptr)
236 << FixItHint::CreateRemoval(TL.getStarLoc());
237 return;
238 }
239 }
240
Eli Friedmana6115062012-05-24 00:47:05 +0000241 if (E->isGLValue() && E->getType().isVolatileQualified()) {
242 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
243 return;
244 }
245
Ted Kremenek351ba912011-02-23 01:52:04 +0000246 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000247}
248
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000249void Sema::ActOnStartOfCompoundStmt() {
250 PushCompoundScope();
251}
252
253void Sema::ActOnFinishOfCompoundStmt() {
254 PopCompoundScope();
255}
256
257sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
258 return getCurFunction()->CompoundScopes.back();
259}
260
John McCall60d7b3a2010-08-24 06:29:42 +0000261StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000262Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000263 MultiStmtArg elts, bool isStmtExpr) {
264 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000265 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000266 // If we're in C89 mode, check that we don't have any decls after stmts. If
267 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000268 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000269 // Note that __extension__ can be around a decl.
270 unsigned i = 0;
271 // Skip over all declarations.
272 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
273 /*empty*/;
274
275 // We found the end of the list or a statement. Scan for another declstmt.
276 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
277 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000279 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000280 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000281 Diag(D->getLocation(), diag::ext_mixed_decls_code);
282 }
283 }
Chris Lattner98414c12007-08-31 21:49:55 +0000284 // Warn about unused expressions in statements.
285 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000286 // Ignore statements that are last in a statement expression.
287 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000288 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Anders Carlsson636463e2009-07-30 22:17:18 +0000290 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000291 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000292
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000293 // Check for suspicious empty body (null statement) in `for' and `while'
294 // statements. Don't do anything for template instantiations, this just adds
295 // noise.
296 if (NumElts != 0 && !CurrentInstantiationScope &&
297 getCurCompoundScope().HasEmptyLoopBodies) {
298 for (unsigned i = 0; i != NumElts - 1; ++i)
299 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
300 }
301
Nico Weberd36aa352012-12-29 20:03:39 +0000302 return Owned(new (Context) CompoundStmt(Context,
303 llvm::makeArrayRef(Elts, NumElts),
304 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000305}
306
John McCall60d7b3a2010-08-24 06:29:42 +0000307StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000308Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
309 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000310 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000311 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000312
John McCall781472f2010-08-25 08:40:02 +0000313 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000314 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000315 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000316 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000317
Richard Smith80ad52f2013-01-02 11:42:31 +0000318 if (!getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000319 // C99 6.8.4.2p3: The expression shall be an integer constant.
320 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000321 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
322 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
323 if (!LHSVal)
324 return StmtError();
325 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000326
327 // GCC extension: The expression shall be an integer constant.
328
Richard Smith282e7e62012-02-04 09:53:13 +0000329 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
330 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
331 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000332 }
333 }
334
Douglas Gregordbb26db2009-05-15 23:57:33 +0000335 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
336 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000337 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000338 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
Chris Lattner24e1e702009-03-04 04:23:07 +0000341/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000342void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000343 DiagnoseUnusedExprResult(SubStmt);
344
Chris Lattner24e1e702009-03-04 04:23:07 +0000345 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000346 CS->setSubStmt(SubStmt);
347}
348
John McCall60d7b3a2010-08-24 06:29:42 +0000349StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000350Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000351 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000352 DiagnoseUnusedExprResult(SubStmt);
353
John McCall781472f2010-08-25 08:40:02 +0000354 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000355 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000356 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000357 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000358
Douglas Gregordbb26db2009-05-15 23:57:33 +0000359 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000360 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000361 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000362}
363
John McCall60d7b3a2010-08-24 06:29:42 +0000364StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000365Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
366 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000367 // If the label was multiply defined, reject it now.
368 if (TheDecl->getStmt()) {
369 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
370 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000371 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 }
Sebastian Redlde307472009-01-11 00:38:46 +0000373
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000374 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000375 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
376 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000377 if (!TheDecl->isGnuLocal()) {
378 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000379 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000380 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000381 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000382}
383
Richard Smith534986f2012-04-14 00:33:13 +0000384StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000385 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000386 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000387 // Fill in the declaration and return it.
388 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000389 return Owned(LS);
390}
391
John McCall60d7b3a2010-08-24 06:29:42 +0000392StmtResult
John McCalld226f652010-08-21 09:40:31 +0000393Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000394 Stmt *thenStmt, SourceLocation ElseLoc,
395 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000396 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000398 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000399 if (CondVar) {
400 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000401 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000402 if (CondResult.isInvalid())
403 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000404 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000405 Expr *ConditionExpr = CondResult.takeAs<Expr>();
406 if (!ConditionExpr)
407 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408
Anders Carlsson75443112009-07-30 22:39:03 +0000409 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000410
John McCall9ae2f072010-08-23 23:25:46 +0000411 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000412 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
413 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000414 }
415
Anders Carlsson75443112009-07-30 22:39:03 +0000416 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000418 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000419 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000420}
421
Chris Lattnerf4021e72007-08-23 05:46:52 +0000422/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
423/// the specified width and sign. If an overflow occurs, detect it and emit
424/// the specified diagnostic.
425void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
426 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000427 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000428 unsigned DiagID) {
429 // Perform a conversion to the promoted condition type if needed.
430 if (NewWidth > Val.getBitWidth()) {
431 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000432 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000433 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000434
435 // If the input was signed and negative and the output is
436 // unsigned, don't bother to warn: this is implementation-defined
437 // behavior.
438 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000439 } else if (NewWidth < Val.getBitWidth()) {
440 // If this is a truncation, check for overflow.
441 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000442 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000443 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000444 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000445 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000446 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000447 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Chris Lattnerf4021e72007-08-23 05:46:52 +0000449 // Regardless of whether a diagnostic was emitted, really do the
450 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000451 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000452 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000453 } else if (NewSign != Val.isSigned()) {
454 // Convert the sign to match the sign of the condition. This can cause
455 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000456 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000457 // behavior.
458 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000459 llvm::APSInt OldVal(Val);
460 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000461 }
462}
463
Chris Lattner0471f5b2007-08-23 18:29:20 +0000464namespace {
465 struct CaseCompareFunctor {
466 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
467 const llvm::APSInt &RHS) {
468 return LHS.first < RHS;
469 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000470 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
471 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
472 return LHS.first < RHS.first;
473 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000474 bool operator()(const llvm::APSInt &LHS,
475 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
476 return LHS < RHS.first;
477 }
478 };
479}
480
Chris Lattner764a7ce2007-09-21 18:15:22 +0000481/// CmpCaseVals - Comparison predicate for sorting case values.
482///
483static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
484 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
485 if (lhs.first < rhs.first)
486 return true;
487
488 if (lhs.first == rhs.first &&
489 lhs.second->getCaseLoc().getRawEncoding()
490 < rhs.second->getCaseLoc().getRawEncoding())
491 return true;
492 return false;
493}
494
Douglas Gregorba915af2010-02-08 22:24:16 +0000495/// CmpEnumVals - Comparison predicate for sorting enumeration values.
496///
497static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
498 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
499{
500 return lhs.first < rhs.first;
501}
502
503/// EqEnumVals - Comparison preficate for uniqing enumeration values.
504///
505static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
506 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
507{
508 return lhs.first == rhs.first;
509}
510
Chris Lattner5f048812009-10-16 16:45:22 +0000511/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
512/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000513static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
514 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
515 expr = cleanups->getSubExpr();
516 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
517 if (impcast->getCastKind() != CK_IntegralCast) break;
518 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000519 }
520 return expr->getType();
521}
522
John McCall60d7b3a2010-08-24 06:29:42 +0000523StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000525 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000526 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000527
Douglas Gregor586596f2010-05-06 17:25:47 +0000528 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000529 if (CondVar) {
530 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000531 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
532 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000533 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000534
John McCall9ae2f072010-08-23 23:25:46 +0000535 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000536 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000537
John McCall9ae2f072010-08-23 23:25:46 +0000538 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000539 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000540
Douglas Gregorab41fe92012-05-04 22:38:52 +0000541 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
542 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000543
Douglas Gregorab41fe92012-05-04 22:38:52 +0000544 public:
545 SwitchConvertDiagnoser(Expr *Cond)
546 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000547
Douglas Gregorab41fe92012-05-04 22:38:52 +0000548 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
549 QualType T) {
550 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
551 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000552
Douglas Gregorab41fe92012-05-04 22:38:52 +0000553 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
554 QualType T) {
555 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
556 << T << Cond->getSourceRange();
557 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000558
Douglas Gregorab41fe92012-05-04 22:38:52 +0000559 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
560 QualType T,
561 QualType ConvTy) {
562 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
563 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000564
Douglas Gregorab41fe92012-05-04 22:38:52 +0000565 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
566 QualType ConvTy) {
567 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
568 << ConvTy->isEnumeralType() << ConvTy;
569 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000570
Douglas Gregorab41fe92012-05-04 22:38:52 +0000571 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
572 QualType T) {
573 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
574 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000575
Douglas Gregorab41fe92012-05-04 22:38:52 +0000576 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
577 QualType ConvTy) {
578 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
579 << ConvTy->isEnumeralType() << ConvTy;
580 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000581
Douglas Gregorab41fe92012-05-04 22:38:52 +0000582 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
583 QualType T,
584 QualType ConvTy) {
585 return DiagnosticBuilder::getEmpty();
586 }
587 } SwitchDiagnoser(Cond);
588
John McCall9ae2f072010-08-23 23:25:46 +0000589 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000590 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000591 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000592 if (CondResult.isInvalid()) return StmtError();
593 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594
John McCalla8e0cd82011-08-06 07:30:58 +0000595 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
596 CondResult = UsualUnaryConversions(Cond);
597 if (CondResult.isInvalid()) return StmtError();
598 Cond = CondResult.take();
599
John McCalld226f652010-08-21 09:40:31 +0000600 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000601 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000602 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000603 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000604 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000605 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000606 }
John McCallb60a77e2010-08-01 00:26:45 +0000607
John McCall781472f2010-08-25 08:40:02 +0000608 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
John McCall9ae2f072010-08-23 23:25:46 +0000610 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000611 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000612 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000613}
614
Gabor Greif28164ab2010-10-01 22:05:14 +0000615static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
616 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000617 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000618 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000619 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000620 Val.setIsSigned(IsSigned);
621}
622
John McCall60d7b3a2010-08-24 06:29:42 +0000623StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000624Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
625 Stmt *BodyStmt) {
626 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000627 assert(SS == getCurFunction()->SwitchStack.back() &&
628 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000629
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000630 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000631 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000632
Chris Lattnerf4021e72007-08-23 05:46:52 +0000633 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000634 if (!CondExpr) return StmtError();
635
636 QualType CondType = CondExpr->getType();
637
John McCall0fb97082010-05-18 03:19:21 +0000638 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000639 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000640 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000641
Chris Lattner5f048812009-10-16 16:45:22 +0000642 // C++ 6.4.2.p2:
643 // Integral promotions are performed (on the switch condition).
644 //
645 // A case value unrepresentable by the original switch condition
646 // type (before the promotion) doesn't make sense, even when it can
647 // be represented by the promoted type. Therefore we need to find
648 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000649 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000650 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000651 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000652 // appropriate type now, just return an error.
653 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000654 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000655
Chris Lattner2b334bb2010-04-16 23:34:13 +0000656 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000657 // switch(bool_expr) {...} is often a programmer error, e.g.
658 // switch(n && mask) { ... } // Doh - should be "n & mask".
659 // One can always use an if statement instead of switch(bool_expr).
660 Diag(SwitchLoc, diag::warn_bool_switch_condition)
661 << CondExpr->getSourceRange();
662 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000663 }
Sebastian Redlde307472009-01-11 00:38:46 +0000664
Chris Lattnerf4021e72007-08-23 05:46:52 +0000665 // Get the bitwidth of the switched-on value before promotions. We must
666 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000667 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000668 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000669 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000670 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000671 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000672 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattnerf4021e72007-08-23 05:46:52 +0000674 // Accumulate all of the case values in a vector so that we can sort them
675 // and detect duplicates. This vector contains the APInt for the case after
676 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000677 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000678 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Chris Lattnerf4021e72007-08-23 05:46:52 +0000680 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000681 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
682 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattnerf4021e72007-08-23 05:46:52 +0000684 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000686 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Douglas Gregordbb26db2009-05-15 23:57:33 +0000688 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000689 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000691 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000692 if (TheDefaultStmt) {
693 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000694 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000695
Chris Lattnerf4021e72007-08-23 05:46:52 +0000696 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000697 // we'll return a valid AST. This requires recursing down the AST and
698 // finding it, not something we are set up to do right now. For now,
699 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000700 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000701 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000702 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattnerf4021e72007-08-23 05:46:52 +0000704 } else {
705 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattner1e0a3902008-01-16 19:17:22 +0000707 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000708
709 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
710 HasDependentValue = true;
711 break;
712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Richard Smith8ef7b202012-01-18 23:55:52 +0000714 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Richard Smith80ad52f2013-01-02 11:42:31 +0000716 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000717 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
718 // constant expression of the promoted type of the switch condition.
719 ExprResult ConvLo =
720 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
721 if (ConvLo.isInvalid()) {
722 CaseListIsErroneous = true;
723 continue;
724 }
725 Lo = ConvLo.take();
726 } else {
727 // We already verified that the expression has a i-c-e value (C99
728 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +0000729 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
730 LoVal = Lo->EvaluateKnownConstInt(Context, &Diags);
731 if (Diags.size() == 1 &&
732 Diags[0].second.getDiagID() == diag::note_constexpr_overflow) {
Fariborz Jahanianf6e65cc2013-01-10 20:26:42 +0000733 Diag(Lo->getLocStart(), diag::warn_case_constant_overflow) <<
734 LoVal.toString(10);
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +0000735 Diag(Diags[0].first, Diags[0].second);
736 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000737
738 // If the LHS is not the same type as the condition, insert an implicit
739 // cast.
740 Lo = DefaultLvalueConversion(Lo).take();
741 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
742 }
743
744 // Convert the value to the same width/sign as the condition had prior to
745 // integral promotions.
746 //
747 // FIXME: This causes us to reject valid code:
748 // switch ((char)c) { case 256: case 0: return 0; }
749 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000750 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000751 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000752 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000753
Chris Lattner1e0a3902008-01-16 19:17:22 +0000754 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000756 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000757 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000758 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000759 CS->getRHS()->isValueDependent()) {
760 HasDependentValue = true;
761 break;
762 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000763 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000764 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000765 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000766 }
767 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000768
769 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000770 // If we don't have a default statement, check whether the
771 // condition is constant.
772 llvm::APSInt ConstantCondValue;
773 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000774 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000775 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000776 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
777 Expr::SE_AllowSideEffects);
778 assert(!HasConstantCond ||
779 (ConstantCondValue.getBitWidth() == CondWidth &&
780 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000781 }
Richard Smith80d4b552011-12-28 19:48:30 +0000782 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000783
Douglas Gregordbb26db2009-05-15 23:57:33 +0000784 // Sort all the scalar case values so we can easily detect duplicates.
785 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
786
787 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000788 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
789 if (ShouldCheckConstantCond &&
790 CaseVals[i].first == ConstantCondValue)
791 ShouldCheckConstantCond = false;
792
793 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000794 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000795 // First, determine if either case value has a name
796 StringRef PrevString, CurrString;
797 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
798 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
799 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
800 PrevString = DeclRef->getDecl()->getName();
801 }
802 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
803 CurrString = DeclRef->getDecl()->getName();
804 }
Douglas Gregor50de5e32012-05-16 16:11:17 +0000805 llvm::SmallString<16> CaseValStr;
806 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000807
808 if (PrevString == CurrString)
809 Diag(CaseVals[i].second->getLHS()->getLocStart(),
810 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000811 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000812 else
813 Diag(CaseVals[i].second->getLHS()->getLocStart(),
814 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000815 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
816 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000817 CaseValStr;
818
John McCall0fb97082010-05-18 03:19:21 +0000819 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000820 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000821 // FIXME: We really want to remove the bogus case stmt from the
822 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000823 CaseListIsErroneous = true;
824 }
825 }
826 }
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregordbb26db2009-05-15 23:57:33 +0000828 // Detect duplicate case ranges, which usually don't exist at all in
829 // the first place.
830 if (!CaseRanges.empty()) {
831 // Sort all the case ranges by their low value so we can easily detect
832 // overlaps between ranges.
833 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregordbb26db2009-05-15 23:57:33 +0000835 // Scan the ranges, computing the high values and removing empty ranges.
836 std::vector<llvm::APSInt> HiVals;
837 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000838 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000839 CaseStmt *CR = CaseRanges[i].second;
840 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000841 llvm::APSInt HiVal;
842
Richard Smith80ad52f2013-01-02 11:42:31 +0000843 if (getLangOpts().CPlusPlus11) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000844 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
845 // constant expression of the promoted type of the switch condition.
846 ExprResult ConvHi =
847 CheckConvertedConstantExpression(Hi, CondType, HiVal,
848 CCEK_CaseValue);
849 if (ConvHi.isInvalid()) {
850 CaseListIsErroneous = true;
851 continue;
852 }
853 Hi = ConvHi.take();
854 } else {
855 HiVal = Hi->EvaluateKnownConstInt(Context);
856
857 // If the RHS is not the same type as the condition, insert an
858 // implicit cast.
859 Hi = DefaultLvalueConversion(Hi).take();
860 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregordbb26db2009-05-15 23:57:33 +0000863 // Convert the value to the same width/sign as the condition.
864 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000865 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000866 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Douglas Gregordbb26db2009-05-15 23:57:33 +0000868 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregordbb26db2009-05-15 23:57:33 +0000870 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000871 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000872 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
873 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000874 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000875 CaseRanges.erase(CaseRanges.begin()+i);
876 --i, --e;
877 continue;
878 }
John McCall0fb97082010-05-18 03:19:21 +0000879
880 if (ShouldCheckConstantCond &&
881 LoVal <= ConstantCondValue &&
882 ConstantCondValue <= HiVal)
883 ShouldCheckConstantCond = false;
884
Douglas Gregordbb26db2009-05-15 23:57:33 +0000885 HiVals.push_back(HiVal);
886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregordbb26db2009-05-15 23:57:33 +0000888 // Rescan the ranges, looking for overlap with singleton values and other
889 // ranges. Since the range list is sorted, we only need to compare case
890 // ranges with their neighbors.
891 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
892 llvm::APSInt &CRLo = CaseRanges[i].first;
893 llvm::APSInt &CRHi = HiVals[i];
894 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Douglas Gregordbb26db2009-05-15 23:57:33 +0000896 // Check to see whether the case range overlaps with any
897 // singleton cases.
898 CaseStmt *OverlapStmt = 0;
899 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregordbb26db2009-05-15 23:57:33 +0000901 // Find the smallest value >= the lower bound. If I is in the
902 // case range, then we have overlap.
903 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
904 CaseVals.end(), CRLo,
905 CaseCompareFunctor());
906 if (I != CaseVals.end() && I->first < CRHi) {
907 OverlapVal = I->first; // Found overlap with scalar.
908 OverlapStmt = I->second;
909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregordbb26db2009-05-15 23:57:33 +0000911 // Find the smallest value bigger than the upper bound.
912 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
913 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
914 OverlapVal = (I-1)->first; // Found overlap with scalar.
915 OverlapStmt = (I-1)->second;
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Douglas Gregordbb26db2009-05-15 23:57:33 +0000918 // Check to see if this case stmt overlaps with the subsequent
919 // case range.
920 if (i && CRLo <= HiVals[i-1]) {
921 OverlapVal = HiVals[i-1]; // Found overlap with range.
922 OverlapStmt = CaseRanges[i-1].second;
923 }
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Douglas Gregordbb26db2009-05-15 23:57:33 +0000925 if (OverlapStmt) {
926 // If we have a duplicate, report it.
927 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
928 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000929 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000930 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000931 // FIXME: We really want to remove the bogus case stmt from the
932 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000933 CaseListIsErroneous = true;
934 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000935 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000936 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000937
John McCall0fb97082010-05-18 03:19:21 +0000938 // Complain if we have a constant condition and we didn't find a match.
939 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
940 // TODO: it would be nice if we printed enums as enums, chars as
941 // chars, etc.
942 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
943 << ConstantCondValue.toString(10)
944 << CondExpr->getSourceRange();
945 }
946
947 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000948 // values. We only issue a warning if there is not 'default:', but
949 // we still do the analysis to preserve this information in the AST
950 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000951 //
Chris Lattnerce784612010-09-16 17:09:42 +0000952 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000953
Douglas Gregorba915af2010-02-08 22:24:16 +0000954 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000955 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000956 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000957 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000958 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000959 EnumValsTy EnumVals;
960
John McCall0fb97082010-05-18 03:19:21 +0000961 // Gather all enum values, set their type and sort them,
962 // allowing easier comparison with CaseVals.
963 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000964 EDI != ED->enumerator_end(); ++EDI) {
965 llvm::APSInt Val = EDI->getInitVal();
966 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000967 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000968 }
969 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000970 EnumValsTy::iterator EIend =
971 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000972
973 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000974 EnumValsTy::const_iterator EI = EnumVals.begin();
975 for (CaseValsTy::const_iterator CI = CaseVals.begin();
976 CI != CaseVals.end(); CI++) {
977 while (EI != EIend && EI->first < CI->first)
978 EI++;
979 if (EI == EIend || EI->first > CI->first)
980 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000981 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000982 }
983 // See which of case ranges aren't in enum
984 EI = EnumVals.begin();
985 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
986 RI != CaseRanges.end() && EI != EIend; RI++) {
987 while (EI != EIend && EI->first < RI->first)
988 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000989
David Blaikie93667502012-01-22 02:31:55 +0000990 if (EI == EIend || EI->first != RI->first) {
991 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000992 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000993 }
David Blaikie93667502012-01-22 02:31:55 +0000994
Chad Rosier1093f492012-08-10 17:56:09 +0000995 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +0000996 RI->second->getRHS()->EvaluateKnownConstInt(Context);
997 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
998 while (EI != EIend && EI->first < Hi)
999 EI++;
1000 if (EI == EIend || EI->first != Hi)
1001 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +00001002 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +00001003 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001004
Ted Kremenek559fb552010-09-09 00:05:53 +00001005 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +00001006 CaseValsTy::const_iterator CI = CaseVals.begin();
1007 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001008 bool hasCasesNotInSwitch = false;
1009
Chris Lattner5f9e2722011-07-23 10:55:15 +00001010 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
David Blaikie93667502012-01-22 02:31:55 +00001012 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001013 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001014 llvm::APSInt CIVal;
1015 while (CI != CaseVals.end() && CI->first < EI->first)
1016 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
Douglas Gregorba915af2010-02-08 22:24:16 +00001018 if (CI != CaseVals.end() && CI->first == EI->first)
1019 continue;
1020
Ted Kremenek559fb552010-09-09 00:05:53 +00001021 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001022 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001023 llvm::APSInt Hi =
1024 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001025 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001026 if (EI->first <= Hi)
1027 break;
1028 }
1029
Ted Kremenek559fb552010-09-09 00:05:53 +00001030 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001031 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001032 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001033 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001034 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
David Blaikie585d7792012-01-23 04:46:12 +00001036 if (TheDefaultStmt && UnhandledNames.empty())
1037 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001038
Chris Lattnerce784612010-09-16 17:09:42 +00001039 // Produce a nice diagnostic if multiple values aren't handled.
1040 switch (UnhandledNames.size()) {
1041 case 0: break;
1042 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001043 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001044 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001045 << UnhandledNames[0];
1046 break;
1047 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001048 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001049 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001050 << UnhandledNames[0] << UnhandledNames[1];
1051 break;
1052 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001053 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1054 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001055 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1056 break;
1057 default:
David Blaikie585d7792012-01-23 04:46:12 +00001058 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1059 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001060 << (unsigned)UnhandledNames.size()
1061 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1062 break;
1063 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001064
1065 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001066 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001067 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001068 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001069
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001070 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1071 diag::warn_empty_switch_body);
1072
Mike Stump390b4cc2009-05-16 07:39:55 +00001073 // FIXME: If the case list was broken is some way, we don't have a good system
1074 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001075 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001076 return StmtError();
1077
Sebastian Redlde307472009-01-11 00:38:46 +00001078 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001079}
1080
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001081void
1082Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1083 Expr *SrcExpr) {
1084 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001085 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001086 == DiagnosticsEngine::Ignored)
1087 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001088
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001089 if (const EnumType *ET = DstType->getAs<EnumType>())
1090 if (!Context.hasSameType(SrcType, DstType) &&
1091 SrcType->isIntegerType()) {
1092 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1093 SrcExpr->isIntegerConstantExpr(Context)) {
1094 // Get the bitwidth of the enum value before promotions.
1095 unsigned DstWith = Context.getIntWidth(DstType);
1096 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1097
1098 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1099 const EnumDecl *ED = ET->getDecl();
1100 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1101 EnumValsTy;
1102 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001103
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001104 // Gather all enum values, set their type and sort them,
1105 // allowing easier comparison with rhs constant.
1106 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1107 EDI != ED->enumerator_end(); ++EDI) {
1108 llvm::APSInt Val = EDI->getInitVal();
1109 AdjustAPSInt(Val, DstWith, DstIsSigned);
1110 EnumVals.push_back(std::make_pair(Val, *EDI));
1111 }
1112 if (EnumVals.empty())
1113 return;
1114 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1115 EnumValsTy::iterator EIend =
1116 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001117
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001118 // See which case values aren't in enum.
1119 EnumValsTy::const_iterator EI = EnumVals.begin();
1120 while (EI != EIend && EI->first < RhsVal)
1121 EI++;
1122 if (EI == EIend || EI->first != RhsVal) {
1123 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1124 << DstType;
1125 }
1126 }
1127 }
1128}
1129
John McCall60d7b3a2010-08-24 06:29:42 +00001130StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001131Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001132 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001133 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001134
Douglas Gregor5656e142009-11-24 21:15:44 +00001135 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001136 if (CondVar) {
1137 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001138 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001139 if (CondResult.isInvalid())
1140 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001141 }
John McCall9ae2f072010-08-23 23:25:46 +00001142 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001143 if (!ConditionExpr)
1144 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145
John McCall9ae2f072010-08-23 23:25:46 +00001146 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001148 if (isa<NullStmt>(Body))
1149 getCurCompoundScope().setHasEmptyLoopBodies();
1150
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001151 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001152 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001153}
1154
John McCall60d7b3a2010-08-24 06:29:42 +00001155StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001156Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001157 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001158 Expr *Cond, SourceLocation CondRParen) {
1159 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001160
John Wiegley429bb272011-04-08 18:41:53 +00001161 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001162 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001163 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001164 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001165
John McCallb4eb64d2010-10-08 02:01:28 +00001166 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +00001167 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +00001168 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001169 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001170 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171
John McCall9ae2f072010-08-23 23:25:46 +00001172 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001173
John McCall9ae2f072010-08-23 23:25:46 +00001174 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001175}
1176
Richard Trieu694e7962012-04-30 18:01:30 +00001177namespace {
1178 // This visitor will traverse a conditional statement and store all
1179 // the evaluated decls into a vector. Simple is set to true if none
1180 // of the excluded constructs are used.
1181 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1182 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1183 llvm::SmallVector<SourceRange, 10> &Ranges;
1184 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001185public:
1186 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1187
1188 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerfacde172012-06-06 17:32:50 +00001189 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001190 Inherited(S.Context),
1191 Decls(Decls),
1192 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001193 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001194
1195 bool isSimple() { return Simple; }
1196
1197 // Replaces the method in EvaluatedExprVisitor.
1198 void VisitMemberExpr(MemberExpr* E) {
1199 Simple = false;
1200 }
1201
1202 // Any Stmt not whitelisted will cause the condition to be marked complex.
1203 void VisitStmt(Stmt *S) {
1204 Simple = false;
1205 }
1206
1207 void VisitBinaryOperator(BinaryOperator *E) {
1208 Visit(E->getLHS());
1209 Visit(E->getRHS());
1210 }
1211
1212 void VisitCastExpr(CastExpr *E) {
1213 Visit(E->getSubExpr());
1214 }
1215
1216 void VisitUnaryOperator(UnaryOperator *E) {
1217 // Skip checking conditionals with derefernces.
1218 if (E->getOpcode() == UO_Deref)
1219 Simple = false;
1220 else
1221 Visit(E->getSubExpr());
1222 }
1223
1224 void VisitConditionalOperator(ConditionalOperator *E) {
1225 Visit(E->getCond());
1226 Visit(E->getTrueExpr());
1227 Visit(E->getFalseExpr());
1228 }
1229
1230 void VisitParenExpr(ParenExpr *E) {
1231 Visit(E->getSubExpr());
1232 }
1233
1234 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1235 Visit(E->getOpaqueValue()->getSourceExpr());
1236 Visit(E->getFalseExpr());
1237 }
1238
1239 void VisitIntegerLiteral(IntegerLiteral *E) { }
1240 void VisitFloatingLiteral(FloatingLiteral *E) { }
1241 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1242 void VisitCharacterLiteral(CharacterLiteral *E) { }
1243 void VisitGNUNullExpr(GNUNullExpr *E) { }
1244 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1245
1246 void VisitDeclRefExpr(DeclRefExpr *E) {
1247 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1248 if (!VD) return;
1249
1250 Ranges.push_back(E->getSourceRange());
1251
1252 Decls.insert(VD);
1253 }
1254
1255 }; // end class DeclExtractor
1256
1257 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001258 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001259 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1260 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1261 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001262
1263public:
1264 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1265
1266 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1267 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1268 if (!Statement) return;
1269
1270 Visit(Statement);
1271 }
1272
1273 void VisitReturnStmt(ReturnStmt *S) {
1274 FoundDecl = true;
1275 }
1276
1277 void VisitBreakStmt(BreakStmt *S) {
1278 FoundDecl = true;
1279 }
1280
1281 void VisitGotoStmt(GotoStmt *S) {
1282 FoundDecl = true;
1283 }
1284
1285 void VisitCastExpr(CastExpr *E) {
1286 if (E->getCastKind() == CK_LValueToRValue)
1287 CheckLValueToRValueCast(E->getSubExpr());
1288 else
1289 Visit(E->getSubExpr());
1290 }
1291
1292 void CheckLValueToRValueCast(Expr *E) {
1293 E = E->IgnoreParenImpCasts();
1294
1295 if (isa<DeclRefExpr>(E)) {
1296 return;
1297 }
1298
1299 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1300 Visit(CO->getCond());
1301 CheckLValueToRValueCast(CO->getTrueExpr());
1302 CheckLValueToRValueCast(CO->getFalseExpr());
1303 return;
1304 }
1305
1306 if (BinaryConditionalOperator *BCO =
1307 dyn_cast<BinaryConditionalOperator>(E)) {
1308 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1309 CheckLValueToRValueCast(BCO->getFalseExpr());
1310 return;
1311 }
1312
1313 Visit(E);
1314 }
1315
1316 void VisitDeclRefExpr(DeclRefExpr *E) {
1317 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1318 if (Decls.count(VD))
1319 FoundDecl = true;
1320 }
1321
1322 bool FoundDeclInUse() { return FoundDecl; }
1323
1324 }; // end class DeclMatcher
1325
1326 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1327 Expr *Third, Stmt *Body) {
1328 // Condition is empty
1329 if (!Second) return;
1330
1331 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1332 Second->getLocStart())
1333 == DiagnosticsEngine::Ignored)
1334 return;
1335
1336 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1337 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1338 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001339 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001340 DE.Visit(Second);
1341
1342 // Don't analyze complex conditionals.
1343 if (!DE.isSimple()) return;
1344
1345 // No decls found.
1346 if (Decls.size() == 0) return;
1347
Richard Trieu90875992012-05-04 03:01:54 +00001348 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001349 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1350 E = Decls.end();
1351 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001352 if ((*I)->getType().isVolatileQualified() ||
1353 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001354
1355 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1356 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1357 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1358 return;
1359
1360 // Load decl names into diagnostic.
1361 if (Decls.size() > 4)
1362 PDiag << 0;
1363 else {
1364 PDiag << Decls.size();
1365 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1366 E = Decls.end();
1367 I != E; ++I)
1368 PDiag << (*I)->getDeclName();
1369 }
1370
1371 // Load SourceRanges into diagnostic if there is room.
1372 // Otherwise, load the SourceRange of the conditional expression.
1373 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1374 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1375 E = Ranges.end();
1376 I != E; ++I)
1377 PDiag << *I;
1378 else
1379 PDiag << Second->getSourceRange();
1380
1381 S.Diag(Ranges.begin()->getBegin(), PDiag);
1382 }
1383
1384} // end namespace
1385
John McCall60d7b3a2010-08-24 06:29:42 +00001386StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001387Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001388 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001389 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001390 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001391 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001392 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001393 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1394 // declare identifiers for objects having storage class 'auto' or
1395 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001396 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1397 DI!=DE; ++DI) {
1398 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001399 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001400 VD = 0;
1401 if (VD == 0)
1402 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1403 // FIXME: mark decl erroneous!
1404 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001405 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001407
Richard Trieu694e7962012-04-30 18:01:30 +00001408 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1409
John McCall60d7b3a2010-08-24 06:29:42 +00001410 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001411 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001412 if (secondVar) {
1413 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001414 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001415 if (SecondResult.isInvalid())
1416 return StmtError();
1417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001419 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420
Anders Carlsson3af708f2009-08-01 01:39:59 +00001421 DiagnoseUnusedExprResult(First);
1422 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001423 DiagnoseUnusedExprResult(Body);
1424
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001425 if (isa<NullStmt>(Body))
1426 getCurCompoundScope().setHasEmptyLoopBodies();
1427
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428 return Owned(new (Context) ForStmt(Context, First,
1429 SecondResult.take(), ConditionVar,
1430 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001431 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001432}
1433
John McCallf6a16482010-12-04 03:47:34 +00001434/// In an Objective C collection iteration statement:
1435/// for (x in y)
1436/// x can be an arbitrary l-value expression. Bind it up as a
1437/// full-expression.
1438StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001439 // Reduce placeholder expressions here. Note that this rejects the
1440 // use of pseudo-object l-values in this position.
1441 ExprResult result = CheckPlaceholderExpr(E);
1442 if (result.isInvalid()) return StmtError();
1443 E = result.take();
1444
John McCallf6a16482010-12-04 03:47:34 +00001445 CheckImplicitConversions(E);
John McCall29bbd1a2012-03-30 05:43:39 +00001446
1447 result = MaybeCreateExprWithCleanups(E);
1448 if (result.isInvalid()) return StmtError();
1449
1450 return Owned(static_cast<Stmt*>(result.take()));
John McCallf6a16482010-12-04 03:47:34 +00001451}
1452
John McCall990567c2011-07-27 01:07:15 +00001453ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001454Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1455 if (!collection)
1456 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001457
John McCall990567c2011-07-27 01:07:15 +00001458 // Bail out early if we've got a type-dependent expression.
1459 if (collection->isTypeDependent()) return Owned(collection);
1460
1461 // Perform normal l-value conversion.
1462 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1463 if (result.isInvalid())
1464 return ExprError();
1465 collection = result.take();
1466
1467 // The operand needs to have object-pointer type.
1468 // TODO: should we do a contextual conversion?
1469 const ObjCObjectPointerType *pointerType =
1470 collection->getType()->getAs<ObjCObjectPointerType>();
1471 if (!pointerType)
1472 return Diag(forLoc, diag::err_collection_expr_type)
1473 << collection->getType() << collection->getSourceRange();
1474
1475 // Check that the operand provides
1476 // - countByEnumeratingWithState:objects:count:
1477 const ObjCObjectType *objectType = pointerType->getObjectType();
1478 ObjCInterfaceDecl *iface = objectType->getInterface();
1479
1480 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001481 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001482 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001483 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001484 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001485 ? diag::err_arc_collection_forward
1486 : 0,
1487 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001488 // Otherwise, if we have any useful type information, check that
1489 // the type declares the appropriate method.
1490 } else if (iface || !objectType->qual_empty()) {
1491 IdentifierInfo *selectorIdents[] = {
1492 &Context.Idents.get("countByEnumeratingWithState"),
1493 &Context.Idents.get("objects"),
1494 &Context.Idents.get("count")
1495 };
1496 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1497
1498 ObjCMethodDecl *method = 0;
1499
1500 // If there's an interface, look in both the public and private APIs.
1501 if (iface) {
1502 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001503 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001504 }
1505
1506 // Also check protocol qualifiers.
1507 if (!method)
1508 method = LookupMethodInQualifiedType(selector, pointerType,
1509 /*instance*/ true);
1510
1511 // If we didn't find it anywhere, give up.
1512 if (!method) {
1513 Diag(forLoc, diag::warn_collection_expr_type)
1514 << collection->getType() << selector << collection->getSourceRange();
1515 }
1516
1517 // TODO: check for an incompatible signature?
1518 }
1519
1520 // Wrap up any cleanups in the expression.
1521 return Owned(MaybeCreateExprWithCleanups(collection));
1522}
1523
John McCall60d7b3a2010-08-24 06:29:42 +00001524StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001525Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001526 Stmt *First, Expr *collection,
1527 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001528
1529 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001530 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001531
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001532 if (First) {
1533 QualType FirstType;
1534 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001535 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001536 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1537 diag::err_toomany_element_decls));
1538
John McCallf85e1932011-06-15 23:02:42 +00001539 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1540 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001541 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1542 // declare identifiers for objects having storage class 'auto' or
1543 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001544 if (!D->hasLocalStorage())
1545 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001546 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001547 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001548 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001549 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001550 return StmtError(Diag(First->getLocStart(),
1551 diag::err_selector_element_not_lvalue)
1552 << First->getSourceRange());
1553
Mike Stump1eb44332009-09-09 15:08:12 +00001554 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001555 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001556 if (!FirstType->isDependentType() &&
1557 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001558 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001559 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1560 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001561 }
Chad Rosier1093f492012-08-10 17:56:09 +00001562
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001563 if (CollectionExprResult.isInvalid())
1564 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001565
1566 return Owned(new (Context) ObjCForCollectionStmt(First,
1567 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001568 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001569}
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
Richard Smithad762fc2011-04-14 22:09:26 +00001571/// Finish building a variable declaration for a for-range statement.
1572/// \return true if an error occurs.
1573static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1574 SourceLocation Loc, int diag) {
1575 // Deduce the type for the iterator variable now rather than leaving it to
1576 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1577 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001578 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001579 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1580 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001581 SemaRef.Diag(Loc, diag) << Init->getType();
1582 if (!InitTSI) {
1583 Decl->setInvalidDecl();
1584 return true;
1585 }
1586 Decl->setTypeSourceInfo(InitTSI);
1587 Decl->setType(InitTSI->getType());
1588
John McCallf85e1932011-06-15 23:02:42 +00001589 // In ARC, infer lifetime.
1590 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1591 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001592 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001593 SemaRef.inferObjCARCLifetime(Decl))
1594 Decl->setInvalidDecl();
1595
Richard Smithad762fc2011-04-14 22:09:26 +00001596 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1597 /*TypeMayContainAuto=*/false);
1598 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001599 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001600 return false;
1601}
1602
Sam Panzere1715b62012-08-21 00:52:01 +00001603namespace {
1604
Richard Smithad762fc2011-04-14 22:09:26 +00001605/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001606/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001607/// nor from the diagnostics produced when analysing the implicit expressions
1608/// required in a for-range statement.
1609void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001610 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001611 CallExpr *CE = dyn_cast<CallExpr>(E);
1612 if (!CE)
1613 return;
1614 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1615 if (!D)
1616 return;
1617 SourceLocation Loc = D->getLocation();
1618
1619 std::string Description;
1620 bool IsTemplate = false;
1621 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1622 Description = SemaRef.getTemplateArgumentBindingsText(
1623 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1624 IsTemplate = true;
1625 }
1626
1627 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1628 << BEF << IsTemplate << Description << E->getType();
1629}
1630
Sam Panzere1715b62012-08-21 00:52:01 +00001631/// Build a variable declaration for a for-range statement.
1632VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1633 QualType Type, const char *Name) {
1634 DeclContext *DC = SemaRef.CurContext;
1635 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1636 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1637 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1638 TInfo, SC_Auto, SC_None);
1639 Decl->setImplicit();
1640 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001641}
1642
1643}
1644
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001645static bool ObjCEnumerationCollection(Expr *Collection) {
1646 return !Collection->isTypeDependent()
1647 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1648}
1649
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001650/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001651///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001652/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001653/// A range-based for statement is equivalent to
1654///
1655/// {
1656/// auto && __range = range-init;
1657/// for ( auto __begin = begin-expr,
1658/// __end = end-expr;
1659/// __begin != __end;
1660/// ++__begin ) {
1661/// for-range-declaration = *__begin;
1662/// statement
1663/// }
1664/// }
1665///
1666/// The body of the loop is not available yet, since it cannot be analysed until
1667/// we have determined the type of the for-range-declaration.
1668StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001669Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001670 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001671 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001672 if (!First || !Range)
1673 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001674
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001675 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001676 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001677
1678 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1679 assert(DS && "first part of for range not a decl stmt");
1680
1681 if (!DS->isSingleDecl()) {
1682 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1683 return StmtError();
1684 }
1685 if (DS->getSingleDecl()->isInvalidDecl())
1686 return StmtError();
1687
1688 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1689 return StmtError();
1690
1691 // Build auto && __range = range-init
1692 SourceLocation RangeLoc = Range->getLocStart();
1693 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1694 Context.getAutoRRefDeductType(),
1695 "__range");
1696 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1697 diag::err_for_range_deduction_failure))
1698 return StmtError();
1699
1700 // Claim the type doesn't contain auto: we've already done the checking.
1701 DeclGroupPtrTy RangeGroup =
1702 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1703 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1704 if (RangeDecl.isInvalid())
1705 return StmtError();
1706
1707 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1708 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001709 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001710}
1711
1712/// \brief Create the initialization, compare, and increment steps for
1713/// the range-based for loop expression.
1714/// This function does not handle array-based for loops,
1715/// which are created in Sema::BuildCXXForRangeStmt.
1716///
1717/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1718/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1719/// CandidateSet and BEF are set and some non-success value is returned on
1720/// failure.
1721static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1722 Expr *BeginRange, Expr *EndRange,
1723 QualType RangeType,
1724 VarDecl *BeginVar,
1725 VarDecl *EndVar,
1726 SourceLocation ColonLoc,
1727 OverloadCandidateSet *CandidateSet,
1728 ExprResult *BeginExpr,
1729 ExprResult *EndExpr,
1730 Sema::BeginEndFunction *BEF) {
1731 DeclarationNameInfo BeginNameInfo(
1732 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1733 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1734 ColonLoc);
1735
1736 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1737 Sema::LookupMemberName);
1738 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1739
1740 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1741 // - if _RangeT is a class type, the unqualified-ids begin and end are
1742 // looked up in the scope of class _RangeT as if by class member access
1743 // lookup (3.4.5), and if either (or both) finds at least one
1744 // declaration, begin-expr and end-expr are __range.begin() and
1745 // __range.end(), respectively;
1746 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1747 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1748
1749 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1750 SourceLocation RangeLoc = BeginVar->getLocation();
1751 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1752
1753 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1754 << RangeLoc << BeginRange->getType() << *BEF;
1755 return Sema::FRS_DiagnosticIssued;
1756 }
1757 } else {
1758 // - otherwise, begin-expr and end-expr are begin(__range) and
1759 // end(__range), respectively, where begin and end are looked up with
1760 // argument-dependent lookup (3.4.2). For the purposes of this name
1761 // lookup, namespace std is an associated namespace.
1762
1763 }
1764
1765 *BEF = Sema::BEF_begin;
1766 Sema::ForRangeStatus RangeStatus =
1767 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1768 Sema::BEF_begin, BeginNameInfo,
1769 BeginMemberLookup, CandidateSet,
1770 BeginRange, BeginExpr);
1771
1772 if (RangeStatus != Sema::FRS_Success)
1773 return RangeStatus;
1774 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1775 diag::err_for_range_iter_deduction_failure)) {
1776 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1777 return Sema::FRS_DiagnosticIssued;
1778 }
1779
1780 *BEF = Sema::BEF_end;
1781 RangeStatus =
1782 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1783 Sema::BEF_end, EndNameInfo,
1784 EndMemberLookup, CandidateSet,
1785 EndRange, EndExpr);
1786 if (RangeStatus != Sema::FRS_Success)
1787 return RangeStatus;
1788 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1789 diag::err_for_range_iter_deduction_failure)) {
1790 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1791 return Sema::FRS_DiagnosticIssued;
1792 }
1793 return Sema::FRS_Success;
1794}
1795
1796/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001797/// If the attempt fails, this function will return a valid, null StmtResult
1798/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001799static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1800 SourceLocation ForLoc,
1801 Stmt *LoopVarDecl,
1802 SourceLocation ColonLoc,
1803 Expr *Range,
1804 SourceLocation RangeLoc,
1805 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001806 // Determine whether we can rebuild the for-range statement with a
1807 // dereferenced range expression.
1808 ExprResult AdjustedRange;
1809 {
1810 Sema::SFINAETrap Trap(SemaRef);
1811
1812 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1813 if (AdjustedRange.isInvalid())
1814 return StmtResult();
1815
1816 StmtResult SR =
1817 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1818 AdjustedRange.get(), RParenLoc,
1819 Sema::BFRK_Check);
1820 if (SR.isInvalid())
1821 return StmtResult();
1822 }
1823
1824 // The attempt to dereference worked well enough that it could produce a valid
1825 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1826 // case there are any other (non-fatal) problems with it.
1827 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1828 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1829 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1830 AdjustedRange.get(), RParenLoc,
1831 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001832}
1833
Richard Smith8b533d92012-09-20 21:52:32 +00001834/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001835StmtResult
1836Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1837 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1838 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001839 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001840 Scope *S = getCurScope();
1841
1842 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1843 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1844 QualType RangeVarType = RangeVar->getType();
1845
1846 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1847 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1848
1849 StmtResult BeginEndDecl = BeginEnd;
1850 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1851
1852 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1853 SourceLocation RangeLoc = RangeVar->getLocation();
1854
Ted Kremeneke50b0152011-10-10 22:36:28 +00001855 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1856
1857 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1858 VK_LValue, ColonLoc);
1859 if (BeginRangeRef.isInvalid())
1860 return StmtError();
1861
1862 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1863 VK_LValue, ColonLoc);
1864 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001865 return StmtError();
1866
1867 QualType AutoType = Context.getAutoDeductType();
1868 Expr *Range = RangeVar->getInit();
1869 if (!Range)
1870 return StmtError();
1871 QualType RangeType = Range->getType();
1872
1873 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001874 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001875 return StmtError();
1876
1877 // Build auto __begin = begin-expr, __end = end-expr.
1878 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1879 "__begin");
1880 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1881 "__end");
1882
1883 // Build begin-expr and end-expr and attach to __begin and __end variables.
1884 ExprResult BeginExpr, EndExpr;
1885 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1886 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1887 // __range + __bound, respectively, where __bound is the array bound. If
1888 // _RangeT is an array of unknown size or an array of incomplete type,
1889 // the program is ill-formed;
1890
1891 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001892 BeginExpr = BeginRangeRef;
1893 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001894 diag::err_for_range_iter_deduction_failure)) {
1895 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1896 return StmtError();
1897 }
1898
1899 // Find the array bound.
1900 ExprResult BoundExpr;
1901 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1902 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001903 Context.getPointerDiffType(),
1904 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001905 else if (const VariableArrayType *VAT =
1906 dyn_cast<VariableArrayType>(UnqAT))
1907 BoundExpr = VAT->getSizeExpr();
1908 else {
1909 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1910 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001911 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001912 }
1913
1914 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001915 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001916 BoundExpr.get());
1917 if (EndExpr.isInvalid())
1918 return StmtError();
1919 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1920 diag::err_for_range_iter_deduction_failure)) {
1921 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1922 return StmtError();
1923 }
1924 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001925 OverloadCandidateSet CandidateSet(RangeLoc);
1926 Sema::BeginEndFunction BEFFailure;
1927 ForRangeStatus RangeStatus =
1928 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1929 EndRangeRef.get(), RangeType,
1930 BeginVar, EndVar, ColonLoc, &CandidateSet,
1931 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001932
Sam Panzere1715b62012-08-21 00:52:01 +00001933 // If building the range failed, try dereferencing the range expression
1934 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001935 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001936 BEFFailure == BEF_begin) {
1937 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1938 LoopVarDecl, ColonLoc,
1939 Range, RangeLoc,
1940 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001941 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001942 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001943 }
1944
Sam Panzere1715b62012-08-21 00:52:01 +00001945 // Otherwise, emit diagnostics if we haven't already.
1946 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001947 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001948 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1949 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001951 }
1952 // Return an error if no fix was discovered.
1953 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001954 return StmtError();
1955 }
1956
Sam Panzere1715b62012-08-21 00:52:01 +00001957 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1958 "invalid range expression in for loop");
1959
1960 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001961 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1962 if (!Context.hasSameType(BeginType, EndType)) {
1963 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1964 << BeginType << EndType;
1965 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1966 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1967 }
1968
1969 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1970 // Claim the type doesn't contain auto: we've already done the checking.
1971 DeclGroupPtrTy BeginEndGroup =
1972 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1973 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1974
Ted Kremeneke50b0152011-10-10 22:36:28 +00001975 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1976 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001977 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001978 if (BeginRef.isInvalid())
1979 return StmtError();
1980
Richard Smithad762fc2011-04-14 22:09:26 +00001981 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1982 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001983 if (EndRef.isInvalid())
1984 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001985
1986 // Build and check __begin != __end expression.
1987 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1988 BeginRef.get(), EndRef.get());
1989 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1990 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1991 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00001992 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
1993 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00001994 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1995 if (!Context.hasSameType(BeginType, EndType))
1996 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1997 return StmtError();
1998 }
1999
2000 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002001 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2002 VK_LValue, ColonLoc);
2003 if (BeginRef.isInvalid())
2004 return StmtError();
2005
Richard Smithad762fc2011-04-14 22:09:26 +00002006 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2007 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2008 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002009 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2010 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002011 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2012 return StmtError();
2013 }
2014
2015 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002016 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2017 VK_LValue, ColonLoc);
2018 if (BeginRef.isInvalid())
2019 return StmtError();
2020
Richard Smithad762fc2011-04-14 22:09:26 +00002021 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2022 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002023 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2024 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002025 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2026 return StmtError();
2027 }
2028
Richard Smith8b533d92012-09-20 21:52:32 +00002029 // Attach *__begin as initializer for VD. Don't touch it if we're just
2030 // trying to determine whether this would be a valid range.
2031 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002032 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2033 /*TypeMayContainAuto=*/true);
2034 if (LoopVar->isInvalidDecl())
2035 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2036 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002037 } else {
2038 // The range is implicitly used as a placeholder when it is dependent.
2039 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002040 }
2041
Richard Smith8b533d92012-09-20 21:52:32 +00002042 // Don't bother to actually allocate the result if we're just trying to
2043 // determine whether it would be valid.
2044 if (Kind == BFRK_Check)
2045 return StmtResult();
2046
Richard Smithad762fc2011-04-14 22:09:26 +00002047 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2048 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2049 NotEqExpr.take(), IncrExpr.take(),
2050 LoopVarDS, /*Body=*/0, ForLoc,
2051 ColonLoc, RParenLoc));
2052}
2053
Chad Rosier1093f492012-08-10 17:56:09 +00002054/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002055/// statement.
2056StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2057 if (!S || !B)
2058 return StmtError();
2059 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002060
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002061 ForStmt->setBody(B);
2062 return S;
2063}
2064
Richard Smithad762fc2011-04-14 22:09:26 +00002065/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2066/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2067/// body cannot be performed until after the type of the range variable is
2068/// determined.
2069StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2070 if (!S || !B)
2071 return StmtError();
2072
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002073 if (isa<ObjCForCollectionStmt>(S))
2074 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002075
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002076 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2077 ForStmt->setBody(B);
2078
2079 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2080 diag::warn_empty_range_based_for_body);
2081
Richard Smithad762fc2011-04-14 22:09:26 +00002082 return S;
2083}
2084
Chris Lattner57ad3782011-02-17 20:34:02 +00002085StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2086 SourceLocation LabelLoc,
2087 LabelDecl *TheDecl) {
2088 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002089 TheDecl->setUsed();
2090 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002091}
2092
John McCall60d7b3a2010-08-24 06:29:42 +00002093StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002094Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002095 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002096 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002097 if (!E->isTypeDependent()) {
2098 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002099 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002100 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002101 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002102 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2103 if (ExprRes.isInvalid())
2104 return StmtError();
2105 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002106 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002107 return StmtError();
Eli Friedmand29975f2012-01-31 22:47:07 +00002108 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002109 }
John McCallb60a77e2010-08-01 00:26:45 +00002110
John McCall781472f2010-08-25 08:40:02 +00002111 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002112
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002113 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002114}
2115
John McCall60d7b3a2010-08-24 06:29:42 +00002116StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002117Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 Scope *S = CurScope->getContinueParent();
2119 if (!S) {
2120 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002121 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002123
Ted Kremenek8189cde2009-02-07 01:47:29 +00002124 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002125}
2126
John McCall60d7b3a2010-08-24 06:29:42 +00002127StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002128Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 Scope *S = CurScope->getBreakParent();
2130 if (!S) {
2131 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002132 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002134
Ted Kremenek8189cde2009-02-07 01:47:29 +00002135 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002136}
2137
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002139/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002140///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002141/// \param ReturnType If we're determining the copy elision candidate for
2142/// a return statement, this is the return type of the function. If we're
2143/// determining the copy elision candidate for a throw expression, this will
2144/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002145///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002146/// \param E The expression being returned from the function or block, or
2147/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002148///
Douglas Gregor4926d832011-05-20 15:00:53 +00002149/// \param AllowFunctionParameter Whether we allow function parameters to
2150/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2151/// we re-use this logic to determine whether we should try to move as part of
2152/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002153///
2154/// \returns The NRVO candidate variable, if the return statement may use the
2155/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002156const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2157 Expr *E,
2158 bool AllowFunctionParameter) {
2159 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002160 // - in a return statement in a function with ...
2161 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002162 if (!ReturnType.isNull()) {
2163 if (!ReturnType->isRecordType())
2164 return 0;
2165 // ... the same cv-unqualified type as the function return type ...
2166 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2167 return 0;
2168 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002169
2170 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002171 // (other than a function or catch-clause parameter)) ...
2172 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002173 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002174 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002175 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2176 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002177 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002178
John McCall1cd76e82011-11-11 03:57:31 +00002179 // ...object (other than a function or catch-clause parameter)...
2180 if (VD->getKind() != Decl::Var &&
2181 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2182 return 0;
2183 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002184
John McCall1cd76e82011-11-11 03:57:31 +00002185 // ...automatic...
2186 if (!VD->hasLocalStorage()) return 0;
2187
2188 // ...non-volatile...
2189 if (VD->getType().isVolatileQualified()) return 0;
2190 if (VD->getType()->isReferenceType()) return 0;
2191
2192 // __block variables can't be allocated in a way that permits NRVO.
2193 if (VD->hasAttr<BlocksAttr>()) return 0;
2194
2195 // Variables with higher required alignment than their type's ABI
2196 // alignment cannot use NRVO.
2197 if (VD->hasAttr<AlignedAttr>() &&
2198 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2199 return 0;
2200
2201 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002202}
2203
Douglas Gregor07f402c2011-01-21 21:08:57 +00002204/// \brief Perform the initialization of a potentially-movable value, which
2205/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002206///
2207/// This routine implements C++0x [class.copy]p33, which attempts to treat
2208/// returned lvalues as rvalues in certain cases (to prefer move construction),
2209/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002210ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002211Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2212 const VarDecl *NRVOCandidate,
2213 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002214 Expr *Value,
2215 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002216 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002217 // When the criteria for elision of a copy operation are met or would
2218 // be met save for the fact that the source object is a function
2219 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002220 // overload resolution to select the constructor for the copy is first
2221 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002222 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002223 if (AllowNRVO &&
2224 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002225 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002226 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002227
Douglas Gregorcc15f012011-01-21 19:38:21 +00002228 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002229 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002230 = InitializationKind::CreateCopy(Value->getLocStart(),
2231 Value->getLocStart());
2232 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002233
2234 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002235 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002236 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002237 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002238 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002239 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2240 StepEnd = Seq.step_end();
2241 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002242 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002243 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
2245 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002246 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002247
Douglas Gregorcc15f012011-01-21 19:38:21 +00002248 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002249 = Constructor->getParamDecl(0)->getType()
2250 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002251
Douglas Gregorcc15f012011-01-21 19:38:21 +00002252 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002253 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002254 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2255 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002256 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
Douglas Gregorcc15f012011-01-21 19:38:21 +00002258 // Promote "AsRvalue" to the heap, since we now need this
2259 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002260 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002261 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002262
Douglas Gregorcc15f012011-01-21 19:38:21 +00002263 // Complete type-checking the initialization of the return type
2264 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002265 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002266 }
2267 }
2268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002269
Douglas Gregorcc15f012011-01-21 19:38:21 +00002270 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002271 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002272 // (again) now with the return value expression as written.
2273 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002274 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002275
Douglas Gregorcc15f012011-01-21 19:38:21 +00002276 return Res;
2277}
2278
Eli Friedman84b007f2012-01-26 03:00:14 +00002279/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2280/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002281///
John McCall60d7b3a2010-08-24 06:29:42 +00002282StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002283Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2284 // If this is the first return we've seen, infer the return type.
2285 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2286 // rules which allows multiple return statements.
2287 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002288 QualType FnRetType = CurCap->ReturnType;
2289
2290 // For blocks/lambdas with implicit return types, we check each return
2291 // statement individually, and deduce the common return type when the block
2292 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002293 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002294 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002295 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2296 if (Result.isInvalid())
2297 return StmtError();
2298 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002299
Jordan Rose7dd900e2012-07-02 21:19:23 +00002300 if (!RetValExp->isTypeDependent())
2301 FnRetType = RetValExp->getType();
2302 else
2303 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002304 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002305 if (RetValExp) {
2306 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2307 // initializer list, because it is not an expression (even
2308 // though we represent it as one). We still deduce 'void'.
2309 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2310 << RetValExp->getSourceRange();
2311 }
2312
Jordan Rose7dd900e2012-07-02 21:19:23 +00002313 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002314 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002315
2316 // Although we'll properly infer the type of the block once it's completed,
2317 // make sure we provide a return type now for better error recovery.
2318 if (CurCap->ReturnType.isNull())
2319 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002320 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002321 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002322
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002323 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002324 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2325 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2326 return StmtError();
2327 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002328 } else {
2329 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2330 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2331 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2332 return StmtError();
2333 }
2334 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002335
Steve Naroff4eb206b2008-09-03 18:15:37 +00002336 // Otherwise, verify that this result type matches the previous one. We are
2337 // pickier with blocks than for normal functions because we don't have GCC
2338 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002339 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002340 if (FnRetType->isDependentType()) {
2341 // Delay processing for now. TODO: there are lots of dependent
2342 // types we can conclusively prove aren't void.
2343 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002344 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002345 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002346 (RetValExp->isTypeDependent() ||
2347 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002348 if (!getLangOpts().CPlusPlus &&
2349 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002350 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002351 else {
2352 Diag(ReturnLoc, diag::err_return_block_has_expr);
2353 RetValExp = 0;
2354 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002355 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002356 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002357 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2358 } else if (!RetValExp->isTypeDependent()) {
2359 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002360
John McCall0a7efe12011-08-17 22:09:46 +00002361 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2362 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2363 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002364
John McCall0a7efe12011-08-17 22:09:46 +00002365 // In C++ the return statement is handled via a copy initialization.
2366 // the C version of which boils down to CheckSingleAssignmentConstraints.
2367 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2368 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2369 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002370 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002371 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2372 FnRetType, RetValExp);
2373 if (Res.isInvalid()) {
2374 // FIXME: Cleanup temporaries here, anyway?
2375 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002376 }
John McCall0a7efe12011-08-17 22:09:46 +00002377 RetValExp = Res.take();
2378 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002379 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002380
John McCalld963c372011-08-17 21:34:14 +00002381 if (RetValExp) {
2382 CheckImplicitConversions(RetValExp, ReturnLoc);
2383 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2384 }
John McCall0a7efe12011-08-17 22:09:46 +00002385 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2386 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002387
Jordan Rose7dd900e2012-07-02 21:19:23 +00002388 // If we need to check for the named return value optimization,
2389 // or if we need to infer the return type,
2390 // save the return statement in our scope for later processing.
2391 if (CurCap->HasImplicitReturnType ||
2392 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2393 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002394 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002395
Douglas Gregor5077c382010-05-15 06:01:05 +00002396 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002397}
Reid Spencer5f016e22007-07-11 17:01:13 +00002398
John McCall60d7b3a2010-08-24 06:29:42 +00002399StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002400Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002401 // Check for unexpanded parameter packs.
2402 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2403 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002404
Eli Friedman84b007f2012-01-26 03:00:14 +00002405 if (isa<CapturingScopeInfo>(getCurFunction()))
2406 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002407
Chris Lattner371f2582008-12-04 23:50:19 +00002408 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002409 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002410 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002411 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002412 if (FD->hasAttr<NoReturnAttr>() ||
2413 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002414 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002415 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002416 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002417 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002418 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2419 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002420 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002421 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002422 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2423 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002424 }
2425 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002426 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregor5077c382010-05-15 06:01:05 +00002428 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002429 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002430 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002431 if (isa<InitListExpr>(RetValExp)) {
2432 // We simply never allow init lists as the return value of void
2433 // functions. This is compatible because this was never allowed before,
2434 // so there's no legacy code to deal with.
2435 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2436 int FunctionKind = 0;
2437 if (isa<ObjCMethodDecl>(CurDecl))
2438 FunctionKind = 1;
2439 else if (isa<CXXConstructorDecl>(CurDecl))
2440 FunctionKind = 2;
2441 else if (isa<CXXDestructorDecl>(CurDecl))
2442 FunctionKind = 3;
2443
2444 Diag(ReturnLoc, diag::err_return_init_list)
2445 << CurDecl->getDeclName() << FunctionKind
2446 << RetValExp->getSourceRange();
2447
2448 // Drop the expression.
2449 RetValExp = 0;
2450 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002451 // C99 6.8.6.4p1 (ext_ since GCC warns)
2452 unsigned D = diag::ext_return_has_expr;
2453 if (RetValExp->getType()->isVoidType())
2454 D = diag::ext_return_has_void_expr;
2455 else {
2456 ExprResult Result = Owned(RetValExp);
2457 Result = IgnoredValueConversions(Result.take());
2458 if (Result.isInvalid())
2459 return StmtError();
2460 RetValExp = Result.take();
2461 RetValExp = ImpCastExprToType(RetValExp,
2462 Context.VoidTy, CK_ToVoid).take();
2463 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002464
Nick Lewycky8d794612011-06-01 07:44:31 +00002465 // return (some void expression); is legal in C++.
2466 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002467 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002468 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002469
2470 int FunctionKind = 0;
2471 if (isa<ObjCMethodDecl>(CurDecl))
2472 FunctionKind = 1;
2473 else if (isa<CXXConstructorDecl>(CurDecl))
2474 FunctionKind = 2;
2475 else if (isa<CXXDestructorDecl>(CurDecl))
2476 FunctionKind = 3;
2477
Nick Lewycky8d794612011-06-01 07:44:31 +00002478 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002479 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002480 << RetValExp->getSourceRange();
2481 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002482 }
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Sebastian Redl33deb352012-02-22 10:50:08 +00002484 if (RetValExp) {
2485 CheckImplicitConversions(RetValExp, ReturnLoc);
2486 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2487 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002489
Douglas Gregor5077c382010-05-15 06:01:05 +00002490 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2491 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002492 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2493 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002494 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002495
2496 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002497 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002498 else
Chris Lattner08631c52008-11-23 21:45:46 +00002499 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002500 Result = new (Context) ReturnStmt(ReturnLoc);
2501 } else {
2502 const VarDecl *NRVOCandidate = 0;
2503 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2504 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002505
Eli Friedman38ac2432012-03-30 01:13:43 +00002506 if (!RelatedRetType.isNull()) {
2507 // If we have a related result type, perform an extra conversion here.
2508 // FIXME: The diagnostics here don't really describe what is happening.
2509 InitializedEntity Entity =
2510 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002511
Eli Friedman38ac2432012-03-30 01:13:43 +00002512 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2513 RetValExp);
2514 if (Res.isInvalid()) {
2515 // FIXME: Cleanup temporaries here, anyway?
2516 return StmtError();
2517 }
2518 RetValExp = Res.takeAs<Expr>();
2519 }
2520
Douglas Gregor5077c382010-05-15 06:01:05 +00002521 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2522 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2523 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002524
John McCall856d3792011-06-16 23:24:51 +00002525 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002526 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002527 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002528 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002529 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002530 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002531 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002532 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002533 if (Res.isInvalid()) {
2534 // FIXME: Cleanup temporaries here, anyway?
2535 return StmtError();
2536 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002537
Douglas Gregor5077c382010-05-15 06:01:05 +00002538 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002539 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002540 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002541 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002542
John McCallb4eb64d2010-10-08 02:01:28 +00002543 if (RetValExp) {
2544 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00002545 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00002546 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002547 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002549
2550 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002551 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002552 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002553 !CurContext->isDependentContext())
2554 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002555
Douglas Gregor5077c382010-05-15 06:01:05 +00002556 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002557}
2558
John McCall60d7b3a2010-08-24 06:29:42 +00002559StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002560Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002561 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002562 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002563 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002564 if (Var && Var->isInvalidDecl())
2565 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002566
John McCall9ae2f072010-08-23 23:25:46 +00002567 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002568}
2569
John McCall60d7b3a2010-08-24 06:29:42 +00002570StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002571Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2572 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002573}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002574
John McCall60d7b3a2010-08-24 06:29:42 +00002575StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002576Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002577 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002578 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002579 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2580
John McCall781472f2010-08-25 08:40:02 +00002581 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002582 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002583 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002584 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002585 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002586 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002587}
2588
John McCalld1376ee2012-05-08 21:41:25 +00002589StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002590 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002591 ExprResult Result = DefaultLvalueConversion(Throw);
2592 if (Result.isInvalid())
2593 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002594
John McCalld1376ee2012-05-08 21:41:25 +00002595 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregord1377b22010-04-22 21:44:01 +00002596 QualType ThrowType = Throw->getType();
2597 // Make sure the expression type is an ObjC pointer or "void *".
2598 if (!ThrowType->isDependentType() &&
2599 !ThrowType->isObjCObjectPointerType()) {
2600 const PointerType *PT = ThrowType->getAs<PointerType>();
2601 if (!PT || !PT->getPointeeType()->isVoidType())
2602 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2603 << Throw->getType() << Throw->getSourceRange());
2604 }
2605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002606
John McCall9ae2f072010-08-23 23:25:46 +00002607 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002608}
2609
John McCall60d7b3a2010-08-24 06:29:42 +00002610StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002611Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002612 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002613 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002614 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2615
John McCall9ae2f072010-08-23 23:25:46 +00002616 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002617 // @throw without an expression designates a rethrow (which much occur
2618 // in the context of an @catch clause).
2619 Scope *AtCatchParent = CurScope;
2620 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2621 AtCatchParent = AtCatchParent->getParent();
2622 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002623 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002624 }
John McCall9ae2f072010-08-23 23:25:46 +00002625 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002626}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002627
John McCall07524032011-07-27 21:50:02 +00002628ExprResult
2629Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2630 ExprResult result = DefaultLvalueConversion(operand);
2631 if (result.isInvalid())
2632 return ExprError();
2633 operand = result.take();
2634
2635 // Make sure the expression type is an ObjC pointer or "void *".
2636 QualType type = operand->getType();
2637 if (!type->isDependentType() &&
2638 !type->isObjCObjectPointerType()) {
2639 const PointerType *pointerType = type->getAs<PointerType>();
2640 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2641 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2642 << type << operand->getSourceRange();
2643 }
2644
2645 // The operand to @synchronized is a full-expression.
2646 return MaybeCreateExprWithCleanups(operand);
2647}
2648
John McCall60d7b3a2010-08-24 06:29:42 +00002649StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002650Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2651 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002652 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002653 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002654 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002655}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002656
2657/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2658/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002659StmtResult
John McCalld226f652010-08-21 09:40:31 +00002660Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002661 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002662 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002663 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002664 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002665 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002666}
Sebastian Redl8351da02008-12-22 21:35:02 +00002667
John McCallf85e1932011-06-15 23:02:42 +00002668StmtResult
2669Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2670 getCurFunction()->setHasBranchProtectedScope();
2671 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2672}
2673
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002674namespace {
2675
Sebastian Redlc447aba2009-07-29 17:15:45 +00002676class TypeWithHandler {
2677 QualType t;
2678 CXXCatchStmt *stmt;
2679public:
2680 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2681 : t(type), stmt(statement) {}
2682
John McCall0953e762009-09-24 19:53:00 +00002683 // An arbitrary order is fine as long as it places identical
2684 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002685 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002686 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002687 return true;
John McCall0953e762009-09-24 19:53:00 +00002688 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002689 return false;
2690 else
2691 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Sebastian Redlc447aba2009-07-29 17:15:45 +00002694 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002695 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002696 }
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Sebastian Redlc447aba2009-07-29 17:15:45 +00002698 CXXCatchStmt *getCatchStmt() const { return stmt; }
2699 SourceLocation getTypeSpecStartLoc() const {
2700 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2701 }
2702};
2703
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002704}
2705
Sebastian Redl8351da02008-12-22 21:35:02 +00002706/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2707/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002708StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002709Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002710 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002711 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002712 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002713 !getSourceManager().isInSystemHeader(TryLoc))
2714 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002715
Sebastian Redl8351da02008-12-22 21:35:02 +00002716 unsigned NumHandlers = RawHandlers.size();
2717 assert(NumHandlers > 0 &&
2718 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002719 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002720
Chris Lattner5f9e2722011-07-23 10:55:15 +00002721 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002722
2723 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002724 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002725 if (!Handler->getExceptionDecl()) {
2726 if (i < NumHandlers - 1)
2727 return StmtError(Diag(Handler->getLocStart(),
2728 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Sebastian Redlc447aba2009-07-29 17:15:45 +00002730 continue;
2731 }
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Sebastian Redlc447aba2009-07-29 17:15:45 +00002733 const QualType CaughtType = Handler->getCaughtType();
2734 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2735 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002736 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002737
2738 // Detect handlers for the same type as an earlier one.
2739 if (NumHandlers > 1) {
2740 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Sebastian Redlc447aba2009-07-29 17:15:45 +00002742 TypeWithHandler prev = TypesWithHandlers[0];
2743 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2744 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Sebastian Redlc447aba2009-07-29 17:15:45 +00002746 if (curr == prev) {
2747 Diag(curr.getTypeSpecStartLoc(),
2748 diag::warn_exception_caught_by_earlier_handler)
2749 << curr.getCatchStmt()->getCaughtType().getAsString();
2750 Diag(prev.getTypeSpecStartLoc(),
2751 diag::note_previous_exception_handler)
2752 << prev.getCatchStmt()->getCaughtType().getAsString();
2753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Sebastian Redlc447aba2009-07-29 17:15:45 +00002755 prev = curr;
2756 }
2757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
John McCall781472f2010-08-25 08:40:02 +00002759 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002760
Sebastian Redl8351da02008-12-22 21:35:02 +00002761 // FIXME: We should detect handlers that cannot catch anything because an
2762 // earlier handler catches a superclass. Need to find a method that is not
2763 // quadratic for this.
2764 // Neither of these are explicitly forbidden, but every compiler detects them
2765 // and warns.
2766
John McCall9ae2f072010-08-23 23:25:46 +00002767 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002768 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002769}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002770
2771StmtResult
2772Sema::ActOnSEHTryBlock(bool IsCXXTry,
2773 SourceLocation TryLoc,
2774 Stmt *TryBlock,
2775 Stmt *Handler) {
2776 assert(TryBlock && Handler);
2777
2778 getCurFunction()->setHasBranchProtectedScope();
2779
2780 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2781}
2782
2783StmtResult
2784Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2785 Expr *FilterExpr,
2786 Stmt *Block) {
2787 assert(FilterExpr && Block);
2788
2789 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002790 return StmtError(Diag(FilterExpr->getExprLoc(),
2791 diag::err_filter_expression_integral)
2792 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002793 }
2794
2795 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2796}
2797
2798StmtResult
2799Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2800 Stmt *Block) {
2801 assert(Block);
2802 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2803}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002804
2805StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2806 bool IsIfExists,
2807 NestedNameSpecifierLoc QualifierLoc,
2808 DeclarationNameInfo NameInfo,
2809 Stmt *Nested)
2810{
2811 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002812 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002813 cast<CompoundStmt>(Nested));
2814}
2815
2816
Chad Rosier1093f492012-08-10 17:56:09 +00002817StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002818 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002819 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002820 UnqualifiedId &Name,
2821 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002822 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002823 SS.getWithLocInContext(Context),
2824 GetNameFromUnqualifiedId(Name),
2825 Nested);
2826}