blob: 944fc40aadb18b92c67f80a7aed769a72d094dcf [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Richard Smithad762fc2011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
John McCall1cd76e82011-11-11 03:57:31 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000024#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
John McCall209acbd2010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000028#include "clang/Lex/Preprocessor.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000029#include "clang/Basic/TargetInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Chad Rosier47f49892012-08-09 20:47:38 +000035#include "llvm/ADT/Triple.h"
36#include "llvm/MC/MCAsmInfo.h"
37#include "llvm/MC/MCContext.h"
38#include "llvm/MC/MCObjectFileInfo.h"
39#include "llvm/MC/MCRegisterInfo.h"
40#include "llvm/MC/MCStreamer.h"
41#include "llvm/MC/MCSubtargetInfo.h"
42#include "llvm/MC/MCTargetAsmParser.h"
43#include "llvm/MC/MCParser/MCAsmParser.h"
44#include "llvm/Support/SourceMgr.h"
45#include "llvm/Support/TargetRegistry.h"
Chad Rosierbe3d0db2012-08-09 17:33:11 +000046#include "llvm/Support/TargetSelect.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000048using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000049
John McCall60d7b3a2010-08-24 06:29:42 +000050StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000051 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000052 if (!E) // FIXME: FullExprArg has no error state?
53 return StmtError();
54
Chris Lattner834a72a2008-07-25 23:18:17 +000055 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
56 // void expression for its side effects. Conversion to void allows any
57 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000058
Chris Lattner834a72a2008-07-25 23:18:17 +000059 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000060 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000061}
62
63
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000064StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000065 bool HasLeadingEmptyMacro) {
66 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000067}
68
Chris Lattner337e5502011-02-18 01:27:55 +000069StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
70 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000071 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner20401692009-04-12 20:13:14 +000073 // If we have an invalid decl, just return an error.
74 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner24e1e702009-03-04 04:23:07 +000076 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000077}
78
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000079void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
80 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000081
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000082 // If we have an invalid decl, just return.
83 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000084 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
85
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000086 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000087 var->setUsed();
88
John McCall7acddac2011-06-17 06:42:21 +000089 // foreach variables are never actually initialized in the way that
90 // the parser came up with.
91 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000092
John McCall7acddac2011-06-17 06:42:21 +000093 // In ARC, we don't need to retain the iteration variable of a fast
94 // enumeration loop. Rather than actually trying to catch that
95 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000096 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000097 QualType type = var->getType();
98
99 // Only do this if we inferred the lifetime. Inferred lifetime
100 // will show up as a local qualifier because explicit lifetime
101 // should have shown up as an AttributedType instead.
102 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
103 // Add 'const' and mark the variable as pseudo-strong.
104 var->setType(type.withConst());
105 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +0000106 }
107 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +0000108}
109
Chandler Carruthec8058f2011-08-17 09:34:37 +0000110/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000111///
112/// Adding a cast to void (or other expression wrappers) will prevent the
113/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000114static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000115 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000116 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000117
118 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
119 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000120 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000121
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000123 IsNotEqual = Op->getOpcode() == BO_NE;
124 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000125 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
126 if (Op->getOperator() != OO_EqualEqual &&
127 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000128 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000129
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000130 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000131 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
132 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000133 } else {
134 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000135 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000136 }
137
138 // Suppress warnings when the operator, suspicious as it may be, comes from
139 // a macro expansion.
140 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000141 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000142
Chandler Carruthec8058f2011-08-17 09:34:37 +0000143 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000144 << (unsigned)IsNotEqual << E->getSourceRange();
145
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000146 // If the LHS is a plausible entity to assign to, provide a fixit hint to
147 // correct common typos.
148 if (CanAssign) {
149 if (IsNotEqual)
150 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
151 << FixItHint::CreateReplacement(Loc, "|=");
152 else
153 S.Diag(Loc, diag::note_equality_comparison_to_assign)
154 << FixItHint::CreateReplacement(Loc, "=");
155 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000156
157 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000158}
159
Anders Carlsson636463e2009-07-30 22:17:18 +0000160void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000161 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
162 return DiagnoseUnusedExprResult(Label->getSubStmt());
163
Anders Carlsson75443112009-07-30 22:39:03 +0000164 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000165 if (!E)
166 return;
167
Eli Friedmana6115062012-05-24 00:47:05 +0000168 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000169 SourceLocation Loc;
170 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000171 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000172 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000173 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattner419cfb32009-08-16 16:57:27 +0000175 // Okay, we have an unused result. Depending on what the base expression is,
176 // we might want to make a more specific diagnostic. Check for one of these
177 // cases now.
178 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000179 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000180 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000181 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
182 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000183
Chandler Carruthec8058f2011-08-17 09:34:37 +0000184 if (DiagnoseUnusedComparison(*this, E))
185 return;
186
Eli Friedmana6115062012-05-24 00:47:05 +0000187 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000188 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000189 if (E->getType()->isVoidType())
190 return;
191
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000192 // If the callee has attribute pure, const, or warn_unused_result, warn with
193 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000194 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000195 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000196 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000197 return;
198 }
199 if (FD->getAttr<PureAttr>()) {
200 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
201 return;
202 }
203 if (FD->getAttr<ConstAttr>()) {
204 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
205 return;
206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000207 }
John McCall12f78a62010-12-02 01:19:52 +0000208 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000209 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000210 Diag(Loc, diag::err_arc_unused_init_message) << R1;
211 return;
212 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000213 const ObjCMethodDecl *MD = ME->getMethodDecl();
214 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000215 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000216 return;
217 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000218 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
219 const Expr *Source = POE->getSyntacticForm();
220 if (isa<ObjCSubscriptRefExpr>(Source))
221 DiagID = diag::warn_unused_container_subscript_expr;
222 else
223 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000224 } else if (const CXXFunctionalCastExpr *FC
225 = dyn_cast<CXXFunctionalCastExpr>(E)) {
226 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
227 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
228 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000229 }
John McCall209acbd2010-04-06 22:24:14 +0000230 // Diagnose "(void*) blah" as a typo for "(void) blah".
231 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
232 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
233 QualType T = TI->getType();
234
235 // We really do want to use the non-canonical type here.
236 if (T == Context.VoidPtrTy) {
237 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
238
239 Diag(Loc, diag::warn_unused_voidptr)
240 << FixItHint::CreateRemoval(TL.getStarLoc());
241 return;
242 }
243 }
244
Eli Friedmana6115062012-05-24 00:47:05 +0000245 if (E->isGLValue() && E->getType().isVolatileQualified()) {
246 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
247 return;
248 }
249
Ted Kremenek351ba912011-02-23 01:52:04 +0000250 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000251}
252
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000253void Sema::ActOnStartOfCompoundStmt() {
254 PushCompoundScope();
255}
256
257void Sema::ActOnFinishOfCompoundStmt() {
258 PopCompoundScope();
259}
260
261sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
262 return getCurFunction()->CompoundScopes.back();
263}
264
John McCall60d7b3a2010-08-24 06:29:42 +0000265StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000266Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000267 MultiStmtArg elts, bool isStmtExpr) {
268 unsigned NumElts = elts.size();
269 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000270 // If we're in C89 mode, check that we don't have any decls after stmts. If
271 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000272 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000273 // Note that __extension__ can be around a decl.
274 unsigned i = 0;
275 // Skip over all declarations.
276 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
277 /*empty*/;
278
279 // We found the end of the list or a statement. Scan for another declstmt.
280 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
281 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000283 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000284 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000285 Diag(D->getLocation(), diag::ext_mixed_decls_code);
286 }
287 }
Chris Lattner98414c12007-08-31 21:49:55 +0000288 // Warn about unused expressions in statements.
289 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000290 // Ignore statements that are last in a statement expression.
291 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000292 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Anders Carlsson636463e2009-07-30 22:17:18 +0000294 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000295 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000296
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000297 // Check for suspicious empty body (null statement) in `for' and `while'
298 // statements. Don't do anything for template instantiations, this just adds
299 // noise.
300 if (NumElts != 0 && !CurrentInstantiationScope &&
301 getCurCompoundScope().HasEmptyLoopBodies) {
302 for (unsigned i = 0; i != NumElts - 1; ++i)
303 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
304 }
305
Ted Kremenek8189cde2009-02-07 01:47:29 +0000306 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000307}
308
John McCall60d7b3a2010-08-24 06:29:42 +0000309StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000310Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
311 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000312 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000313 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000314
John McCall781472f2010-08-25 08:40:02 +0000315 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000316 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000317 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000318 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000319
David Blaikie4e4d0842012-03-11 07:00:24 +0000320 if (!getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000321 // C99 6.8.4.2p3: The expression shall be an integer constant.
322 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000323 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
324 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
325 if (!LHSVal)
326 return StmtError();
327 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000328
329 // GCC extension: The expression shall be an integer constant.
330
Richard Smith282e7e62012-02-04 09:53:13 +0000331 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
332 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
333 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000334 }
335 }
336
Douglas Gregordbb26db2009-05-15 23:57:33 +0000337 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
338 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000339 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000340 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000341}
342
Chris Lattner24e1e702009-03-04 04:23:07 +0000343/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000344void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000345 DiagnoseUnusedExprResult(SubStmt);
346
Chris Lattner24e1e702009-03-04 04:23:07 +0000347 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000348 CS->setSubStmt(SubStmt);
349}
350
John McCall60d7b3a2010-08-24 06:29:42 +0000351StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000352Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000353 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000354 DiagnoseUnusedExprResult(SubStmt);
355
John McCall781472f2010-08-25 08:40:02 +0000356 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000357 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000358 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000359 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000360
Douglas Gregordbb26db2009-05-15 23:57:33 +0000361 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000362 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000363 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
John McCall60d7b3a2010-08-24 06:29:42 +0000366StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000367Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
368 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000369 // If the label was multiply defined, reject it now.
370 if (TheDecl->getStmt()) {
371 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
372 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000373 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 }
Sebastian Redlde307472009-01-11 00:38:46 +0000375
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000376 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000377 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
378 TheDecl->setStmt(LS);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000379 if (!TheDecl->isGnuLocal())
380 TheDecl->setLocation(IdentLoc);
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);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000671 bool CondIsSigned
672 = 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
David Blaikie4e4d0842012-03-11 07:00:24 +0000716 if (getLangOpts().CPlusPlus0x) {
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.
729 LoVal = Lo->EvaluateKnownConstInt(Context);
730
731 // If the LHS is not the same type as the condition, insert an implicit
732 // cast.
733 Lo = DefaultLvalueConversion(Lo).take();
734 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
735 }
736
737 // Convert the value to the same width/sign as the condition had prior to
738 // integral promotions.
739 //
740 // FIXME: This causes us to reject valid code:
741 // switch ((char)c) { case 256: case 0: return 0; }
742 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000743 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000744 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000745 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000746
Chris Lattner1e0a3902008-01-16 19:17:22 +0000747 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000749 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000750 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000751 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000752 CS->getRHS()->isValueDependent()) {
753 HasDependentValue = true;
754 break;
755 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000756 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000757 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000758 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000759 }
760 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000761
762 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000763 // If we don't have a default statement, check whether the
764 // condition is constant.
765 llvm::APSInt ConstantCondValue;
766 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000767 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000768 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000769 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
770 Expr::SE_AllowSideEffects);
771 assert(!HasConstantCond ||
772 (ConstantCondValue.getBitWidth() == CondWidth &&
773 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000774 }
Richard Smith80d4b552011-12-28 19:48:30 +0000775 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000776
Douglas Gregordbb26db2009-05-15 23:57:33 +0000777 // Sort all the scalar case values so we can easily detect duplicates.
778 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
779
780 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000781 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
782 if (ShouldCheckConstantCond &&
783 CaseVals[i].first == ConstantCondValue)
784 ShouldCheckConstantCond = false;
785
786 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000787 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000788 // First, determine if either case value has a name
789 StringRef PrevString, CurrString;
790 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
791 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
792 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
793 PrevString = DeclRef->getDecl()->getName();
794 }
795 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
796 CurrString = DeclRef->getDecl()->getName();
797 }
Douglas Gregor50de5e32012-05-16 16:11:17 +0000798 llvm::SmallString<16> CaseValStr;
799 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000800
801 if (PrevString == CurrString)
802 Diag(CaseVals[i].second->getLHS()->getLocStart(),
803 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000804 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000805 else
806 Diag(CaseVals[i].second->getLHS()->getLocStart(),
807 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000808 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
809 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000810 CaseValStr;
811
John McCall0fb97082010-05-18 03:19:21 +0000812 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000813 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000814 // FIXME: We really want to remove the bogus case stmt from the
815 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000816 CaseListIsErroneous = true;
817 }
818 }
819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Douglas Gregordbb26db2009-05-15 23:57:33 +0000821 // Detect duplicate case ranges, which usually don't exist at all in
822 // the first place.
823 if (!CaseRanges.empty()) {
824 // Sort all the case ranges by their low value so we can easily detect
825 // overlaps between ranges.
826 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregordbb26db2009-05-15 23:57:33 +0000828 // Scan the ranges, computing the high values and removing empty ranges.
829 std::vector<llvm::APSInt> HiVals;
830 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000831 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000832 CaseStmt *CR = CaseRanges[i].second;
833 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000834 llvm::APSInt HiVal;
835
David Blaikie4e4d0842012-03-11 07:00:24 +0000836 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000837 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
838 // constant expression of the promoted type of the switch condition.
839 ExprResult ConvHi =
840 CheckConvertedConstantExpression(Hi, CondType, HiVal,
841 CCEK_CaseValue);
842 if (ConvHi.isInvalid()) {
843 CaseListIsErroneous = true;
844 continue;
845 }
846 Hi = ConvHi.take();
847 } else {
848 HiVal = Hi->EvaluateKnownConstInt(Context);
849
850 // If the RHS is not the same type as the condition, insert an
851 // implicit cast.
852 Hi = DefaultLvalueConversion(Hi).take();
853 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Douglas Gregordbb26db2009-05-15 23:57:33 +0000856 // Convert the value to the same width/sign as the condition.
857 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000858 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000859 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregordbb26db2009-05-15 23:57:33 +0000861 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregordbb26db2009-05-15 23:57:33 +0000863 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000864 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000865 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
866 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000867 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000868 CaseRanges.erase(CaseRanges.begin()+i);
869 --i, --e;
870 continue;
871 }
John McCall0fb97082010-05-18 03:19:21 +0000872
873 if (ShouldCheckConstantCond &&
874 LoVal <= ConstantCondValue &&
875 ConstantCondValue <= HiVal)
876 ShouldCheckConstantCond = false;
877
Douglas Gregordbb26db2009-05-15 23:57:33 +0000878 HiVals.push_back(HiVal);
879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Douglas Gregordbb26db2009-05-15 23:57:33 +0000881 // Rescan the ranges, looking for overlap with singleton values and other
882 // ranges. Since the range list is sorted, we only need to compare case
883 // ranges with their neighbors.
884 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
885 llvm::APSInt &CRLo = CaseRanges[i].first;
886 llvm::APSInt &CRHi = HiVals[i];
887 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Douglas Gregordbb26db2009-05-15 23:57:33 +0000889 // Check to see whether the case range overlaps with any
890 // singleton cases.
891 CaseStmt *OverlapStmt = 0;
892 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Douglas Gregordbb26db2009-05-15 23:57:33 +0000894 // Find the smallest value >= the lower bound. If I is in the
895 // case range, then we have overlap.
896 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
897 CaseVals.end(), CRLo,
898 CaseCompareFunctor());
899 if (I != CaseVals.end() && I->first < CRHi) {
900 OverlapVal = I->first; // Found overlap with scalar.
901 OverlapStmt = I->second;
902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Douglas Gregordbb26db2009-05-15 23:57:33 +0000904 // Find the smallest value bigger than the upper bound.
905 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
906 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
907 OverlapVal = (I-1)->first; // Found overlap with scalar.
908 OverlapStmt = (I-1)->second;
909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregordbb26db2009-05-15 23:57:33 +0000911 // Check to see if this case stmt overlaps with the subsequent
912 // case range.
913 if (i && CRLo <= HiVals[i-1]) {
914 OverlapVal = HiVals[i-1]; // Found overlap with range.
915 OverlapStmt = CaseRanges[i-1].second;
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Douglas Gregordbb26db2009-05-15 23:57:33 +0000918 if (OverlapStmt) {
919 // If we have a duplicate, report it.
920 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
921 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000922 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000923 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000924 // FIXME: We really want to remove the bogus case stmt from the
925 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000926 CaseListIsErroneous = true;
927 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000928 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000929 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000930
John McCall0fb97082010-05-18 03:19:21 +0000931 // Complain if we have a constant condition and we didn't find a match.
932 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
933 // TODO: it would be nice if we printed enums as enums, chars as
934 // chars, etc.
935 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
936 << ConstantCondValue.toString(10)
937 << CondExpr->getSourceRange();
938 }
939
940 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000941 // values. We only issue a warning if there is not 'default:', but
942 // we still do the analysis to preserve this information in the AST
943 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000944 //
Chris Lattnerce784612010-09-16 17:09:42 +0000945 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000946
Douglas Gregorba915af2010-02-08 22:24:16 +0000947 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000948 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000949 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000950 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000951 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000952 EnumValsTy EnumVals;
953
John McCall0fb97082010-05-18 03:19:21 +0000954 // Gather all enum values, set their type and sort them,
955 // allowing easier comparison with CaseVals.
956 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000957 EDI != ED->enumerator_end(); ++EDI) {
958 llvm::APSInt Val = EDI->getInitVal();
959 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000960 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000961 }
962 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000963 EnumValsTy::iterator EIend =
964 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000965
966 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000967 EnumValsTy::const_iterator EI = EnumVals.begin();
968 for (CaseValsTy::const_iterator CI = CaseVals.begin();
969 CI != CaseVals.end(); CI++) {
970 while (EI != EIend && EI->first < CI->first)
971 EI++;
972 if (EI == EIend || EI->first > CI->first)
973 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000974 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000975 }
976 // See which of case ranges aren't in enum
977 EI = EnumVals.begin();
978 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
979 RI != CaseRanges.end() && EI != EIend; RI++) {
980 while (EI != EIend && EI->first < RI->first)
981 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
David Blaikie93667502012-01-22 02:31:55 +0000983 if (EI == EIend || EI->first != RI->first) {
984 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000985 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000986 }
David Blaikie93667502012-01-22 02:31:55 +0000987
988 llvm::APSInt Hi =
989 RI->second->getRHS()->EvaluateKnownConstInt(Context);
990 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
991 while (EI != EIend && EI->first < Hi)
992 EI++;
993 if (EI == EIend || EI->first != Hi)
994 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000995 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +0000996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000997
Ted Kremenek559fb552010-09-09 00:05:53 +0000998 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000999 CaseValsTy::const_iterator CI = CaseVals.begin();
1000 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001001 bool hasCasesNotInSwitch = false;
1002
Chris Lattner5f9e2722011-07-23 10:55:15 +00001003 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001004
David Blaikie93667502012-01-22 02:31:55 +00001005 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001006 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001007 llvm::APSInt CIVal;
1008 while (CI != CaseVals.end() && CI->first < EI->first)
1009 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001010
Douglas Gregorba915af2010-02-08 22:24:16 +00001011 if (CI != CaseVals.end() && CI->first == EI->first)
1012 continue;
1013
Ted Kremenek559fb552010-09-09 00:05:53 +00001014 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001015 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001016 llvm::APSInt Hi =
1017 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001018 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001019 if (EI->first <= Hi)
1020 break;
1021 }
1022
Ted Kremenek559fb552010-09-09 00:05:53 +00001023 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001024 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001025 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001026 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001027 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
David Blaikie585d7792012-01-23 04:46:12 +00001029 if (TheDefaultStmt && UnhandledNames.empty())
1030 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001031
Chris Lattnerce784612010-09-16 17:09:42 +00001032 // Produce a nice diagnostic if multiple values aren't handled.
1033 switch (UnhandledNames.size()) {
1034 case 0: break;
1035 case 1:
David Blaikie585d7792012-01-23 04:46:12 +00001036 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1037 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001038 << UnhandledNames[0];
1039 break;
1040 case 2:
David Blaikie585d7792012-01-23 04:46:12 +00001041 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1042 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001043 << UnhandledNames[0] << UnhandledNames[1];
1044 break;
1045 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001046 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1047 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001048 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1049 break;
1050 default:
David Blaikie585d7792012-01-23 04:46:12 +00001051 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1052 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001053 << (unsigned)UnhandledNames.size()
1054 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1055 break;
1056 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001057
1058 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001059 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001060 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001061 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001062
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001063 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1064 diag::warn_empty_switch_body);
1065
Mike Stump390b4cc2009-05-16 07:39:55 +00001066 // FIXME: If the case list was broken is some way, we don't have a good system
1067 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001068 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001069 return StmtError();
1070
Sebastian Redlde307472009-01-11 00:38:46 +00001071 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001072}
1073
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001074void
1075Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1076 Expr *SrcExpr) {
1077 unsigned DIAG = diag::warn_not_in_enum_assignement;
1078 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1079 == DiagnosticsEngine::Ignored)
1080 return;
1081
1082 if (const EnumType *ET = DstType->getAs<EnumType>())
1083 if (!Context.hasSameType(SrcType, DstType) &&
1084 SrcType->isIntegerType()) {
1085 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1086 SrcExpr->isIntegerConstantExpr(Context)) {
1087 // Get the bitwidth of the enum value before promotions.
1088 unsigned DstWith = Context.getIntWidth(DstType);
1089 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1090
1091 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1092 const EnumDecl *ED = ET->getDecl();
1093 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1094 EnumValsTy;
1095 EnumValsTy EnumVals;
1096
1097 // Gather all enum values, set their type and sort them,
1098 // allowing easier comparison with rhs constant.
1099 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1100 EDI != ED->enumerator_end(); ++EDI) {
1101 llvm::APSInt Val = EDI->getInitVal();
1102 AdjustAPSInt(Val, DstWith, DstIsSigned);
1103 EnumVals.push_back(std::make_pair(Val, *EDI));
1104 }
1105 if (EnumVals.empty())
1106 return;
1107 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1108 EnumValsTy::iterator EIend =
1109 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1110
1111 // See which case values aren't in enum.
1112 EnumValsTy::const_iterator EI = EnumVals.begin();
1113 while (EI != EIend && EI->first < RhsVal)
1114 EI++;
1115 if (EI == EIend || EI->first != RhsVal) {
1116 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1117 << DstType;
1118 }
1119 }
1120 }
1121}
1122
John McCall60d7b3a2010-08-24 06:29:42 +00001123StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001125 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001126 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001127
Douglas Gregor5656e142009-11-24 21:15:44 +00001128 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001129 if (CondVar) {
1130 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001131 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001132 if (CondResult.isInvalid())
1133 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001134 }
John McCall9ae2f072010-08-23 23:25:46 +00001135 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001136 if (!ConditionExpr)
1137 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138
John McCall9ae2f072010-08-23 23:25:46 +00001139 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001141 if (isa<NullStmt>(Body))
1142 getCurCompoundScope().setHasEmptyLoopBodies();
1143
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001144 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001145 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001146}
1147
John McCall60d7b3a2010-08-24 06:29:42 +00001148StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001149Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001150 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001151 Expr *Cond, SourceLocation CondRParen) {
1152 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001153
John Wiegley429bb272011-04-08 18:41:53 +00001154 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1155 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001156 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001157 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001158
John McCallb4eb64d2010-10-08 02:01:28 +00001159 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +00001160 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +00001161 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001162 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001163 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001164
John McCall9ae2f072010-08-23 23:25:46 +00001165 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001166
John McCall9ae2f072010-08-23 23:25:46 +00001167 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001168}
1169
Richard Trieu694e7962012-04-30 18:01:30 +00001170namespace {
1171 // This visitor will traverse a conditional statement and store all
1172 // the evaluated decls into a vector. Simple is set to true if none
1173 // of the excluded constructs are used.
1174 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1175 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1176 llvm::SmallVector<SourceRange, 10> &Ranges;
1177 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001178public:
1179 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1180
1181 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerfacde172012-06-06 17:32:50 +00001182 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001183 Inherited(S.Context),
1184 Decls(Decls),
1185 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001186 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001187
1188 bool isSimple() { return Simple; }
1189
1190 // Replaces the method in EvaluatedExprVisitor.
1191 void VisitMemberExpr(MemberExpr* E) {
1192 Simple = false;
1193 }
1194
1195 // Any Stmt not whitelisted will cause the condition to be marked complex.
1196 void VisitStmt(Stmt *S) {
1197 Simple = false;
1198 }
1199
1200 void VisitBinaryOperator(BinaryOperator *E) {
1201 Visit(E->getLHS());
1202 Visit(E->getRHS());
1203 }
1204
1205 void VisitCastExpr(CastExpr *E) {
1206 Visit(E->getSubExpr());
1207 }
1208
1209 void VisitUnaryOperator(UnaryOperator *E) {
1210 // Skip checking conditionals with derefernces.
1211 if (E->getOpcode() == UO_Deref)
1212 Simple = false;
1213 else
1214 Visit(E->getSubExpr());
1215 }
1216
1217 void VisitConditionalOperator(ConditionalOperator *E) {
1218 Visit(E->getCond());
1219 Visit(E->getTrueExpr());
1220 Visit(E->getFalseExpr());
1221 }
1222
1223 void VisitParenExpr(ParenExpr *E) {
1224 Visit(E->getSubExpr());
1225 }
1226
1227 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1228 Visit(E->getOpaqueValue()->getSourceExpr());
1229 Visit(E->getFalseExpr());
1230 }
1231
1232 void VisitIntegerLiteral(IntegerLiteral *E) { }
1233 void VisitFloatingLiteral(FloatingLiteral *E) { }
1234 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1235 void VisitCharacterLiteral(CharacterLiteral *E) { }
1236 void VisitGNUNullExpr(GNUNullExpr *E) { }
1237 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1238
1239 void VisitDeclRefExpr(DeclRefExpr *E) {
1240 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1241 if (!VD) return;
1242
1243 Ranges.push_back(E->getSourceRange());
1244
1245 Decls.insert(VD);
1246 }
1247
1248 }; // end class DeclExtractor
1249
1250 // DeclMatcher checks to see if the decls are used in a non-evauluated
1251 // context.
1252 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1253 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1254 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001255
1256public:
1257 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1258
1259 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1260 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1261 if (!Statement) return;
1262
1263 Visit(Statement);
1264 }
1265
1266 void VisitReturnStmt(ReturnStmt *S) {
1267 FoundDecl = true;
1268 }
1269
1270 void VisitBreakStmt(BreakStmt *S) {
1271 FoundDecl = true;
1272 }
1273
1274 void VisitGotoStmt(GotoStmt *S) {
1275 FoundDecl = true;
1276 }
1277
1278 void VisitCastExpr(CastExpr *E) {
1279 if (E->getCastKind() == CK_LValueToRValue)
1280 CheckLValueToRValueCast(E->getSubExpr());
1281 else
1282 Visit(E->getSubExpr());
1283 }
1284
1285 void CheckLValueToRValueCast(Expr *E) {
1286 E = E->IgnoreParenImpCasts();
1287
1288 if (isa<DeclRefExpr>(E)) {
1289 return;
1290 }
1291
1292 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1293 Visit(CO->getCond());
1294 CheckLValueToRValueCast(CO->getTrueExpr());
1295 CheckLValueToRValueCast(CO->getFalseExpr());
1296 return;
1297 }
1298
1299 if (BinaryConditionalOperator *BCO =
1300 dyn_cast<BinaryConditionalOperator>(E)) {
1301 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1302 CheckLValueToRValueCast(BCO->getFalseExpr());
1303 return;
1304 }
1305
1306 Visit(E);
1307 }
1308
1309 void VisitDeclRefExpr(DeclRefExpr *E) {
1310 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1311 if (Decls.count(VD))
1312 FoundDecl = true;
1313 }
1314
1315 bool FoundDeclInUse() { return FoundDecl; }
1316
1317 }; // end class DeclMatcher
1318
1319 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1320 Expr *Third, Stmt *Body) {
1321 // Condition is empty
1322 if (!Second) return;
1323
1324 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1325 Second->getLocStart())
1326 == DiagnosticsEngine::Ignored)
1327 return;
1328
1329 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1330 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1331 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001332 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001333 DE.Visit(Second);
1334
1335 // Don't analyze complex conditionals.
1336 if (!DE.isSimple()) return;
1337
1338 // No decls found.
1339 if (Decls.size() == 0) return;
1340
Richard Trieu90875992012-05-04 03:01:54 +00001341 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001342 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1343 E = Decls.end();
1344 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001345 if ((*I)->getType().isVolatileQualified() ||
1346 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001347
1348 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1349 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1350 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1351 return;
1352
1353 // Load decl names into diagnostic.
1354 if (Decls.size() > 4)
1355 PDiag << 0;
1356 else {
1357 PDiag << Decls.size();
1358 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1359 E = Decls.end();
1360 I != E; ++I)
1361 PDiag << (*I)->getDeclName();
1362 }
1363
1364 // Load SourceRanges into diagnostic if there is room.
1365 // Otherwise, load the SourceRange of the conditional expression.
1366 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1367 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1368 E = Ranges.end();
1369 I != E; ++I)
1370 PDiag << *I;
1371 else
1372 PDiag << Second->getSourceRange();
1373
1374 S.Diag(Ranges.begin()->getBegin(), PDiag);
1375 }
1376
1377} // end namespace
1378
John McCall60d7b3a2010-08-24 06:29:42 +00001379StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001380Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001381 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001382 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001383 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001384 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001385 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001386 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1387 // declare identifiers for objects having storage class 'auto' or
1388 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001389 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1390 DI!=DE; ++DI) {
1391 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001392 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001393 VD = 0;
1394 if (VD == 0)
1395 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1396 // FIXME: mark decl erroneous!
1397 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001398 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001400
Richard Trieu694e7962012-04-30 18:01:30 +00001401 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1402
John McCall60d7b3a2010-08-24 06:29:42 +00001403 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001404 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001405 if (secondVar) {
1406 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001407 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001408 if (SecondResult.isInvalid())
1409 return StmtError();
1410 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001411
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001412 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413
Anders Carlsson3af708f2009-08-01 01:39:59 +00001414 DiagnoseUnusedExprResult(First);
1415 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001416 DiagnoseUnusedExprResult(Body);
1417
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001418 if (isa<NullStmt>(Body))
1419 getCurCompoundScope().setHasEmptyLoopBodies();
1420
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001421 return Owned(new (Context) ForStmt(Context, First,
1422 SecondResult.take(), ConditionVar,
1423 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001424 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001425}
1426
John McCallf6a16482010-12-04 03:47:34 +00001427/// In an Objective C collection iteration statement:
1428/// for (x in y)
1429/// x can be an arbitrary l-value expression. Bind it up as a
1430/// full-expression.
1431StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001432 // Reduce placeholder expressions here. Note that this rejects the
1433 // use of pseudo-object l-values in this position.
1434 ExprResult result = CheckPlaceholderExpr(E);
1435 if (result.isInvalid()) return StmtError();
1436 E = result.take();
1437
John McCallf6a16482010-12-04 03:47:34 +00001438 CheckImplicitConversions(E);
John McCall29bbd1a2012-03-30 05:43:39 +00001439
1440 result = MaybeCreateExprWithCleanups(E);
1441 if (result.isInvalid()) return StmtError();
1442
1443 return Owned(static_cast<Stmt*>(result.take()));
John McCallf6a16482010-12-04 03:47:34 +00001444}
1445
John McCall990567c2011-07-27 01:07:15 +00001446ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001447Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1448 if (!collection)
1449 return ExprError();
1450
John McCall990567c2011-07-27 01:07:15 +00001451 // Bail out early if we've got a type-dependent expression.
1452 if (collection->isTypeDependent()) return Owned(collection);
1453
1454 // Perform normal l-value conversion.
1455 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1456 if (result.isInvalid())
1457 return ExprError();
1458 collection = result.take();
1459
1460 // The operand needs to have object-pointer type.
1461 // TODO: should we do a contextual conversion?
1462 const ObjCObjectPointerType *pointerType =
1463 collection->getType()->getAs<ObjCObjectPointerType>();
1464 if (!pointerType)
1465 return Diag(forLoc, diag::err_collection_expr_type)
1466 << collection->getType() << collection->getSourceRange();
1467
1468 // Check that the operand provides
1469 // - countByEnumeratingWithState:objects:count:
1470 const ObjCObjectType *objectType = pointerType->getObjectType();
1471 ObjCInterfaceDecl *iface = objectType->getInterface();
1472
1473 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001474 // Under ARC, it is an error not to have a forward-declared class.
1475 if (iface &&
1476 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001477 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001478 ? diag::err_arc_collection_forward
1479 : 0,
1480 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001481 // Otherwise, if we have any useful type information, check that
1482 // the type declares the appropriate method.
1483 } else if (iface || !objectType->qual_empty()) {
1484 IdentifierInfo *selectorIdents[] = {
1485 &Context.Idents.get("countByEnumeratingWithState"),
1486 &Context.Idents.get("objects"),
1487 &Context.Idents.get("count")
1488 };
1489 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1490
1491 ObjCMethodDecl *method = 0;
1492
1493 // If there's an interface, look in both the public and private APIs.
1494 if (iface) {
1495 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001496 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001497 }
1498
1499 // Also check protocol qualifiers.
1500 if (!method)
1501 method = LookupMethodInQualifiedType(selector, pointerType,
1502 /*instance*/ true);
1503
1504 // If we didn't find it anywhere, give up.
1505 if (!method) {
1506 Diag(forLoc, diag::warn_collection_expr_type)
1507 << collection->getType() << selector << collection->getSourceRange();
1508 }
1509
1510 // TODO: check for an incompatible signature?
1511 }
1512
1513 // Wrap up any cleanups in the expression.
1514 return Owned(MaybeCreateExprWithCleanups(collection));
1515}
1516
John McCall60d7b3a2010-08-24 06:29:42 +00001517StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001518Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1519 SourceLocation LParenLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001520 Stmt *First, Expr *collection,
1521 SourceLocation RParenLoc) {
1522
1523 ExprResult CollectionExprResult =
1524 CheckObjCForCollectionOperand(ForLoc, collection);
1525
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001526 if (First) {
1527 QualType FirstType;
1528 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001529 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001530 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1531 diag::err_toomany_element_decls));
1532
John McCallf85e1932011-06-15 23:02:42 +00001533 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1534 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001535 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1536 // declare identifiers for objects having storage class 'auto' or
1537 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001538 if (!D->hasLocalStorage())
1539 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001540 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001541 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001542 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001543 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001544 return StmtError(Diag(First->getLocStart(),
1545 diag::err_selector_element_not_lvalue)
1546 << First->getSourceRange());
1547
Mike Stump1eb44332009-09-09 15:08:12 +00001548 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001549 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001550 if (!FirstType->isDependentType() &&
1551 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001552 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001553 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1554 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001555 }
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001556
1557 if (CollectionExprResult.isInvalid())
1558 return StmtError();
1559
1560 return Owned(new (Context) ObjCForCollectionStmt(First,
1561 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001562 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001563}
Reid Spencer5f016e22007-07-11 17:01:13 +00001564
Richard Smithad762fc2011-04-14 22:09:26 +00001565namespace {
1566
1567enum BeginEndFunction {
1568 BEF_begin,
1569 BEF_end
1570};
1571
1572/// Build a variable declaration for a for-range statement.
1573static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1574 QualType Type, const char *Name) {
1575 DeclContext *DC = SemaRef.CurContext;
1576 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1577 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1578 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1579 TInfo, SC_Auto, SC_None);
Richard Smithb403d6d2011-04-18 15:49:25 +00001580 Decl->setImplicit();
Richard Smithad762fc2011-04-14 22:09:26 +00001581 return Decl;
1582}
1583
1584/// Finish building a variable declaration for a for-range statement.
1585/// \return true if an error occurs.
1586static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1587 SourceLocation Loc, int diag) {
1588 // Deduce the type for the iterator variable now rather than leaving it to
1589 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1590 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001591 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001592 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1593 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001594 SemaRef.Diag(Loc, diag) << Init->getType();
1595 if (!InitTSI) {
1596 Decl->setInvalidDecl();
1597 return true;
1598 }
1599 Decl->setTypeSourceInfo(InitTSI);
1600 Decl->setType(InitTSI->getType());
1601
John McCallf85e1932011-06-15 23:02:42 +00001602 // In ARC, infer lifetime.
1603 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1604 // we're doing the equivalent of fast iteration.
David Blaikie4e4d0842012-03-11 07:00:24 +00001605 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001606 SemaRef.inferObjCARCLifetime(Decl))
1607 Decl->setInvalidDecl();
1608
Richard Smithad762fc2011-04-14 22:09:26 +00001609 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1610 /*TypeMayContainAuto=*/false);
1611 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001612 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001613 return false;
1614}
1615
1616/// Produce a note indicating which begin/end function was implicitly called
1617/// by a C++0x for-range statement. This is often not obvious from the code,
1618/// nor from the diagnostics produced when analysing the implicit expressions
1619/// required in a for-range statement.
1620void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1621 BeginEndFunction BEF) {
1622 CallExpr *CE = dyn_cast<CallExpr>(E);
1623 if (!CE)
1624 return;
1625 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1626 if (!D)
1627 return;
1628 SourceLocation Loc = D->getLocation();
1629
1630 std::string Description;
1631 bool IsTemplate = false;
1632 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1633 Description = SemaRef.getTemplateArgumentBindingsText(
1634 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1635 IsTemplate = true;
1636 }
1637
1638 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1639 << BEF << IsTemplate << Description << E->getType();
1640}
1641
1642/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1643/// given LookupResult is non-empty, it is assumed to describe a member which
1644/// will be invoked. Otherwise, the function will be found via argument
1645/// dependent lookup.
1646static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1647 SourceLocation Loc,
1648 VarDecl *Decl,
1649 BeginEndFunction BEF,
1650 const DeclarationNameInfo &NameInfo,
1651 LookupResult &MemberLookup,
1652 Expr *Range) {
1653 ExprResult CallExpr;
1654 if (!MemberLookup.empty()) {
1655 ExprResult MemberRef =
1656 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1657 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001658 /*TemplateKWLoc=*/SourceLocation(),
1659 /*FirstQualifierInScope=*/0,
1660 MemberLookup,
Richard Smithad762fc2011-04-14 22:09:26 +00001661 /*TemplateArgs=*/0);
1662 if (MemberRef.isInvalid())
1663 return ExprError();
1664 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1665 Loc, 0);
1666 if (CallExpr.isInvalid())
1667 return ExprError();
1668 } else {
1669 UnresolvedSet<0> FoundNames;
1670 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1671 // std is an associated namespace.
1672 UnresolvedLookupExpr *Fn =
1673 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1674 NestedNameSpecifierLoc(), NameInfo,
1675 /*NeedsADL=*/true, /*Overloaded=*/false,
1676 FoundNames.begin(), FoundNames.end(),
1677 /*LookInStdNamespace=*/true);
1678 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00001679 0, /*AllowTypoCorrection=*/false);
Richard Smithad762fc2011-04-14 22:09:26 +00001680 if (CallExpr.isInvalid()) {
1681 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1682 << Range->getType();
1683 return ExprError();
1684 }
1685 }
1686 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1687 diag::err_for_range_iter_deduction_failure)) {
1688 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1689 return ExprError();
1690 }
1691 return CallExpr;
1692}
1693
1694}
1695
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001696static bool ObjCEnumerationCollection(Expr *Collection) {
1697 return !Collection->isTypeDependent()
1698 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1699}
1700
Richard Smithad762fc2011-04-14 22:09:26 +00001701/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1702///
1703/// C++0x [stmt.ranged]:
1704/// A range-based for statement is equivalent to
1705///
1706/// {
1707/// auto && __range = range-init;
1708/// for ( auto __begin = begin-expr,
1709/// __end = end-expr;
1710/// __begin != __end;
1711/// ++__begin ) {
1712/// for-range-declaration = *__begin;
1713/// statement
1714/// }
1715/// }
1716///
1717/// The body of the loop is not available yet, since it cannot be analysed until
1718/// we have determined the type of the for-range-declaration.
1719StmtResult
1720Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1721 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1722 SourceLocation RParenLoc) {
1723 if (!First || !Range)
1724 return StmtError();
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001725
1726 if (ObjCEnumerationCollection(Range))
1727 return ActOnObjCForCollectionStmt(ForLoc, LParenLoc, First, Range,
1728 RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001729
1730 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1731 assert(DS && "first part of for range not a decl stmt");
1732
1733 if (!DS->isSingleDecl()) {
1734 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1735 return StmtError();
1736 }
1737 if (DS->getSingleDecl()->isInvalidDecl())
1738 return StmtError();
1739
1740 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1741 return StmtError();
1742
1743 // Build auto && __range = range-init
1744 SourceLocation RangeLoc = Range->getLocStart();
1745 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1746 Context.getAutoRRefDeductType(),
1747 "__range");
1748 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1749 diag::err_for_range_deduction_failure))
1750 return StmtError();
1751
1752 // Claim the type doesn't contain auto: we've already done the checking.
1753 DeclGroupPtrTy RangeGroup =
1754 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1755 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1756 if (RangeDecl.isInvalid())
1757 return StmtError();
1758
1759 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1760 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1761 RParenLoc);
1762}
1763
1764/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1765StmtResult
1766Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1767 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1768 Expr *Inc, Stmt *LoopVarDecl,
1769 SourceLocation RParenLoc) {
1770 Scope *S = getCurScope();
1771
1772 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1773 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1774 QualType RangeVarType = RangeVar->getType();
1775
1776 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1777 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1778
1779 StmtResult BeginEndDecl = BeginEnd;
1780 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1781
1782 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1783 SourceLocation RangeLoc = RangeVar->getLocation();
1784
Ted Kremeneke50b0152011-10-10 22:36:28 +00001785 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1786
1787 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1788 VK_LValue, ColonLoc);
1789 if (BeginRangeRef.isInvalid())
1790 return StmtError();
1791
1792 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1793 VK_LValue, ColonLoc);
1794 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001795 return StmtError();
1796
1797 QualType AutoType = Context.getAutoDeductType();
1798 Expr *Range = RangeVar->getInit();
1799 if (!Range)
1800 return StmtError();
1801 QualType RangeType = Range->getType();
1802
1803 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001804 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001805 return StmtError();
1806
1807 // Build auto __begin = begin-expr, __end = end-expr.
1808 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1809 "__begin");
1810 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1811 "__end");
1812
1813 // Build begin-expr and end-expr and attach to __begin and __end variables.
1814 ExprResult BeginExpr, EndExpr;
1815 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1816 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1817 // __range + __bound, respectively, where __bound is the array bound. If
1818 // _RangeT is an array of unknown size or an array of incomplete type,
1819 // the program is ill-formed;
1820
1821 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001822 BeginExpr = BeginRangeRef;
1823 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001824 diag::err_for_range_iter_deduction_failure)) {
1825 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1826 return StmtError();
1827 }
1828
1829 // Find the array bound.
1830 ExprResult BoundExpr;
1831 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1832 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001833 Context.getPointerDiffType(),
1834 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001835 else if (const VariableArrayType *VAT =
1836 dyn_cast<VariableArrayType>(UnqAT))
1837 BoundExpr = VAT->getSizeExpr();
1838 else {
1839 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1840 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001841 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001842 }
1843
1844 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001845 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001846 BoundExpr.get());
1847 if (EndExpr.isInvalid())
1848 return StmtError();
1849 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1850 diag::err_for_range_iter_deduction_failure)) {
1851 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1852 return StmtError();
1853 }
1854 } else {
1855 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1856 ColonLoc);
1857 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1858 ColonLoc);
1859
1860 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1861 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1862
1863 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1864 // - if _RangeT is a class type, the unqualified-ids begin and end are
1865 // looked up in the scope of class _RangeT as if by class member access
1866 // lookup (3.4.5), and if either (or both) finds at least one
1867 // declaration, begin-expr and end-expr are __range.begin() and
1868 // __range.end(), respectively;
1869 LookupQualifiedName(BeginMemberLookup, D);
1870 LookupQualifiedName(EndMemberLookup, D);
1871
1872 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1873 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1874 << RangeType << BeginMemberLookup.empty();
1875 return StmtError();
1876 }
1877 } else {
1878 // - otherwise, begin-expr and end-expr are begin(__range) and
1879 // end(__range), respectively, where begin and end are looked up with
1880 // argument-dependent lookup (3.4.2). For the purposes of this name
1881 // lookup, namespace std is an associated namespace.
1882 }
1883
1884 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1885 BEF_begin, BeginNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001886 BeginMemberLookup,
1887 BeginRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001888 if (BeginExpr.isInvalid())
1889 return StmtError();
1890
1891 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1892 BEF_end, EndNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001893 EndMemberLookup, EndRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001894 if (EndExpr.isInvalid())
1895 return StmtError();
1896 }
1897
1898 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1899 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1900 if (!Context.hasSameType(BeginType, EndType)) {
1901 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1902 << BeginType << EndType;
1903 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1904 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1905 }
1906
1907 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1908 // Claim the type doesn't contain auto: we've already done the checking.
1909 DeclGroupPtrTy BeginEndGroup =
1910 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1911 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1912
Ted Kremeneke50b0152011-10-10 22:36:28 +00001913 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1914 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001915 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001916 if (BeginRef.isInvalid())
1917 return StmtError();
1918
Richard Smithad762fc2011-04-14 22:09:26 +00001919 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1920 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001921 if (EndRef.isInvalid())
1922 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001923
1924 // Build and check __begin != __end expression.
1925 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1926 BeginRef.get(), EndRef.get());
1927 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1928 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1929 if (NotEqExpr.isInvalid()) {
1930 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1931 if (!Context.hasSameType(BeginType, EndType))
1932 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1933 return StmtError();
1934 }
1935
1936 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001937 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1938 VK_LValue, ColonLoc);
1939 if (BeginRef.isInvalid())
1940 return StmtError();
1941
Richard Smithad762fc2011-04-14 22:09:26 +00001942 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1943 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1944 if (IncrExpr.isInvalid()) {
1945 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1946 return StmtError();
1947 }
1948
1949 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001950 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1951 VK_LValue, ColonLoc);
1952 if (BeginRef.isInvalid())
1953 return StmtError();
1954
Richard Smithad762fc2011-04-14 22:09:26 +00001955 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1956 if (DerefExpr.isInvalid()) {
1957 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1958 return StmtError();
1959 }
1960
1961 // Attach *__begin as initializer for VD.
1962 if (!LoopVar->isInvalidDecl()) {
1963 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1964 /*TypeMayContainAuto=*/true);
1965 if (LoopVar->isInvalidDecl())
1966 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1967 }
Richard Smithcd6f3662011-06-21 23:07:19 +00001968 } else {
1969 // The range is implicitly used as a placeholder when it is dependent.
1970 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00001971 }
1972
1973 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1974 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1975 NotEqExpr.take(), IncrExpr.take(),
1976 LoopVarDS, /*Body=*/0, ForLoc,
1977 ColonLoc, RParenLoc));
1978}
1979
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001980/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
1981/// statement.
1982StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1983 if (!S || !B)
1984 return StmtError();
1985 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
1986
1987 ForStmt->setBody(B);
1988 return S;
1989}
1990
Richard Smithad762fc2011-04-14 22:09:26 +00001991/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1992/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1993/// body cannot be performed until after the type of the range variable is
1994/// determined.
1995StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1996 if (!S || !B)
1997 return StmtError();
1998
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001999 if (isa<ObjCForCollectionStmt>(S))
2000 return FinishObjCForCollectionStmt(S, B);
2001
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002002 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2003 ForStmt->setBody(B);
2004
2005 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2006 diag::warn_empty_range_based_for_body);
2007
Richard Smithad762fc2011-04-14 22:09:26 +00002008 return S;
2009}
2010
Chris Lattner57ad3782011-02-17 20:34:02 +00002011StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2012 SourceLocation LabelLoc,
2013 LabelDecl *TheDecl) {
2014 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002015 TheDecl->setUsed();
2016 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002017}
2018
John McCall60d7b3a2010-08-24 06:29:42 +00002019StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002020Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002021 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002022 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002023 if (!E->isTypeDependent()) {
2024 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002025 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002026 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002027 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002028 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2029 if (ExprRes.isInvalid())
2030 return StmtError();
2031 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002032 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002033 return StmtError();
Eli Friedmand29975f2012-01-31 22:47:07 +00002034 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002035 }
John McCallb60a77e2010-08-01 00:26:45 +00002036
John McCall781472f2010-08-25 08:40:02 +00002037 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002038
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002039 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002040}
2041
John McCall60d7b3a2010-08-24 06:29:42 +00002042StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002043Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 Scope *S = CurScope->getContinueParent();
2045 if (!S) {
2046 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002047 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002049
Ted Kremenek8189cde2009-02-07 01:47:29 +00002050 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002051}
2052
John McCall60d7b3a2010-08-24 06:29:42 +00002053StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002054Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 Scope *S = CurScope->getBreakParent();
2056 if (!S) {
2057 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002058 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002060
Ted Kremenek8189cde2009-02-07 01:47:29 +00002061 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002062}
2063
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002064/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002065/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002066///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002067/// \param ReturnType If we're determining the copy elision candidate for
2068/// a return statement, this is the return type of the function. If we're
2069/// determining the copy elision candidate for a throw expression, this will
2070/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002071///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002072/// \param E The expression being returned from the function or block, or
2073/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002074///
Douglas Gregor4926d832011-05-20 15:00:53 +00002075/// \param AllowFunctionParameter Whether we allow function parameters to
2076/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2077/// we re-use this logic to determine whether we should try to move as part of
2078/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002079///
2080/// \returns The NRVO candidate variable, if the return statement may use the
2081/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002082const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2083 Expr *E,
2084 bool AllowFunctionParameter) {
2085 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002086 // - in a return statement in a function with ...
2087 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002088 if (!ReturnType.isNull()) {
2089 if (!ReturnType->isRecordType())
2090 return 0;
2091 // ... the same cv-unqualified type as the function return type ...
2092 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2093 return 0;
2094 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095
2096 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002097 // (other than a function or catch-clause parameter)) ...
2098 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002099 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002100 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002101 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2102 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002103 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002104
John McCall1cd76e82011-11-11 03:57:31 +00002105 // ...object (other than a function or catch-clause parameter)...
2106 if (VD->getKind() != Decl::Var &&
2107 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2108 return 0;
2109 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002110
John McCall1cd76e82011-11-11 03:57:31 +00002111 // ...automatic...
2112 if (!VD->hasLocalStorage()) return 0;
2113
2114 // ...non-volatile...
2115 if (VD->getType().isVolatileQualified()) return 0;
2116 if (VD->getType()->isReferenceType()) return 0;
2117
2118 // __block variables can't be allocated in a way that permits NRVO.
2119 if (VD->hasAttr<BlocksAttr>()) return 0;
2120
2121 // Variables with higher required alignment than their type's ABI
2122 // alignment cannot use NRVO.
2123 if (VD->hasAttr<AlignedAttr>() &&
2124 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2125 return 0;
2126
2127 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002128}
2129
Douglas Gregor07f402c2011-01-21 21:08:57 +00002130/// \brief Perform the initialization of a potentially-movable value, which
2131/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002132///
2133/// This routine implements C++0x [class.copy]p33, which attempts to treat
2134/// returned lvalues as rvalues in certain cases (to prefer move construction),
2135/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002137Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2138 const VarDecl *NRVOCandidate,
2139 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002140 Expr *Value,
2141 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002142 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143 // When the criteria for elision of a copy operation are met or would
2144 // be met save for the fact that the source object is a function
2145 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002146 // overload resolution to select the constructor for the copy is first
2147 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002148 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002149 if (AllowNRVO &&
2150 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002152 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002153
Douglas Gregorcc15f012011-01-21 19:38:21 +00002154 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002155 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002156 = InitializationKind::CreateCopy(Value->getLocStart(),
2157 Value->getLocStart());
2158 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002159
2160 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002161 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002162 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002163 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002164 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002165 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2166 StepEnd = Seq.step_end();
2167 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002168 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002169 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170
2171 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002172 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002173
Douglas Gregorcc15f012011-01-21 19:38:21 +00002174 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002175 = Constructor->getParamDecl(0)->getType()
2176 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002177
Douglas Gregorcc15f012011-01-21 19:38:21 +00002178 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002179 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002180 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2181 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002182 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183
Douglas Gregorcc15f012011-01-21 19:38:21 +00002184 // Promote "AsRvalue" to the heap, since we now need this
2185 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002186 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002187 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188
Douglas Gregorcc15f012011-01-21 19:38:21 +00002189 // Complete type-checking the initialization of the return type
2190 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002191 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002192 }
2193 }
2194 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002195
Douglas Gregorcc15f012011-01-21 19:38:21 +00002196 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002197 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002198 // (again) now with the return value expression as written.
2199 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002200 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201
Douglas Gregorcc15f012011-01-21 19:38:21 +00002202 return Res;
2203}
2204
Eli Friedman84b007f2012-01-26 03:00:14 +00002205/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2206/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002207///
John McCall60d7b3a2010-08-24 06:29:42 +00002208StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002209Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2210 // If this is the first return we've seen, infer the return type.
2211 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2212 // rules which allows multiple return statements.
2213 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002214 QualType FnRetType = CurCap->ReturnType;
2215
2216 // For blocks/lambdas with implicit return types, we check each return
2217 // statement individually, and deduce the common return type when the block
2218 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002219 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002220 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002221 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2222 if (Result.isInvalid())
2223 return StmtError();
2224 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002225
Jordan Rose7dd900e2012-07-02 21:19:23 +00002226 if (!RetValExp->isTypeDependent())
2227 FnRetType = RetValExp->getType();
2228 else
2229 FnRetType = CurCap->ReturnType = Context.DependentTy;
Douglas Gregora0c2b212012-02-09 18:40:39 +00002230 } else {
2231 if (RetValExp) {
2232 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2233 // initializer list, because it is not an expression (even
2234 // though we represent it as one). We still deduce 'void'.
2235 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2236 << RetValExp->getSourceRange();
2237 }
2238
Jordan Rose7dd900e2012-07-02 21:19:23 +00002239 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002240 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002241
2242 // Although we'll properly infer the type of the block once it's completed,
2243 // make sure we provide a return type now for better error recovery.
2244 if (CurCap->ReturnType.isNull())
2245 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002246 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002247 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002248
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002249 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002250 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2251 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2252 return StmtError();
2253 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002254 } else {
2255 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2256 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2257 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2258 return StmtError();
2259 }
2260 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002261
Steve Naroff4eb206b2008-09-03 18:15:37 +00002262 // Otherwise, verify that this result type matches the previous one. We are
2263 // pickier with blocks than for normal functions because we don't have GCC
2264 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002265 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002266 if (FnRetType->isDependentType()) {
2267 // Delay processing for now. TODO: there are lots of dependent
2268 // types we can conclusively prove aren't void.
2269 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002270 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002271 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002272 (RetValExp->isTypeDependent() ||
2273 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002274 if (!getLangOpts().CPlusPlus &&
2275 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002276 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002277 else {
2278 Diag(ReturnLoc, diag::err_return_block_has_expr);
2279 RetValExp = 0;
2280 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002281 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002282 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002283 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2284 } else if (!RetValExp->isTypeDependent()) {
2285 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002286
John McCall0a7efe12011-08-17 22:09:46 +00002287 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2288 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2289 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002290
John McCall0a7efe12011-08-17 22:09:46 +00002291 // In C++ the return statement is handled via a copy initialization.
2292 // the C version of which boils down to CheckSingleAssignmentConstraints.
2293 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2294 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2295 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002296 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002297 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2298 FnRetType, RetValExp);
2299 if (Res.isInvalid()) {
2300 // FIXME: Cleanup temporaries here, anyway?
2301 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002302 }
John McCall0a7efe12011-08-17 22:09:46 +00002303 RetValExp = Res.take();
2304 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002305 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002306
John McCalld963c372011-08-17 21:34:14 +00002307 if (RetValExp) {
2308 CheckImplicitConversions(RetValExp, ReturnLoc);
2309 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2310 }
John McCall0a7efe12011-08-17 22:09:46 +00002311 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2312 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002313
Jordan Rose7dd900e2012-07-02 21:19:23 +00002314 // If we need to check for the named return value optimization,
2315 // or if we need to infer the return type,
2316 // save the return statement in our scope for later processing.
2317 if (CurCap->HasImplicitReturnType ||
2318 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2319 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002320 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002321
Douglas Gregor5077c382010-05-15 06:01:05 +00002322 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002323}
Reid Spencer5f016e22007-07-11 17:01:13 +00002324
John McCall60d7b3a2010-08-24 06:29:42 +00002325StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002326Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002327 // Check for unexpanded parameter packs.
2328 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2329 return StmtError();
2330
Eli Friedman84b007f2012-01-26 03:00:14 +00002331 if (isa<CapturingScopeInfo>(getCurFunction()))
2332 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002333
Chris Lattner371f2582008-12-04 23:50:19 +00002334 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002335 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002336 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002337 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002338 if (FD->hasAttr<NoReturnAttr>() ||
2339 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002340 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002341 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002342 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002343 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002344 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2345 // In the implementation of a method with a related return type, the
2346 // type used to type-check the validity of return statements within the
2347 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002348 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2349 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002350 }
2351 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002352 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor5077c382010-05-15 06:01:05 +00002354 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002355 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002356 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002357 if (isa<InitListExpr>(RetValExp)) {
2358 // We simply never allow init lists as the return value of void
2359 // functions. This is compatible because this was never allowed before,
2360 // so there's no legacy code to deal with.
2361 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2362 int FunctionKind = 0;
2363 if (isa<ObjCMethodDecl>(CurDecl))
2364 FunctionKind = 1;
2365 else if (isa<CXXConstructorDecl>(CurDecl))
2366 FunctionKind = 2;
2367 else if (isa<CXXDestructorDecl>(CurDecl))
2368 FunctionKind = 3;
2369
2370 Diag(ReturnLoc, diag::err_return_init_list)
2371 << CurDecl->getDeclName() << FunctionKind
2372 << RetValExp->getSourceRange();
2373
2374 // Drop the expression.
2375 RetValExp = 0;
2376 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002377 // C99 6.8.6.4p1 (ext_ since GCC warns)
2378 unsigned D = diag::ext_return_has_expr;
2379 if (RetValExp->getType()->isVoidType())
2380 D = diag::ext_return_has_void_expr;
2381 else {
2382 ExprResult Result = Owned(RetValExp);
2383 Result = IgnoredValueConversions(Result.take());
2384 if (Result.isInvalid())
2385 return StmtError();
2386 RetValExp = Result.take();
2387 RetValExp = ImpCastExprToType(RetValExp,
2388 Context.VoidTy, CK_ToVoid).take();
2389 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002390
Nick Lewycky8d794612011-06-01 07:44:31 +00002391 // return (some void expression); is legal in C++.
2392 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002393 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002394 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002395
2396 int FunctionKind = 0;
2397 if (isa<ObjCMethodDecl>(CurDecl))
2398 FunctionKind = 1;
2399 else if (isa<CXXConstructorDecl>(CurDecl))
2400 FunctionKind = 2;
2401 else if (isa<CXXDestructorDecl>(CurDecl))
2402 FunctionKind = 3;
2403
Nick Lewycky8d794612011-06-01 07:44:31 +00002404 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002405 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002406 << RetValExp->getSourceRange();
2407 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002408 }
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Sebastian Redl33deb352012-02-22 10:50:08 +00002410 if (RetValExp) {
2411 CheckImplicitConversions(RetValExp, ReturnLoc);
2412 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002415
Douglas Gregor5077c382010-05-15 06:01:05 +00002416 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2417 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002418 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2419 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002420 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002421
2422 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002423 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002424 else
Chris Lattner08631c52008-11-23 21:45:46 +00002425 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002426 Result = new (Context) ReturnStmt(ReturnLoc);
2427 } else {
2428 const VarDecl *NRVOCandidate = 0;
2429 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2430 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002431
Eli Friedman38ac2432012-03-30 01:13:43 +00002432 if (!RelatedRetType.isNull()) {
2433 // If we have a related result type, perform an extra conversion here.
2434 // FIXME: The diagnostics here don't really describe what is happening.
2435 InitializedEntity Entity =
2436 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002437
Eli Friedman38ac2432012-03-30 01:13:43 +00002438 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2439 RetValExp);
2440 if (Res.isInvalid()) {
2441 // FIXME: Cleanup temporaries here, anyway?
2442 return StmtError();
2443 }
2444 RetValExp = Res.takeAs<Expr>();
2445 }
2446
Douglas Gregor5077c382010-05-15 06:01:05 +00002447 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2448 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2449 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002450
John McCall856d3792011-06-16 23:24:51 +00002451 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002452 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002453 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002454 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002455 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002456 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002457 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002458 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002459 if (Res.isInvalid()) {
2460 // FIXME: Cleanup temporaries here, anyway?
2461 return StmtError();
2462 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002463
Douglas Gregor5077c382010-05-15 06:01:05 +00002464 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002465 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002466 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002468
John McCallb4eb64d2010-10-08 02:01:28 +00002469 if (RetValExp) {
2470 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00002471 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00002472 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002473 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002474 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002475
2476 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002477 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002478 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002479 !CurContext->isDependentContext())
2480 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002481
Douglas Gregor5077c382010-05-15 06:01:05 +00002482 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002483}
2484
Chris Lattner810f6d52009-03-13 17:38:01 +00002485/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2486/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2487/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2488/// provide a strong guidance to not use it.
2489///
2490/// This method checks to see if the argument is an acceptable l-value and
2491/// returns false if it is a case we can handle.
2492static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00002493 // Type dependent expressions will be checked during instantiation.
2494 if (E->isTypeDependent())
2495 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002496
John McCall7eb0a9e2010-11-24 05:12:34 +00002497 if (E->isLValue())
Chris Lattner810f6d52009-03-13 17:38:01 +00002498 return false; // Cool, this is an lvalue.
2499
2500 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2501 // are supposed to allow.
2502 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall7eb0a9e2010-11-24 05:12:34 +00002503 if (E != E2 && E2->isLValue()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002504 if (!S.getLangOpts().HeinousExtensions)
Chris Lattner810f6d52009-03-13 17:38:01 +00002505 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2506 << E->getSourceRange();
2507 else
2508 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2509 << E->getSourceRange();
2510 // Accept, even if we emitted an error diagnostic.
2511 return false;
2512 }
2513
2514 // None of the above, just randomly invalid non-lvalue.
2515 return true;
2516}
2517
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002518/// isOperandMentioned - Return true if the specified operand # is mentioned
2519/// anywhere in the decomposed asm string.
2520static bool isOperandMentioned(unsigned OpNo,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002521 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002522 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2523 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2524 if (!Piece.isOperand()) continue;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002525
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002526 // If this is a reference to the input and if the input was the smaller
2527 // one, then we have to reject this asm.
2528 if (Piece.getOperandNo() == OpNo)
2529 return true;
2530 }
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002531 return false;
2532}
Chris Lattner810f6d52009-03-13 17:38:01 +00002533
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002534StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2535 bool IsVolatile, unsigned NumOutputs,
2536 unsigned NumInputs, IdentifierInfo **Names,
2537 MultiExprArg constraints, MultiExprArg exprs,
2538 Expr *asmString, MultiExprArg clobbers,
2539 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002540 unsigned NumClobbers = clobbers.size();
2541 StringLiteral **Constraints =
2542 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00002543 Expr **Exprs = exprs.get();
2544 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00002545 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2546
Chris Lattner5f9e2722011-07-23 10:55:15 +00002547 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00002548
Chris Lattner1708b962008-08-18 19:55:17 +00002549 // The parser verifies that there is a string literal here.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002550 if (!AsmString->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002551 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2552 << AsmString->getSourceRange());
2553
Chris Lattner1708b962008-08-18 19:55:17 +00002554 for (unsigned i = 0; i != NumOutputs; i++) {
2555 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002556 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002557 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2558 << Literal->getSourceRange());
2559
Chris Lattner5f9e2722011-07-23 10:55:15 +00002560 StringRef OutputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002561 if (Names[i])
2562 OutputName = Names[i]->getName();
2563
2564 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002565 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002566 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002567 diag::err_asm_invalid_output_constraint)
2568 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00002569
Anders Carlssond04c6e22007-11-27 04:11:28 +00002570 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00002571 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00002572 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00002573 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002574 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00002575 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002576 }
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Chris Lattner44def072009-04-26 07:16:29 +00002578 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002579 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002580
Chris Lattner5f9e2722011-07-23 10:55:15 +00002581 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner806503f2009-05-03 05:55:43 +00002582
Anders Carlsson04728b72007-11-23 19:43:50 +00002583 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00002584 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002585 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002586 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2587 << Literal->getSourceRange());
2588
Chris Lattner5f9e2722011-07-23 10:55:15 +00002589 StringRef InputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002590 if (Names[i])
2591 InputName = Names[i]->getName();
2592
2593 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002594 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00002595 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002596 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002597 diag::err_asm_invalid_input_constraint)
2598 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00002599 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002600
Eli Friedman72056a22009-05-03 07:49:42 +00002601 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00002602
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002603 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00002604 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00002605 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00002606 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002607 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00002608 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002609 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002610 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002611
Chris Lattner44def072009-04-26 07:16:29 +00002612 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002613 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00002614 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002615 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00002616 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002617 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002618 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002619 }
Mike Stump1eb44332009-09-09 15:08:12 +00002620
John Wiegley429bb272011-04-08 18:41:53 +00002621 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2622 if (Result.isInvalid())
2623 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002624
John Wiegley429bb272011-04-08 18:41:53 +00002625 Exprs[i] = Result.take();
Chris Lattner806503f2009-05-03 05:55:43 +00002626 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002627 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002628
Anders Carlsson6fa90862007-11-25 00:25:21 +00002629 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00002630 for (unsigned i = 0; i != NumClobbers; i++) {
2631 StringLiteral *Literal = Clobbers[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002632 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002633 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2634 << Literal->getSourceRange());
2635
Chris Lattner5f9e2722011-07-23 10:55:15 +00002636 StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00002637
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002638 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002639 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00002640 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00002641 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002642
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002643 AsmStmt *NS =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002644 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2645 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson966146e2010-01-30 23:19:41 +00002646 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002647 // Validate the asm string, ensuring it makes sense given the operands we
2648 // have.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002649 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002650 unsigned DiagOffs;
2651 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00002652 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2653 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002654 return StmtError();
2655 }
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Chris Lattner806503f2009-05-03 05:55:43 +00002657 // Validate tied input operands for type mismatches.
2658 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2659 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Chris Lattner806503f2009-05-03 05:55:43 +00002661 // If this is a tied constraint, verify that the output and input have
2662 // either exactly the same type, or that they are int/ptr operands with the
2663 // same size (int/long, int*/long, are ok etc).
2664 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Chris Lattner806503f2009-05-03 05:55:43 +00002666 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner935f0f02011-02-21 22:09:29 +00002667 unsigned InputOpNo = i+NumOutputs;
Chris Lattnerf69fcae2009-05-03 07:04:21 +00002668 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner935f0f02011-02-21 22:09:29 +00002669 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedmanf45b3572011-09-14 19:20:00 +00002670
2671 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2672 continue;
2673
Chris Lattner7adaa182009-05-03 05:59:17 +00002674 QualType InTy = InputExpr->getType();
2675 QualType OutTy = OutputExpr->getType();
2676 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00002677 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Chris Lattneraab64d02010-04-23 17:27:29 +00002679 // Decide if the input and output are in the same domain (integer/ptr or
2680 // floating point.
2681 enum AsmDomain {
2682 AD_Int, AD_FP, AD_Other
2683 } InputDomain, OutputDomain;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002684
Chris Lattneraab64d02010-04-23 17:27:29 +00002685 if (InTy->isIntegerType() || InTy->isPointerType())
2686 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002687 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002688 InputDomain = AD_FP;
2689 else
2690 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Chris Lattneraab64d02010-04-23 17:27:29 +00002692 if (OutTy->isIntegerType() || OutTy->isPointerType())
2693 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002694 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002695 OutputDomain = AD_FP;
2696 else
2697 OutputDomain = AD_Other;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002698
Chris Lattneraab64d02010-04-23 17:27:29 +00002699 // They are ok if they are the same size and in the same domain. This
2700 // allows tying things like:
2701 // void* to int*
2702 // void* to int if they are the same size.
2703 // double to long double if they are the same size.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002704 //
Chris Lattneraab64d02010-04-23 17:27:29 +00002705 uint64_t OutSize = Context.getTypeSize(OutTy);
2706 uint64_t InSize = Context.getTypeSize(InTy);
2707 if (OutSize == InSize && InputDomain == OutputDomain &&
2708 InputDomain != AD_Other)
2709 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710
Chris Lattneraab64d02010-04-23 17:27:29 +00002711 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002712 // then we can promote the smaller one to a larger input and the asm string
2713 // won't notice.
Chris Lattneraab64d02010-04-23 17:27:29 +00002714 bool SmallerValueMentioned = false;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002715
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002716 // If this is a reference to the input and if the input was the smaller
2717 // one, then we have to reject this asm.
Chris Lattner935f0f02011-02-21 22:09:29 +00002718 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002719 // This is a use in the asm string of the smaller operand. Since we
2720 // codegen this by promoting to a wider value, the asm will get printed
2721 // "wrong".
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002722 SmallerValueMentioned |= InSize < OutSize;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002723 }
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002724 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002725 // If this is a reference to the output, and if the output is the larger
2726 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002727 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner806503f2009-05-03 05:55:43 +00002728 }
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Chris Lattneraab64d02010-04-23 17:27:29 +00002730 // If the smaller value wasn't mentioned in the asm string, and if the
2731 // output was a register, just extend the shorter one to the size of the
2732 // larger one.
2733 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2734 OutputConstraintInfos[TiedTo].allowsRegister())
2735 continue;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002736
Chris Lattner935f0f02011-02-21 22:09:29 +00002737 // Either both of the operands were mentioned or the smaller one was
2738 // mentioned. One more special case that we'll allow: if the tied input is
2739 // integer, unmentioned, and is a constant, then we'll allow truncating it
2740 // down to the size of the destination.
2741 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2742 !isOperandMentioned(InputOpNo, Pieces) &&
2743 InputExpr->isEvaluatable(Context)) {
John McCall4da89c82011-05-10 23:39:47 +00002744 CastKind castKind =
2745 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2746 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner935f0f02011-02-21 22:09:29 +00002747 Exprs[InputOpNo] = InputExpr;
2748 NS->setInputExpr(i, InputExpr);
2749 continue;
2750 }
Chad Rosier8e1e0542012-06-20 18:51:04 +00002751
Chris Lattnerc1f3b282009-05-03 06:50:40 +00002752 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00002753 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00002754 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00002755 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00002756 return StmtError();
2757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002759 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00002760}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002761
Chad Rosiere696b692012-08-08 18:22:06 +00002762// needSpaceAsmToken - This function handles whitespace around asm punctuation.
2763// Returns true if a space should be emitted.
Chad Rosiere696b692012-08-08 18:22:06 +00002764static inline bool needSpaceAsmToken(Token currTok) {
2765 static Token prevTok;
2766
2767 // No need for space after prevToken.
2768 switch(prevTok.getKind()) {
2769 default:
2770 break;
2771 case tok::l_square:
2772 case tok::r_square:
2773 case tok::l_brace:
2774 case tok::r_brace:
2775 case tok::colon:
2776 prevTok = currTok;
2777 return false;
2778 }
2779
2780 // No need for a space before currToken.
2781 switch(currTok.getKind()) {
2782 default:
2783 break;
2784 case tok::l_square:
2785 case tok::r_square:
2786 case tok::l_brace:
2787 case tok::r_brace:
2788 case tok::comma:
2789 case tok::colon:
2790 prevTok = currTok;
2791 return false;
2792 }
2793 prevTok = currTok;
2794 return true;
2795}
2796
2797static std::string PatchMSAsmString(Sema &SemaRef, bool &IsSimple,
2798 SourceLocation AsmLoc,
2799 ArrayRef<Token> AsmToks,
2800 const TargetInfo &TI) {
Chad Rosier871ee562012-08-08 21:08:20 +00002801 // Assume simple asm stmt until we parse a non-register identifer.
2802 IsSimple = true;
2803
Chad Rosier77c7b0a2012-08-08 21:42:11 +00002804 if (AsmToks.empty())
Chad Rosierb64f3102012-08-08 20:37:31 +00002805 return "";
2806
Chad Rosiere696b692012-08-08 18:22:06 +00002807 std::string Res;
2808 IdentifierInfo *II = AsmToks[0].getIdentifierInfo();
2809 Res = II->getName().str();
2810
Chad Rosiere696b692012-08-08 18:22:06 +00002811 // Check the operands.
2812 for (unsigned i = 1, e = AsmToks.size(); i != e; ++i) {
2813 if (needSpaceAsmToken(AsmToks[i]))
2814 Res += " ";
2815
2816 switch (AsmToks[i].getKind()) {
2817 default:
2818 //llvm_unreachable("Unknown token.");
2819 break;
2820 case tok::comma: Res += ","; break;
2821 case tok::colon: Res += ":"; break;
2822 case tok::l_square: Res += "["; break;
2823 case tok::r_square: Res += "]"; break;
2824 case tok::l_brace: Res += "{"; break;
2825 case tok::r_brace: Res += "}"; break;
2826 case tok::numeric_constant: {
2827 SmallString<32> TokenBuf;
2828 TokenBuf.resize(32);
2829 bool StringInvalid = false;
2830 const char *ThisTokBuf = &TokenBuf[0];
2831 unsigned ThisTokLen =
2832 Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2833 SemaRef.getLangOpts(), &StringInvalid);
2834 Res += StringRef(ThisTokBuf, ThisTokLen);
2835 break;
2836 }
2837 case tok::identifier: {
2838 II = AsmToks[i].getIdentifierInfo();
2839 StringRef Name = II->getName();
2840
2841 // Valid registers don't need modification.
2842 if (TI.isValidGCCRegisterName(Name)) {
2843 Res += Name;
2844 break;
2845 }
2846
2847 // TODO: Lookup the identifier.
2848 IsSimple = false;
2849 }
2850 } // AsmToks[i].getKind()
2851 }
2852 return Res;
2853}
2854
Chad Rosier62f22b82012-08-08 19:48:07 +00002855// Build the unmodified MSAsmString.
2856static std::string buildMSAsmString(Sema &SemaRef,
2857 ArrayRef<Token> AsmToks,
2858 ArrayRef<unsigned> LineEnds) {
Chad Rosier77c7b0a2012-08-08 21:42:11 +00002859 if (AsmToks.empty())
Chad Rosierb64f3102012-08-08 20:37:31 +00002860 return "";
2861
Chad Rosier62f22b82012-08-08 19:48:07 +00002862 SmallString<512> Asm;
2863 SmallString<512> TokenBuf;
2864 TokenBuf.resize(512);
2865 unsigned AsmLineNum = 0;
2866 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
2867 const char *ThisTokBuf = &TokenBuf[0];
2868 bool StringInvalid = false;
2869 unsigned ThisTokLen =
2870 Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2871 SemaRef.getLangOpts(), &StringInvalid);
2872 if (i && (!AsmLineNum || i != LineEnds[AsmLineNum-1]) &&
2873 needSpaceAsmToken(AsmToks[i]))
2874 Asm += ' ';
2875 Asm += StringRef(ThisTokBuf, ThisTokLen);
2876 if (i + 1 == LineEnds[AsmLineNum] && i + 1 != AsmToks.size()) {
2877 Asm += '\n';
2878 ++AsmLineNum;
2879 }
2880 }
2881 return Asm.c_str();
2882}
2883
Chad Rosier8cd64b42012-06-11 20:47:18 +00002884StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
Chad Rosier79efe242012-08-07 00:29:06 +00002885 ArrayRef<Token> AsmToks,
Chad Rosier62f22b82012-08-08 19:48:07 +00002886 ArrayRef<unsigned> LineEnds,
Chad Rosier8cd64b42012-06-11 20:47:18 +00002887 SourceLocation EndLoc) {
Chad Rosier52e4ed92012-06-20 18:28:37 +00002888 // MS-style inline assembly is not fully supported, so emit a warning.
2889 Diag(AsmLoc, diag::warn_unsupported_msasm);
2890
Chad Rosier4144f902012-08-09 20:52:43 +00002891 // Empty asm statements don't need to instantiate the AsmParser, etc.
2892 if (AsmToks.empty()) {
Chad Rosiercace2102012-08-09 21:06:32 +00002893 StringRef AsmString;
Chad Rosier4144f902012-08-09 20:52:43 +00002894 MSAsmStmt *NS =
2895 new (Context) MSAsmStmt(Context, AsmLoc, /* IsSimple */ true,
2896 /* IsVolatile */ true, AsmToks, LineEnds,
2897 AsmString, EndLoc);
2898 return Owned(NS);
2899 }
2900
Chad Rosier62f22b82012-08-08 19:48:07 +00002901 std::string AsmString = buildMSAsmString(*this, AsmToks, LineEnds);
2902
Chad Rosiere696b692012-08-08 18:22:06 +00002903 bool IsSimple;
2904 // Rewrite operands to appease the AsmParser.
2905 std::string PatchedAsmString =
2906 PatchMSAsmString(*this, IsSimple, AsmLoc, AsmToks, Context.getTargetInfo());
2907
Chad Rosierbe3d0db2012-08-09 17:33:11 +00002908 // Initialize targets and assembly printers/parsers.
2909 llvm::InitializeAllTargetInfos();
2910 llvm::InitializeAllTargetMCs();
2911 llvm::InitializeAllAsmParsers();
2912
Chad Rosier47f49892012-08-09 20:47:38 +00002913 // Get the target specific parser.
2914 std::string Error;
2915 const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
2916 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
2917
2918 llvm::SourceMgr SrcMgr;
2919 llvm::MemoryBuffer *Buffer =
2920 llvm::MemoryBuffer::getMemBuffer(PatchedAsmString, "<inline asm>");
2921
2922 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2923 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2924
2925 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
2926 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2927 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2928 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
2929 OwningPtr<llvm::MCSubtargetInfo>
2930 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2931
2932 OwningPtr<llvm::MCStreamer> Str;
2933 OwningPtr<llvm::MCAsmParser>
2934 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
2935 OwningPtr<llvm::MCTargetAsmParser>
2936 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
2937
2938 // Change to the Intel syntax.
2939 Parser->setAssemblerDialect(1);
2940 Parser->setTargetParser(*TargetParser.get());
2941
Chad Rosier8cd64b42012-06-11 20:47:18 +00002942 MSAsmStmt *NS =
Chad Rosiere696b692012-08-08 18:22:06 +00002943 new (Context) MSAsmStmt(Context, AsmLoc, IsSimple, /* IsVolatile */ true,
Chad Rosier62f22b82012-08-08 19:48:07 +00002944 AsmToks, LineEnds, AsmString, EndLoc);
Chad Rosier8cd64b42012-06-11 20:47:18 +00002945
2946 return Owned(NS);
2947}
2948
John McCall60d7b3a2010-08-24 06:29:42 +00002949StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002950Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002951 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002952 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002953 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002954 if (Var && Var->isInvalidDecl())
2955 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002956
John McCall9ae2f072010-08-23 23:25:46 +00002957 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002958}
2959
John McCall60d7b3a2010-08-24 06:29:42 +00002960StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002961Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2962 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002963}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002964
John McCall60d7b3a2010-08-24 06:29:42 +00002965StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002966Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002967 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002968 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002969 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2970
John McCall781472f2010-08-25 08:40:02 +00002971 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002972 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002973 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2974 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002975 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002976 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002977}
2978
John McCalld1376ee2012-05-08 21:41:25 +00002979StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002980 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002981 ExprResult Result = DefaultLvalueConversion(Throw);
2982 if (Result.isInvalid())
2983 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002984
John McCalld1376ee2012-05-08 21:41:25 +00002985 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregord1377b22010-04-22 21:44:01 +00002986 QualType ThrowType = Throw->getType();
2987 // Make sure the expression type is an ObjC pointer or "void *".
2988 if (!ThrowType->isDependentType() &&
2989 !ThrowType->isObjCObjectPointerType()) {
2990 const PointerType *PT = ThrowType->getAs<PointerType>();
2991 if (!PT || !PT->getPointeeType()->isVoidType())
2992 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2993 << Throw->getType() << Throw->getSourceRange());
2994 }
2995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002996
John McCall9ae2f072010-08-23 23:25:46 +00002997 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002998}
2999
John McCall60d7b3a2010-08-24 06:29:42 +00003000StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003001Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00003002 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003003 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00003004 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3005
John McCall9ae2f072010-08-23 23:25:46 +00003006 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00003007 // @throw without an expression designates a rethrow (which much occur
3008 // in the context of an @catch clause).
3009 Scope *AtCatchParent = CurScope;
3010 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3011 AtCatchParent = AtCatchParent->getParent();
3012 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00003013 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003014 }
John McCall9ae2f072010-08-23 23:25:46 +00003015 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00003016}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00003017
John McCall07524032011-07-27 21:50:02 +00003018ExprResult
3019Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3020 ExprResult result = DefaultLvalueConversion(operand);
3021 if (result.isInvalid())
3022 return ExprError();
3023 operand = result.take();
3024
3025 // Make sure the expression type is an ObjC pointer or "void *".
3026 QualType type = operand->getType();
3027 if (!type->isDependentType() &&
3028 !type->isObjCObjectPointerType()) {
3029 const PointerType *pointerType = type->getAs<PointerType>();
3030 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3031 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3032 << type << operand->getSourceRange();
3033 }
3034
3035 // The operand to @synchronized is a full-expression.
3036 return MaybeCreateExprWithCleanups(operand);
3037}
3038
John McCall60d7b3a2010-08-24 06:29:42 +00003039StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00003040Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3041 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00003042 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00003043 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00003044 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00003045}
Sebastian Redl4b07b292008-12-22 19:15:10 +00003046
3047/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3048/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00003049StmtResult
John McCalld226f652010-08-21 09:40:31 +00003050Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00003051 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003052 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003053 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00003054 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00003055 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003056}
Sebastian Redl8351da02008-12-22 21:35:02 +00003057
John McCallf85e1932011-06-15 23:02:42 +00003058StmtResult
3059Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3060 getCurFunction()->setHasBranchProtectedScope();
3061 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3062}
3063
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003064namespace {
3065
Sebastian Redlc447aba2009-07-29 17:15:45 +00003066class TypeWithHandler {
3067 QualType t;
3068 CXXCatchStmt *stmt;
3069public:
3070 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3071 : t(type), stmt(statement) {}
3072
John McCall0953e762009-09-24 19:53:00 +00003073 // An arbitrary order is fine as long as it places identical
3074 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00003075 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00003076 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003077 return true;
John McCall0953e762009-09-24 19:53:00 +00003078 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003079 return false;
3080 else
3081 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3082 }
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Sebastian Redlc447aba2009-07-29 17:15:45 +00003084 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00003085 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00003086 }
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Sebastian Redlc447aba2009-07-29 17:15:45 +00003088 CXXCatchStmt *getCatchStmt() const { return stmt; }
3089 SourceLocation getTypeSpecStartLoc() const {
3090 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3091 }
3092};
3093
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003094}
3095
Sebastian Redl8351da02008-12-22 21:35:02 +00003096/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3097/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00003098StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00003099Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00003100 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00003101 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00003102 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00003103 !getSourceManager().isInSystemHeader(TryLoc))
3104 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00003105
Sebastian Redl8351da02008-12-22 21:35:02 +00003106 unsigned NumHandlers = RawHandlers.size();
3107 assert(NumHandlers > 0 &&
3108 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00003109 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00003110
Chris Lattner5f9e2722011-07-23 10:55:15 +00003111 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00003112
3113 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003114 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00003115 if (!Handler->getExceptionDecl()) {
3116 if (i < NumHandlers - 1)
3117 return StmtError(Diag(Handler->getLocStart(),
3118 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Sebastian Redlc447aba2009-07-29 17:15:45 +00003120 continue;
3121 }
Mike Stump1eb44332009-09-09 15:08:12 +00003122
Sebastian Redlc447aba2009-07-29 17:15:45 +00003123 const QualType CaughtType = Handler->getCaughtType();
3124 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3125 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00003126 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00003127
3128 // Detect handlers for the same type as an earlier one.
3129 if (NumHandlers > 1) {
3130 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Sebastian Redlc447aba2009-07-29 17:15:45 +00003132 TypeWithHandler prev = TypesWithHandlers[0];
3133 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3134 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Sebastian Redlc447aba2009-07-29 17:15:45 +00003136 if (curr == prev) {
3137 Diag(curr.getTypeSpecStartLoc(),
3138 diag::warn_exception_caught_by_earlier_handler)
3139 << curr.getCatchStmt()->getCaughtType().getAsString();
3140 Diag(prev.getTypeSpecStartLoc(),
3141 diag::note_previous_exception_handler)
3142 << prev.getCatchStmt()->getCaughtType().getAsString();
3143 }
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Sebastian Redlc447aba2009-07-29 17:15:45 +00003145 prev = curr;
3146 }
3147 }
Mike Stump1eb44332009-09-09 15:08:12 +00003148
John McCall781472f2010-08-25 08:40:02 +00003149 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00003150
Sebastian Redl8351da02008-12-22 21:35:02 +00003151 // FIXME: We should detect handlers that cannot catch anything because an
3152 // earlier handler catches a superclass. Need to find a method that is not
3153 // quadratic for this.
3154 // Neither of these are explicitly forbidden, but every compiler detects them
3155 // and warns.
3156
John McCall9ae2f072010-08-23 23:25:46 +00003157 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00003158 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00003159}
John Wiegley28bbe4b2011-04-28 01:08:34 +00003160
3161StmtResult
3162Sema::ActOnSEHTryBlock(bool IsCXXTry,
3163 SourceLocation TryLoc,
3164 Stmt *TryBlock,
3165 Stmt *Handler) {
3166 assert(TryBlock && Handler);
3167
3168 getCurFunction()->setHasBranchProtectedScope();
3169
3170 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3171}
3172
3173StmtResult
3174Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3175 Expr *FilterExpr,
3176 Stmt *Block) {
3177 assert(FilterExpr && Block);
3178
3179 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00003180 return StmtError(Diag(FilterExpr->getExprLoc(),
3181 diag::err_filter_expression_integral)
3182 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00003183 }
3184
3185 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3186}
3187
3188StmtResult
3189Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3190 Stmt *Block) {
3191 assert(Block);
3192 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3193}
Douglas Gregorba0513d2011-10-25 01:33:02 +00003194
3195StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3196 bool IsIfExists,
3197 NestedNameSpecifierLoc QualifierLoc,
3198 DeclarationNameInfo NameInfo,
3199 Stmt *Nested)
3200{
3201 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3202 QualifierLoc, NameInfo,
3203 cast<CompoundStmt>(Nested));
3204}
3205
3206
3207StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3208 bool IsIfExists,
3209 CXXScopeSpec &SS,
3210 UnqualifiedId &Name,
3211 Stmt *Nested) {
3212 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3213 SS.getWithLocInContext(Context),
3214 GetNameFromUnqualifiedId(Name),
3215 Nested);
3216}