1*67e74705SXin Li //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements semantic analysis for statements.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
15*67e74705SXin Li #include "clang/AST/ASTContext.h"
16*67e74705SXin Li #include "clang/AST/ASTDiagnostic.h"
17*67e74705SXin Li #include "clang/AST/CharUnits.h"
18*67e74705SXin Li #include "clang/AST/CXXInheritance.h"
19*67e74705SXin Li #include "clang/AST/DeclObjC.h"
20*67e74705SXin Li #include "clang/AST/EvaluatedExprVisitor.h"
21*67e74705SXin Li #include "clang/AST/ExprCXX.h"
22*67e74705SXin Li #include "clang/AST/ExprObjC.h"
23*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
24*67e74705SXin Li #include "clang/AST/StmtCXX.h"
25*67e74705SXin Li #include "clang/AST/StmtObjC.h"
26*67e74705SXin Li #include "clang/AST/TypeLoc.h"
27*67e74705SXin Li #include "clang/AST/TypeOrdering.h"
28*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
29*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
30*67e74705SXin Li #include "clang/Sema/Initialization.h"
31*67e74705SXin Li #include "clang/Sema/Lookup.h"
32*67e74705SXin Li #include "clang/Sema/Scope.h"
33*67e74705SXin Li #include "clang/Sema/ScopeInfo.h"
34*67e74705SXin Li #include "llvm/ADT/ArrayRef.h"
35*67e74705SXin Li #include "llvm/ADT/DenseMap.h"
36*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
37*67e74705SXin Li #include "llvm/ADT/SmallPtrSet.h"
38*67e74705SXin Li #include "llvm/ADT/SmallString.h"
39*67e74705SXin Li #include "llvm/ADT/SmallVector.h"
40*67e74705SXin Li
41*67e74705SXin Li using namespace clang;
42*67e74705SXin Li using namespace sema;
43*67e74705SXin Li
ActOnExprStmt(ExprResult FE)44*67e74705SXin Li StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45*67e74705SXin Li if (FE.isInvalid())
46*67e74705SXin Li return StmtError();
47*67e74705SXin Li
48*67e74705SXin Li FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49*67e74705SXin Li /*DiscardedValue*/ true);
50*67e74705SXin Li if (FE.isInvalid())
51*67e74705SXin Li return StmtError();
52*67e74705SXin Li
53*67e74705SXin Li // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54*67e74705SXin Li // void expression for its side effects. Conversion to void allows any
55*67e74705SXin Li // operand, even incomplete types.
56*67e74705SXin Li
57*67e74705SXin Li // Same thing in for stmt first clause (when expr) and third clause.
58*67e74705SXin Li return StmtResult(FE.getAs<Stmt>());
59*67e74705SXin Li }
60*67e74705SXin Li
61*67e74705SXin Li
ActOnExprStmtError()62*67e74705SXin Li StmtResult Sema::ActOnExprStmtError() {
63*67e74705SXin Li DiscardCleanupsInEvaluationContext();
64*67e74705SXin Li return StmtError();
65*67e74705SXin Li }
66*67e74705SXin Li
ActOnNullStmt(SourceLocation SemiLoc,bool HasLeadingEmptyMacro)67*67e74705SXin Li StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
68*67e74705SXin Li bool HasLeadingEmptyMacro) {
69*67e74705SXin Li return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
70*67e74705SXin Li }
71*67e74705SXin Li
ActOnDeclStmt(DeclGroupPtrTy dg,SourceLocation StartLoc,SourceLocation EndLoc)72*67e74705SXin Li StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73*67e74705SXin Li SourceLocation EndLoc) {
74*67e74705SXin Li DeclGroupRef DG = dg.get();
75*67e74705SXin Li
76*67e74705SXin Li // If we have an invalid decl, just return an error.
77*67e74705SXin Li if (DG.isNull()) return StmtError();
78*67e74705SXin Li
79*67e74705SXin Li return new (Context) DeclStmt(DG, StartLoc, EndLoc);
80*67e74705SXin Li }
81*67e74705SXin Li
ActOnForEachDeclStmt(DeclGroupPtrTy dg)82*67e74705SXin Li void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
83*67e74705SXin Li DeclGroupRef DG = dg.get();
84*67e74705SXin Li
85*67e74705SXin Li // If we don't have a declaration, or we have an invalid declaration,
86*67e74705SXin Li // just return.
87*67e74705SXin Li if (DG.isNull() || !DG.isSingleDecl())
88*67e74705SXin Li return;
89*67e74705SXin Li
90*67e74705SXin Li Decl *decl = DG.getSingleDecl();
91*67e74705SXin Li if (!decl || decl->isInvalidDecl())
92*67e74705SXin Li return;
93*67e74705SXin Li
94*67e74705SXin Li // Only variable declarations are permitted.
95*67e74705SXin Li VarDecl *var = dyn_cast<VarDecl>(decl);
96*67e74705SXin Li if (!var) {
97*67e74705SXin Li Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98*67e74705SXin Li decl->setInvalidDecl();
99*67e74705SXin Li return;
100*67e74705SXin Li }
101*67e74705SXin Li
102*67e74705SXin Li // foreach variables are never actually initialized in the way that
103*67e74705SXin Li // the parser came up with.
104*67e74705SXin Li var->setInit(nullptr);
105*67e74705SXin Li
106*67e74705SXin Li // In ARC, we don't need to retain the iteration variable of a fast
107*67e74705SXin Li // enumeration loop. Rather than actually trying to catch that
108*67e74705SXin Li // during declaration processing, we remove the consequences here.
109*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount) {
110*67e74705SXin Li QualType type = var->getType();
111*67e74705SXin Li
112*67e74705SXin Li // Only do this if we inferred the lifetime. Inferred lifetime
113*67e74705SXin Li // will show up as a local qualifier because explicit lifetime
114*67e74705SXin Li // should have shown up as an AttributedType instead.
115*67e74705SXin Li if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116*67e74705SXin Li // Add 'const' and mark the variable as pseudo-strong.
117*67e74705SXin Li var->setType(type.withConst());
118*67e74705SXin Li var->setARCPseudoStrong(true);
119*67e74705SXin Li }
120*67e74705SXin Li }
121*67e74705SXin Li }
122*67e74705SXin Li
123*67e74705SXin Li /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124*67e74705SXin Li /// For '==' and '!=', suggest fixits for '=' or '|='.
125*67e74705SXin Li ///
126*67e74705SXin Li /// Adding a cast to void (or other expression wrappers) will prevent the
127*67e74705SXin Li /// warning from firing.
DiagnoseUnusedComparison(Sema & S,const Expr * E)128*67e74705SXin Li static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
129*67e74705SXin Li SourceLocation Loc;
130*67e74705SXin Li bool IsNotEqual, CanAssign, IsRelational;
131*67e74705SXin Li
132*67e74705SXin Li if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
133*67e74705SXin Li if (!Op->isComparisonOp())
134*67e74705SXin Li return false;
135*67e74705SXin Li
136*67e74705SXin Li IsRelational = Op->isRelationalOp();
137*67e74705SXin Li Loc = Op->getOperatorLoc();
138*67e74705SXin Li IsNotEqual = Op->getOpcode() == BO_NE;
139*67e74705SXin Li CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
140*67e74705SXin Li } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
141*67e74705SXin Li switch (Op->getOperator()) {
142*67e74705SXin Li default:
143*67e74705SXin Li return false;
144*67e74705SXin Li case OO_EqualEqual:
145*67e74705SXin Li case OO_ExclaimEqual:
146*67e74705SXin Li IsRelational = false;
147*67e74705SXin Li break;
148*67e74705SXin Li case OO_Less:
149*67e74705SXin Li case OO_Greater:
150*67e74705SXin Li case OO_GreaterEqual:
151*67e74705SXin Li case OO_LessEqual:
152*67e74705SXin Li IsRelational = true;
153*67e74705SXin Li break;
154*67e74705SXin Li }
155*67e74705SXin Li
156*67e74705SXin Li Loc = Op->getOperatorLoc();
157*67e74705SXin Li IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158*67e74705SXin Li CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
159*67e74705SXin Li } else {
160*67e74705SXin Li // Not a typo-prone comparison.
161*67e74705SXin Li return false;
162*67e74705SXin Li }
163*67e74705SXin Li
164*67e74705SXin Li // Suppress warnings when the operator, suspicious as it may be, comes from
165*67e74705SXin Li // a macro expansion.
166*67e74705SXin Li if (S.SourceMgr.isMacroBodyExpansion(Loc))
167*67e74705SXin Li return false;
168*67e74705SXin Li
169*67e74705SXin Li S.Diag(Loc, diag::warn_unused_comparison)
170*67e74705SXin Li << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
171*67e74705SXin Li
172*67e74705SXin Li // If the LHS is a plausible entity to assign to, provide a fixit hint to
173*67e74705SXin Li // correct common typos.
174*67e74705SXin Li if (!IsRelational && CanAssign) {
175*67e74705SXin Li if (IsNotEqual)
176*67e74705SXin Li S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177*67e74705SXin Li << FixItHint::CreateReplacement(Loc, "|=");
178*67e74705SXin Li else
179*67e74705SXin Li S.Diag(Loc, diag::note_equality_comparison_to_assign)
180*67e74705SXin Li << FixItHint::CreateReplacement(Loc, "=");
181*67e74705SXin Li }
182*67e74705SXin Li
183*67e74705SXin Li return true;
184*67e74705SXin Li }
185*67e74705SXin Li
DiagnoseUnusedExprResult(const Stmt * S)186*67e74705SXin Li void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
187*67e74705SXin Li if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188*67e74705SXin Li return DiagnoseUnusedExprResult(Label->getSubStmt());
189*67e74705SXin Li
190*67e74705SXin Li const Expr *E = dyn_cast_or_null<Expr>(S);
191*67e74705SXin Li if (!E)
192*67e74705SXin Li return;
193*67e74705SXin Li
194*67e74705SXin Li // If we are in an unevaluated expression context, then there can be no unused
195*67e74705SXin Li // results because the results aren't expected to be used in the first place.
196*67e74705SXin Li if (isUnevaluatedContext())
197*67e74705SXin Li return;
198*67e74705SXin Li
199*67e74705SXin Li SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
200*67e74705SXin Li // In most cases, we don't want to warn if the expression is written in a
201*67e74705SXin Li // macro body, or if the macro comes from a system header. If the offending
202*67e74705SXin Li // expression is a call to a function with the warn_unused_result attribute,
203*67e74705SXin Li // we warn no matter the location. Because of the order in which the various
204*67e74705SXin Li // checks need to happen, we factor out the macro-related test here.
205*67e74705SXin Li bool ShouldSuppress =
206*67e74705SXin Li SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207*67e74705SXin Li SourceMgr.isInSystemMacro(ExprLoc);
208*67e74705SXin Li
209*67e74705SXin Li const Expr *WarnExpr;
210*67e74705SXin Li SourceLocation Loc;
211*67e74705SXin Li SourceRange R1, R2;
212*67e74705SXin Li if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
213*67e74705SXin Li return;
214*67e74705SXin Li
215*67e74705SXin Li // If this is a GNU statement expression expanded from a macro, it is probably
216*67e74705SXin Li // unused because it is a function-like macro that can be used as either an
217*67e74705SXin Li // expression or statement. Don't warn, because it is almost certainly a
218*67e74705SXin Li // false positive.
219*67e74705SXin Li if (isa<StmtExpr>(E) && Loc.isMacroID())
220*67e74705SXin Li return;
221*67e74705SXin Li
222*67e74705SXin Li // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223*67e74705SXin Li // That macro is frequently used to suppress "unused parameter" warnings,
224*67e74705SXin Li // but its implementation makes clang's -Wunused-value fire. Prevent this.
225*67e74705SXin Li if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226*67e74705SXin Li SourceLocation SpellLoc = Loc;
227*67e74705SXin Li if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228*67e74705SXin Li return;
229*67e74705SXin Li }
230*67e74705SXin Li
231*67e74705SXin Li // Okay, we have an unused result. Depending on what the base expression is,
232*67e74705SXin Li // we might want to make a more specific diagnostic. Check for one of these
233*67e74705SXin Li // cases now.
234*67e74705SXin Li unsigned DiagID = diag::warn_unused_expr;
235*67e74705SXin Li if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
236*67e74705SXin Li E = Temps->getSubExpr();
237*67e74705SXin Li if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238*67e74705SXin Li E = TempExpr->getSubExpr();
239*67e74705SXin Li
240*67e74705SXin Li if (DiagnoseUnusedComparison(*this, E))
241*67e74705SXin Li return;
242*67e74705SXin Li
243*67e74705SXin Li E = WarnExpr;
244*67e74705SXin Li if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
245*67e74705SXin Li if (E->getType()->isVoidType())
246*67e74705SXin Li return;
247*67e74705SXin Li
248*67e74705SXin Li // If the callee has attribute pure, const, or warn_unused_result, warn with
249*67e74705SXin Li // a more specific message to make it clear what is happening. If the call
250*67e74705SXin Li // is written in a macro body, only warn if it has the warn_unused_result
251*67e74705SXin Li // attribute.
252*67e74705SXin Li if (const Decl *FD = CE->getCalleeDecl()) {
253*67e74705SXin Li if (const Attr *A = isa<FunctionDecl>(FD)
254*67e74705SXin Li ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255*67e74705SXin Li : FD->getAttr<WarnUnusedResultAttr>()) {
256*67e74705SXin Li Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
257*67e74705SXin Li return;
258*67e74705SXin Li }
259*67e74705SXin Li if (ShouldSuppress)
260*67e74705SXin Li return;
261*67e74705SXin Li if (FD->hasAttr<PureAttr>()) {
262*67e74705SXin Li Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263*67e74705SXin Li return;
264*67e74705SXin Li }
265*67e74705SXin Li if (FD->hasAttr<ConstAttr>()) {
266*67e74705SXin Li Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267*67e74705SXin Li return;
268*67e74705SXin Li }
269*67e74705SXin Li }
270*67e74705SXin Li } else if (ShouldSuppress)
271*67e74705SXin Li return;
272*67e74705SXin Li
273*67e74705SXin Li if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
274*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
275*67e74705SXin Li Diag(Loc, diag::err_arc_unused_init_message) << R1;
276*67e74705SXin Li return;
277*67e74705SXin Li }
278*67e74705SXin Li const ObjCMethodDecl *MD = ME->getMethodDecl();
279*67e74705SXin Li if (MD) {
280*67e74705SXin Li if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281*67e74705SXin Li Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
282*67e74705SXin Li return;
283*67e74705SXin Li }
284*67e74705SXin Li }
285*67e74705SXin Li } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286*67e74705SXin Li const Expr *Source = POE->getSyntacticForm();
287*67e74705SXin Li if (isa<ObjCSubscriptRefExpr>(Source))
288*67e74705SXin Li DiagID = diag::warn_unused_container_subscript_expr;
289*67e74705SXin Li else
290*67e74705SXin Li DiagID = diag::warn_unused_property_expr;
291*67e74705SXin Li } else if (const CXXFunctionalCastExpr *FC
292*67e74705SXin Li = dyn_cast<CXXFunctionalCastExpr>(E)) {
293*67e74705SXin Li if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
294*67e74705SXin Li isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
295*67e74705SXin Li return;
296*67e74705SXin Li }
297*67e74705SXin Li // Diagnose "(void*) blah" as a typo for "(void) blah".
298*67e74705SXin Li else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
299*67e74705SXin Li TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
300*67e74705SXin Li QualType T = TI->getType();
301*67e74705SXin Li
302*67e74705SXin Li // We really do want to use the non-canonical type here.
303*67e74705SXin Li if (T == Context.VoidPtrTy) {
304*67e74705SXin Li PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
305*67e74705SXin Li
306*67e74705SXin Li Diag(Loc, diag::warn_unused_voidptr)
307*67e74705SXin Li << FixItHint::CreateRemoval(TL.getStarLoc());
308*67e74705SXin Li return;
309*67e74705SXin Li }
310*67e74705SXin Li }
311*67e74705SXin Li
312*67e74705SXin Li if (E->isGLValue() && E->getType().isVolatileQualified()) {
313*67e74705SXin Li Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
314*67e74705SXin Li return;
315*67e74705SXin Li }
316*67e74705SXin Li
317*67e74705SXin Li DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
318*67e74705SXin Li }
319*67e74705SXin Li
ActOnStartOfCompoundStmt()320*67e74705SXin Li void Sema::ActOnStartOfCompoundStmt() {
321*67e74705SXin Li PushCompoundScope();
322*67e74705SXin Li }
323*67e74705SXin Li
ActOnFinishOfCompoundStmt()324*67e74705SXin Li void Sema::ActOnFinishOfCompoundStmt() {
325*67e74705SXin Li PopCompoundScope();
326*67e74705SXin Li }
327*67e74705SXin Li
getCurCompoundScope() const328*67e74705SXin Li sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
329*67e74705SXin Li return getCurFunction()->CompoundScopes.back();
330*67e74705SXin Li }
331*67e74705SXin Li
ActOnCompoundStmt(SourceLocation L,SourceLocation R,ArrayRef<Stmt * > Elts,bool isStmtExpr)332*67e74705SXin Li StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
333*67e74705SXin Li ArrayRef<Stmt *> Elts, bool isStmtExpr) {
334*67e74705SXin Li const unsigned NumElts = Elts.size();
335*67e74705SXin Li
336*67e74705SXin Li // If we're in C89 mode, check that we don't have any decls after stmts. If
337*67e74705SXin Li // so, emit an extension diagnostic.
338*67e74705SXin Li if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
339*67e74705SXin Li // Note that __extension__ can be around a decl.
340*67e74705SXin Li unsigned i = 0;
341*67e74705SXin Li // Skip over all declarations.
342*67e74705SXin Li for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
343*67e74705SXin Li /*empty*/;
344*67e74705SXin Li
345*67e74705SXin Li // We found the end of the list or a statement. Scan for another declstmt.
346*67e74705SXin Li for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
347*67e74705SXin Li /*empty*/;
348*67e74705SXin Li
349*67e74705SXin Li if (i != NumElts) {
350*67e74705SXin Li Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
351*67e74705SXin Li Diag(D->getLocation(), diag::ext_mixed_decls_code);
352*67e74705SXin Li }
353*67e74705SXin Li }
354*67e74705SXin Li // Warn about unused expressions in statements.
355*67e74705SXin Li for (unsigned i = 0; i != NumElts; ++i) {
356*67e74705SXin Li // Ignore statements that are last in a statement expression.
357*67e74705SXin Li if (isStmtExpr && i == NumElts - 1)
358*67e74705SXin Li continue;
359*67e74705SXin Li
360*67e74705SXin Li DiagnoseUnusedExprResult(Elts[i]);
361*67e74705SXin Li }
362*67e74705SXin Li
363*67e74705SXin Li // Check for suspicious empty body (null statement) in `for' and `while'
364*67e74705SXin Li // statements. Don't do anything for template instantiations, this just adds
365*67e74705SXin Li // noise.
366*67e74705SXin Li if (NumElts != 0 && !CurrentInstantiationScope &&
367*67e74705SXin Li getCurCompoundScope().HasEmptyLoopBodies) {
368*67e74705SXin Li for (unsigned i = 0; i != NumElts - 1; ++i)
369*67e74705SXin Li DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
370*67e74705SXin Li }
371*67e74705SXin Li
372*67e74705SXin Li return new (Context) CompoundStmt(Context, Elts, L, R);
373*67e74705SXin Li }
374*67e74705SXin Li
375*67e74705SXin Li StmtResult
ActOnCaseStmt(SourceLocation CaseLoc,Expr * LHSVal,SourceLocation DotDotDotLoc,Expr * RHSVal,SourceLocation ColonLoc)376*67e74705SXin Li Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
377*67e74705SXin Li SourceLocation DotDotDotLoc, Expr *RHSVal,
378*67e74705SXin Li SourceLocation ColonLoc) {
379*67e74705SXin Li assert(LHSVal && "missing expression in case statement");
380*67e74705SXin Li
381*67e74705SXin Li if (getCurFunction()->SwitchStack.empty()) {
382*67e74705SXin Li Diag(CaseLoc, diag::err_case_not_in_switch);
383*67e74705SXin Li return StmtError();
384*67e74705SXin Li }
385*67e74705SXin Li
386*67e74705SXin Li ExprResult LHS =
387*67e74705SXin Li CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
388*67e74705SXin Li if (!getLangOpts().CPlusPlus11)
389*67e74705SXin Li return VerifyIntegerConstantExpression(E);
390*67e74705SXin Li if (Expr *CondExpr =
391*67e74705SXin Li getCurFunction()->SwitchStack.back()->getCond()) {
392*67e74705SXin Li QualType CondType = CondExpr->getType();
393*67e74705SXin Li llvm::APSInt TempVal;
394*67e74705SXin Li return CheckConvertedConstantExpression(E, CondType, TempVal,
395*67e74705SXin Li CCEK_CaseValue);
396*67e74705SXin Li }
397*67e74705SXin Li return ExprError();
398*67e74705SXin Li });
399*67e74705SXin Li if (LHS.isInvalid())
400*67e74705SXin Li return StmtError();
401*67e74705SXin Li LHSVal = LHS.get();
402*67e74705SXin Li
403*67e74705SXin Li if (!getLangOpts().CPlusPlus11) {
404*67e74705SXin Li // C99 6.8.4.2p3: The expression shall be an integer constant.
405*67e74705SXin Li // However, GCC allows any evaluatable integer expression.
406*67e74705SXin Li if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
407*67e74705SXin Li LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
408*67e74705SXin Li if (!LHSVal)
409*67e74705SXin Li return StmtError();
410*67e74705SXin Li }
411*67e74705SXin Li
412*67e74705SXin Li // GCC extension: The expression shall be an integer constant.
413*67e74705SXin Li
414*67e74705SXin Li if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
415*67e74705SXin Li RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
416*67e74705SXin Li // Recover from an error by just forgetting about it.
417*67e74705SXin Li }
418*67e74705SXin Li }
419*67e74705SXin Li
420*67e74705SXin Li LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
421*67e74705SXin Li getLangOpts().CPlusPlus11);
422*67e74705SXin Li if (LHS.isInvalid())
423*67e74705SXin Li return StmtError();
424*67e74705SXin Li
425*67e74705SXin Li auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
426*67e74705SXin Li getLangOpts().CPlusPlus11)
427*67e74705SXin Li : ExprResult();
428*67e74705SXin Li if (RHS.isInvalid())
429*67e74705SXin Li return StmtError();
430*67e74705SXin Li
431*67e74705SXin Li CaseStmt *CS = new (Context)
432*67e74705SXin Li CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
433*67e74705SXin Li getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
434*67e74705SXin Li return CS;
435*67e74705SXin Li }
436*67e74705SXin Li
437*67e74705SXin Li /// ActOnCaseStmtBody - This installs a statement as the body of a case.
ActOnCaseStmtBody(Stmt * caseStmt,Stmt * SubStmt)438*67e74705SXin Li void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
439*67e74705SXin Li DiagnoseUnusedExprResult(SubStmt);
440*67e74705SXin Li
441*67e74705SXin Li CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
442*67e74705SXin Li CS->setSubStmt(SubStmt);
443*67e74705SXin Li }
444*67e74705SXin Li
445*67e74705SXin Li StmtResult
ActOnDefaultStmt(SourceLocation DefaultLoc,SourceLocation ColonLoc,Stmt * SubStmt,Scope * CurScope)446*67e74705SXin Li Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
447*67e74705SXin Li Stmt *SubStmt, Scope *CurScope) {
448*67e74705SXin Li DiagnoseUnusedExprResult(SubStmt);
449*67e74705SXin Li
450*67e74705SXin Li if (getCurFunction()->SwitchStack.empty()) {
451*67e74705SXin Li Diag(DefaultLoc, diag::err_default_not_in_switch);
452*67e74705SXin Li return SubStmt;
453*67e74705SXin Li }
454*67e74705SXin Li
455*67e74705SXin Li DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
456*67e74705SXin Li getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
457*67e74705SXin Li return DS;
458*67e74705SXin Li }
459*67e74705SXin Li
460*67e74705SXin Li StmtResult
ActOnLabelStmt(SourceLocation IdentLoc,LabelDecl * TheDecl,SourceLocation ColonLoc,Stmt * SubStmt)461*67e74705SXin Li Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
462*67e74705SXin Li SourceLocation ColonLoc, Stmt *SubStmt) {
463*67e74705SXin Li // If the label was multiply defined, reject it now.
464*67e74705SXin Li if (TheDecl->getStmt()) {
465*67e74705SXin Li Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
466*67e74705SXin Li Diag(TheDecl->getLocation(), diag::note_previous_definition);
467*67e74705SXin Li return SubStmt;
468*67e74705SXin Li }
469*67e74705SXin Li
470*67e74705SXin Li // Otherwise, things are good. Fill in the declaration and return it.
471*67e74705SXin Li LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
472*67e74705SXin Li TheDecl->setStmt(LS);
473*67e74705SXin Li if (!TheDecl->isGnuLocal()) {
474*67e74705SXin Li TheDecl->setLocStart(IdentLoc);
475*67e74705SXin Li if (!TheDecl->isMSAsmLabel()) {
476*67e74705SXin Li // Don't update the location of MS ASM labels. These will result in
477*67e74705SXin Li // a diagnostic, and changing the location here will mess that up.
478*67e74705SXin Li TheDecl->setLocation(IdentLoc);
479*67e74705SXin Li }
480*67e74705SXin Li }
481*67e74705SXin Li return LS;
482*67e74705SXin Li }
483*67e74705SXin Li
ActOnAttributedStmt(SourceLocation AttrLoc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)484*67e74705SXin Li StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
485*67e74705SXin Li ArrayRef<const Attr*> Attrs,
486*67e74705SXin Li Stmt *SubStmt) {
487*67e74705SXin Li // Fill in the declaration and return it.
488*67e74705SXin Li AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
489*67e74705SXin Li return LS;
490*67e74705SXin Li }
491*67e74705SXin Li
492*67e74705SXin Li namespace {
493*67e74705SXin Li class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
494*67e74705SXin Li typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
495*67e74705SXin Li Sema &SemaRef;
496*67e74705SXin Li public:
CommaVisitor(Sema & SemaRef)497*67e74705SXin Li CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
VisitBinaryOperator(BinaryOperator * E)498*67e74705SXin Li void VisitBinaryOperator(BinaryOperator *E) {
499*67e74705SXin Li if (E->getOpcode() == BO_Comma)
500*67e74705SXin Li SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
501*67e74705SXin Li EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
502*67e74705SXin Li }
503*67e74705SXin Li };
504*67e74705SXin Li }
505*67e74705SXin Li
506*67e74705SXin Li StmtResult
ActOnIfStmt(SourceLocation IfLoc,bool IsConstexpr,Stmt * InitStmt,ConditionResult Cond,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)507*67e74705SXin Li Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
508*67e74705SXin Li ConditionResult Cond,
509*67e74705SXin Li Stmt *thenStmt, SourceLocation ElseLoc,
510*67e74705SXin Li Stmt *elseStmt) {
511*67e74705SXin Li if (Cond.isInvalid())
512*67e74705SXin Li Cond = ConditionResult(
513*67e74705SXin Li *this, nullptr,
514*67e74705SXin Li MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
515*67e74705SXin Li Context.BoolTy, VK_RValue),
516*67e74705SXin Li IfLoc),
517*67e74705SXin Li false);
518*67e74705SXin Li
519*67e74705SXin Li Expr *CondExpr = Cond.get().second;
520*67e74705SXin Li if (!Diags.isIgnored(diag::warn_comma_operator,
521*67e74705SXin Li CondExpr->getExprLoc()))
522*67e74705SXin Li CommaVisitor(*this).Visit(CondExpr);
523*67e74705SXin Li
524*67e74705SXin Li if (!elseStmt)
525*67e74705SXin Li DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
526*67e74705SXin Li diag::warn_empty_if_body);
527*67e74705SXin Li
528*67e74705SXin Li return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
529*67e74705SXin Li elseStmt);
530*67e74705SXin Li }
531*67e74705SXin Li
BuildIfStmt(SourceLocation IfLoc,bool IsConstexpr,Stmt * InitStmt,ConditionResult Cond,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)532*67e74705SXin Li StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
533*67e74705SXin Li Stmt *InitStmt, ConditionResult Cond,
534*67e74705SXin Li Stmt *thenStmt, SourceLocation ElseLoc,
535*67e74705SXin Li Stmt *elseStmt) {
536*67e74705SXin Li if (Cond.isInvalid())
537*67e74705SXin Li return StmtError();
538*67e74705SXin Li
539*67e74705SXin Li if (IsConstexpr)
540*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
541*67e74705SXin Li
542*67e74705SXin Li DiagnoseUnusedExprResult(thenStmt);
543*67e74705SXin Li DiagnoseUnusedExprResult(elseStmt);
544*67e74705SXin Li
545*67e74705SXin Li return new (Context)
546*67e74705SXin Li IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
547*67e74705SXin Li Cond.get().second, thenStmt, ElseLoc, elseStmt);
548*67e74705SXin Li }
549*67e74705SXin Li
550*67e74705SXin Li namespace {
551*67e74705SXin Li struct CaseCompareFunctor {
operator ()__anonececbb350311::CaseCompareFunctor552*67e74705SXin Li bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
553*67e74705SXin Li const llvm::APSInt &RHS) {
554*67e74705SXin Li return LHS.first < RHS;
555*67e74705SXin Li }
operator ()__anonececbb350311::CaseCompareFunctor556*67e74705SXin Li bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
557*67e74705SXin Li const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
558*67e74705SXin Li return LHS.first < RHS.first;
559*67e74705SXin Li }
operator ()__anonececbb350311::CaseCompareFunctor560*67e74705SXin Li bool operator()(const llvm::APSInt &LHS,
561*67e74705SXin Li const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
562*67e74705SXin Li return LHS < RHS.first;
563*67e74705SXin Li }
564*67e74705SXin Li };
565*67e74705SXin Li }
566*67e74705SXin Li
567*67e74705SXin Li /// CmpCaseVals - Comparison predicate for sorting case values.
568*67e74705SXin Li ///
CmpCaseVals(const std::pair<llvm::APSInt,CaseStmt * > & lhs,const std::pair<llvm::APSInt,CaseStmt * > & rhs)569*67e74705SXin Li static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
570*67e74705SXin Li const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
571*67e74705SXin Li if (lhs.first < rhs.first)
572*67e74705SXin Li return true;
573*67e74705SXin Li
574*67e74705SXin Li if (lhs.first == rhs.first &&
575*67e74705SXin Li lhs.second->getCaseLoc().getRawEncoding()
576*67e74705SXin Li < rhs.second->getCaseLoc().getRawEncoding())
577*67e74705SXin Li return true;
578*67e74705SXin Li return false;
579*67e74705SXin Li }
580*67e74705SXin Li
581*67e74705SXin Li /// CmpEnumVals - Comparison predicate for sorting enumeration values.
582*67e74705SXin Li ///
CmpEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)583*67e74705SXin Li static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
584*67e74705SXin Li const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
585*67e74705SXin Li {
586*67e74705SXin Li return lhs.first < rhs.first;
587*67e74705SXin Li }
588*67e74705SXin Li
589*67e74705SXin Li /// EqEnumVals - Comparison preficate for uniqing enumeration values.
590*67e74705SXin Li ///
EqEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)591*67e74705SXin Li static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
592*67e74705SXin Li const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
593*67e74705SXin Li {
594*67e74705SXin Li return lhs.first == rhs.first;
595*67e74705SXin Li }
596*67e74705SXin Li
597*67e74705SXin Li /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
598*67e74705SXin Li /// potentially integral-promoted expression @p expr.
GetTypeBeforeIntegralPromotion(Expr * & expr)599*67e74705SXin Li static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
600*67e74705SXin Li if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
601*67e74705SXin Li expr = cleanups->getSubExpr();
602*67e74705SXin Li while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
603*67e74705SXin Li if (impcast->getCastKind() != CK_IntegralCast) break;
604*67e74705SXin Li expr = impcast->getSubExpr();
605*67e74705SXin Li }
606*67e74705SXin Li return expr->getType();
607*67e74705SXin Li }
608*67e74705SXin Li
CheckSwitchCondition(SourceLocation SwitchLoc,Expr * Cond)609*67e74705SXin Li ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
610*67e74705SXin Li class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
611*67e74705SXin Li Expr *Cond;
612*67e74705SXin Li
613*67e74705SXin Li public:
614*67e74705SXin Li SwitchConvertDiagnoser(Expr *Cond)
615*67e74705SXin Li : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
616*67e74705SXin Li Cond(Cond) {}
617*67e74705SXin Li
618*67e74705SXin Li SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
619*67e74705SXin Li QualType T) override {
620*67e74705SXin Li return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
621*67e74705SXin Li }
622*67e74705SXin Li
623*67e74705SXin Li SemaDiagnosticBuilder diagnoseIncomplete(
624*67e74705SXin Li Sema &S, SourceLocation Loc, QualType T) override {
625*67e74705SXin Li return S.Diag(Loc, diag::err_switch_incomplete_class_type)
626*67e74705SXin Li << T << Cond->getSourceRange();
627*67e74705SXin Li }
628*67e74705SXin Li
629*67e74705SXin Li SemaDiagnosticBuilder diagnoseExplicitConv(
630*67e74705SXin Li Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
631*67e74705SXin Li return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
632*67e74705SXin Li }
633*67e74705SXin Li
634*67e74705SXin Li SemaDiagnosticBuilder noteExplicitConv(
635*67e74705SXin Li Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
636*67e74705SXin Li return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
637*67e74705SXin Li << ConvTy->isEnumeralType() << ConvTy;
638*67e74705SXin Li }
639*67e74705SXin Li
640*67e74705SXin Li SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
641*67e74705SXin Li QualType T) override {
642*67e74705SXin Li return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
643*67e74705SXin Li }
644*67e74705SXin Li
645*67e74705SXin Li SemaDiagnosticBuilder noteAmbiguous(
646*67e74705SXin Li Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
647*67e74705SXin Li return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
648*67e74705SXin Li << ConvTy->isEnumeralType() << ConvTy;
649*67e74705SXin Li }
650*67e74705SXin Li
651*67e74705SXin Li SemaDiagnosticBuilder diagnoseConversion(
652*67e74705SXin Li Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
653*67e74705SXin Li llvm_unreachable("conversion functions are permitted");
654*67e74705SXin Li }
655*67e74705SXin Li } SwitchDiagnoser(Cond);
656*67e74705SXin Li
657*67e74705SXin Li ExprResult CondResult =
658*67e74705SXin Li PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
659*67e74705SXin Li if (CondResult.isInvalid())
660*67e74705SXin Li return ExprError();
661*67e74705SXin Li
662*67e74705SXin Li // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
663*67e74705SXin Li return UsualUnaryConversions(CondResult.get());
664*67e74705SXin Li }
665*67e74705SXin Li
ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,Stmt * InitStmt,ConditionResult Cond)666*67e74705SXin Li StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
667*67e74705SXin Li Stmt *InitStmt, ConditionResult Cond) {
668*67e74705SXin Li if (Cond.isInvalid())
669*67e74705SXin Li return StmtError();
670*67e74705SXin Li
671*67e74705SXin Li getCurFunction()->setHasBranchIntoScope();
672*67e74705SXin Li
673*67e74705SXin Li SwitchStmt *SS = new (Context)
674*67e74705SXin Li SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
675*67e74705SXin Li getCurFunction()->SwitchStack.push_back(SS);
676*67e74705SXin Li return SS;
677*67e74705SXin Li }
678*67e74705SXin Li
AdjustAPSInt(llvm::APSInt & Val,unsigned BitWidth,bool IsSigned)679*67e74705SXin Li static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
680*67e74705SXin Li Val = Val.extOrTrunc(BitWidth);
681*67e74705SXin Li Val.setIsSigned(IsSigned);
682*67e74705SXin Li }
683*67e74705SXin Li
684*67e74705SXin Li /// Check the specified case value is in range for the given unpromoted switch
685*67e74705SXin Li /// type.
checkCaseValue(Sema & S,SourceLocation Loc,const llvm::APSInt & Val,unsigned UnpromotedWidth,bool UnpromotedSign)686*67e74705SXin Li static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
687*67e74705SXin Li unsigned UnpromotedWidth, bool UnpromotedSign) {
688*67e74705SXin Li // If the case value was signed and negative and the switch expression is
689*67e74705SXin Li // unsigned, don't bother to warn: this is implementation-defined behavior.
690*67e74705SXin Li // FIXME: Introduce a second, default-ignored warning for this case?
691*67e74705SXin Li if (UnpromotedWidth < Val.getBitWidth()) {
692*67e74705SXin Li llvm::APSInt ConvVal(Val);
693*67e74705SXin Li AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
694*67e74705SXin Li AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
695*67e74705SXin Li // FIXME: Use different diagnostics for overflow in conversion to promoted
696*67e74705SXin Li // type versus "switch expression cannot have this value". Use proper
697*67e74705SXin Li // IntRange checking rather than just looking at the unpromoted type here.
698*67e74705SXin Li if (ConvVal != Val)
699*67e74705SXin Li S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
700*67e74705SXin Li << ConvVal.toString(10);
701*67e74705SXin Li }
702*67e74705SXin Li }
703*67e74705SXin Li
704*67e74705SXin Li typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
705*67e74705SXin Li
706*67e74705SXin Li /// Returns true if we should emit a diagnostic about this case expression not
707*67e74705SXin Li /// being a part of the enum used in the switch controlling expression.
ShouldDiagnoseSwitchCaseNotInEnum(const Sema & S,const EnumDecl * ED,const Expr * CaseExpr,EnumValsTy::iterator & EI,EnumValsTy::iterator & EIEnd,const llvm::APSInt & Val)708*67e74705SXin Li static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
709*67e74705SXin Li const EnumDecl *ED,
710*67e74705SXin Li const Expr *CaseExpr,
711*67e74705SXin Li EnumValsTy::iterator &EI,
712*67e74705SXin Li EnumValsTy::iterator &EIEnd,
713*67e74705SXin Li const llvm::APSInt &Val) {
714*67e74705SXin Li if (const DeclRefExpr *DRE =
715*67e74705SXin Li dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
716*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
717*67e74705SXin Li QualType VarType = VD->getType();
718*67e74705SXin Li QualType EnumType = S.Context.getTypeDeclType(ED);
719*67e74705SXin Li if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
720*67e74705SXin Li S.Context.hasSameUnqualifiedType(EnumType, VarType))
721*67e74705SXin Li return false;
722*67e74705SXin Li }
723*67e74705SXin Li }
724*67e74705SXin Li
725*67e74705SXin Li if (ED->hasAttr<FlagEnumAttr>()) {
726*67e74705SXin Li return !S.IsValueInFlagEnum(ED, Val, false);
727*67e74705SXin Li } else {
728*67e74705SXin Li while (EI != EIEnd && EI->first < Val)
729*67e74705SXin Li EI++;
730*67e74705SXin Li
731*67e74705SXin Li if (EI != EIEnd && EI->first == Val)
732*67e74705SXin Li return false;
733*67e74705SXin Li }
734*67e74705SXin Li
735*67e74705SXin Li return true;
736*67e74705SXin Li }
737*67e74705SXin Li
738*67e74705SXin Li StmtResult
ActOnFinishSwitchStmt(SourceLocation SwitchLoc,Stmt * Switch,Stmt * BodyStmt)739*67e74705SXin Li Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
740*67e74705SXin Li Stmt *BodyStmt) {
741*67e74705SXin Li SwitchStmt *SS = cast<SwitchStmt>(Switch);
742*67e74705SXin Li assert(SS == getCurFunction()->SwitchStack.back() &&
743*67e74705SXin Li "switch stack missing push/pop!");
744*67e74705SXin Li
745*67e74705SXin Li getCurFunction()->SwitchStack.pop_back();
746*67e74705SXin Li
747*67e74705SXin Li if (!BodyStmt) return StmtError();
748*67e74705SXin Li SS->setBody(BodyStmt, SwitchLoc);
749*67e74705SXin Li
750*67e74705SXin Li Expr *CondExpr = SS->getCond();
751*67e74705SXin Li if (!CondExpr) return StmtError();
752*67e74705SXin Li
753*67e74705SXin Li QualType CondType = CondExpr->getType();
754*67e74705SXin Li
755*67e74705SXin Li Expr *CondExprBeforePromotion = CondExpr;
756*67e74705SXin Li QualType CondTypeBeforePromotion =
757*67e74705SXin Li GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
758*67e74705SXin Li
759*67e74705SXin Li // C++ 6.4.2.p2:
760*67e74705SXin Li // Integral promotions are performed (on the switch condition).
761*67e74705SXin Li //
762*67e74705SXin Li // A case value unrepresentable by the original switch condition
763*67e74705SXin Li // type (before the promotion) doesn't make sense, even when it can
764*67e74705SXin Li // be represented by the promoted type. Therefore we need to find
765*67e74705SXin Li // the pre-promotion type of the switch condition.
766*67e74705SXin Li if (!CondExpr->isTypeDependent()) {
767*67e74705SXin Li // We have already converted the expression to an integral or enumeration
768*67e74705SXin Li // type, when we started the switch statement. If we don't have an
769*67e74705SXin Li // appropriate type now, just return an error.
770*67e74705SXin Li if (!CondType->isIntegralOrEnumerationType())
771*67e74705SXin Li return StmtError();
772*67e74705SXin Li
773*67e74705SXin Li if (CondExpr->isKnownToHaveBooleanValue()) {
774*67e74705SXin Li // switch(bool_expr) {...} is often a programmer error, e.g.
775*67e74705SXin Li // switch(n && mask) { ... } // Doh - should be "n & mask".
776*67e74705SXin Li // One can always use an if statement instead of switch(bool_expr).
777*67e74705SXin Li Diag(SwitchLoc, diag::warn_bool_switch_condition)
778*67e74705SXin Li << CondExpr->getSourceRange();
779*67e74705SXin Li }
780*67e74705SXin Li }
781*67e74705SXin Li
782*67e74705SXin Li // Get the bitwidth of the switched-on value after promotions. We must
783*67e74705SXin Li // convert the integer case values to this width before comparison.
784*67e74705SXin Li bool HasDependentValue
785*67e74705SXin Li = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
786*67e74705SXin Li unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
787*67e74705SXin Li bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
788*67e74705SXin Li
789*67e74705SXin Li // Get the width and signedness that the condition might actually have, for
790*67e74705SXin Li // warning purposes.
791*67e74705SXin Li // FIXME: Grab an IntRange for the condition rather than using the unpromoted
792*67e74705SXin Li // type.
793*67e74705SXin Li unsigned CondWidthBeforePromotion
794*67e74705SXin Li = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
795*67e74705SXin Li bool CondIsSignedBeforePromotion
796*67e74705SXin Li = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
797*67e74705SXin Li
798*67e74705SXin Li // Accumulate all of the case values in a vector so that we can sort them
799*67e74705SXin Li // and detect duplicates. This vector contains the APInt for the case after
800*67e74705SXin Li // it has been converted to the condition type.
801*67e74705SXin Li typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
802*67e74705SXin Li CaseValsTy CaseVals;
803*67e74705SXin Li
804*67e74705SXin Li // Keep track of any GNU case ranges we see. The APSInt is the low value.
805*67e74705SXin Li typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
806*67e74705SXin Li CaseRangesTy CaseRanges;
807*67e74705SXin Li
808*67e74705SXin Li DefaultStmt *TheDefaultStmt = nullptr;
809*67e74705SXin Li
810*67e74705SXin Li bool CaseListIsErroneous = false;
811*67e74705SXin Li
812*67e74705SXin Li for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
813*67e74705SXin Li SC = SC->getNextSwitchCase()) {
814*67e74705SXin Li
815*67e74705SXin Li if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
816*67e74705SXin Li if (TheDefaultStmt) {
817*67e74705SXin Li Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
818*67e74705SXin Li Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
819*67e74705SXin Li
820*67e74705SXin Li // FIXME: Remove the default statement from the switch block so that
821*67e74705SXin Li // we'll return a valid AST. This requires recursing down the AST and
822*67e74705SXin Li // finding it, not something we are set up to do right now. For now,
823*67e74705SXin Li // just lop the entire switch stmt out of the AST.
824*67e74705SXin Li CaseListIsErroneous = true;
825*67e74705SXin Li }
826*67e74705SXin Li TheDefaultStmt = DS;
827*67e74705SXin Li
828*67e74705SXin Li } else {
829*67e74705SXin Li CaseStmt *CS = cast<CaseStmt>(SC);
830*67e74705SXin Li
831*67e74705SXin Li Expr *Lo = CS->getLHS();
832*67e74705SXin Li
833*67e74705SXin Li if (Lo->isTypeDependent() || Lo->isValueDependent()) {
834*67e74705SXin Li HasDependentValue = true;
835*67e74705SXin Li break;
836*67e74705SXin Li }
837*67e74705SXin Li
838*67e74705SXin Li llvm::APSInt LoVal;
839*67e74705SXin Li
840*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
841*67e74705SXin Li // C++11 [stmt.switch]p2: the constant-expression shall be a converted
842*67e74705SXin Li // constant expression of the promoted type of the switch condition.
843*67e74705SXin Li ExprResult ConvLo =
844*67e74705SXin Li CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
845*67e74705SXin Li if (ConvLo.isInvalid()) {
846*67e74705SXin Li CaseListIsErroneous = true;
847*67e74705SXin Li continue;
848*67e74705SXin Li }
849*67e74705SXin Li Lo = ConvLo.get();
850*67e74705SXin Li } else {
851*67e74705SXin Li // We already verified that the expression has a i-c-e value (C99
852*67e74705SXin Li // 6.8.4.2p3) - get that value now.
853*67e74705SXin Li LoVal = Lo->EvaluateKnownConstInt(Context);
854*67e74705SXin Li
855*67e74705SXin Li // If the LHS is not the same type as the condition, insert an implicit
856*67e74705SXin Li // cast.
857*67e74705SXin Li Lo = DefaultLvalueConversion(Lo).get();
858*67e74705SXin Li Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
859*67e74705SXin Li }
860*67e74705SXin Li
861*67e74705SXin Li // Check the unconverted value is within the range of possible values of
862*67e74705SXin Li // the switch expression.
863*67e74705SXin Li checkCaseValue(*this, Lo->getLocStart(), LoVal,
864*67e74705SXin Li CondWidthBeforePromotion, CondIsSignedBeforePromotion);
865*67e74705SXin Li
866*67e74705SXin Li // Convert the value to the same width/sign as the condition.
867*67e74705SXin Li AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
868*67e74705SXin Li
869*67e74705SXin Li CS->setLHS(Lo);
870*67e74705SXin Li
871*67e74705SXin Li // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
872*67e74705SXin Li if (CS->getRHS()) {
873*67e74705SXin Li if (CS->getRHS()->isTypeDependent() ||
874*67e74705SXin Li CS->getRHS()->isValueDependent()) {
875*67e74705SXin Li HasDependentValue = true;
876*67e74705SXin Li break;
877*67e74705SXin Li }
878*67e74705SXin Li CaseRanges.push_back(std::make_pair(LoVal, CS));
879*67e74705SXin Li } else
880*67e74705SXin Li CaseVals.push_back(std::make_pair(LoVal, CS));
881*67e74705SXin Li }
882*67e74705SXin Li }
883*67e74705SXin Li
884*67e74705SXin Li if (!HasDependentValue) {
885*67e74705SXin Li // If we don't have a default statement, check whether the
886*67e74705SXin Li // condition is constant.
887*67e74705SXin Li llvm::APSInt ConstantCondValue;
888*67e74705SXin Li bool HasConstantCond = false;
889*67e74705SXin Li if (!HasDependentValue && !TheDefaultStmt) {
890*67e74705SXin Li HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
891*67e74705SXin Li Expr::SE_AllowSideEffects);
892*67e74705SXin Li assert(!HasConstantCond ||
893*67e74705SXin Li (ConstantCondValue.getBitWidth() == CondWidth &&
894*67e74705SXin Li ConstantCondValue.isSigned() == CondIsSigned));
895*67e74705SXin Li }
896*67e74705SXin Li bool ShouldCheckConstantCond = HasConstantCond;
897*67e74705SXin Li
898*67e74705SXin Li // Sort all the scalar case values so we can easily detect duplicates.
899*67e74705SXin Li std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
900*67e74705SXin Li
901*67e74705SXin Li if (!CaseVals.empty()) {
902*67e74705SXin Li for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
903*67e74705SXin Li if (ShouldCheckConstantCond &&
904*67e74705SXin Li CaseVals[i].first == ConstantCondValue)
905*67e74705SXin Li ShouldCheckConstantCond = false;
906*67e74705SXin Li
907*67e74705SXin Li if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
908*67e74705SXin Li // If we have a duplicate, report it.
909*67e74705SXin Li // First, determine if either case value has a name
910*67e74705SXin Li StringRef PrevString, CurrString;
911*67e74705SXin Li Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
912*67e74705SXin Li Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
913*67e74705SXin Li if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
914*67e74705SXin Li PrevString = DeclRef->getDecl()->getName();
915*67e74705SXin Li }
916*67e74705SXin Li if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
917*67e74705SXin Li CurrString = DeclRef->getDecl()->getName();
918*67e74705SXin Li }
919*67e74705SXin Li SmallString<16> CaseValStr;
920*67e74705SXin Li CaseVals[i-1].first.toString(CaseValStr);
921*67e74705SXin Li
922*67e74705SXin Li if (PrevString == CurrString)
923*67e74705SXin Li Diag(CaseVals[i].second->getLHS()->getLocStart(),
924*67e74705SXin Li diag::err_duplicate_case) <<
925*67e74705SXin Li (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
926*67e74705SXin Li else
927*67e74705SXin Li Diag(CaseVals[i].second->getLHS()->getLocStart(),
928*67e74705SXin Li diag::err_duplicate_case_differing_expr) <<
929*67e74705SXin Li (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
930*67e74705SXin Li (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
931*67e74705SXin Li CaseValStr;
932*67e74705SXin Li
933*67e74705SXin Li Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
934*67e74705SXin Li diag::note_duplicate_case_prev);
935*67e74705SXin Li // FIXME: We really want to remove the bogus case stmt from the
936*67e74705SXin Li // substmt, but we have no way to do this right now.
937*67e74705SXin Li CaseListIsErroneous = true;
938*67e74705SXin Li }
939*67e74705SXin Li }
940*67e74705SXin Li }
941*67e74705SXin Li
942*67e74705SXin Li // Detect duplicate case ranges, which usually don't exist at all in
943*67e74705SXin Li // the first place.
944*67e74705SXin Li if (!CaseRanges.empty()) {
945*67e74705SXin Li // Sort all the case ranges by their low value so we can easily detect
946*67e74705SXin Li // overlaps between ranges.
947*67e74705SXin Li std::stable_sort(CaseRanges.begin(), CaseRanges.end());
948*67e74705SXin Li
949*67e74705SXin Li // Scan the ranges, computing the high values and removing empty ranges.
950*67e74705SXin Li std::vector<llvm::APSInt> HiVals;
951*67e74705SXin Li for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
952*67e74705SXin Li llvm::APSInt &LoVal = CaseRanges[i].first;
953*67e74705SXin Li CaseStmt *CR = CaseRanges[i].second;
954*67e74705SXin Li Expr *Hi = CR->getRHS();
955*67e74705SXin Li llvm::APSInt HiVal;
956*67e74705SXin Li
957*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
958*67e74705SXin Li // C++11 [stmt.switch]p2: the constant-expression shall be a converted
959*67e74705SXin Li // constant expression of the promoted type of the switch condition.
960*67e74705SXin Li ExprResult ConvHi =
961*67e74705SXin Li CheckConvertedConstantExpression(Hi, CondType, HiVal,
962*67e74705SXin Li CCEK_CaseValue);
963*67e74705SXin Li if (ConvHi.isInvalid()) {
964*67e74705SXin Li CaseListIsErroneous = true;
965*67e74705SXin Li continue;
966*67e74705SXin Li }
967*67e74705SXin Li Hi = ConvHi.get();
968*67e74705SXin Li } else {
969*67e74705SXin Li HiVal = Hi->EvaluateKnownConstInt(Context);
970*67e74705SXin Li
971*67e74705SXin Li // If the RHS is not the same type as the condition, insert an
972*67e74705SXin Li // implicit cast.
973*67e74705SXin Li Hi = DefaultLvalueConversion(Hi).get();
974*67e74705SXin Li Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
975*67e74705SXin Li }
976*67e74705SXin Li
977*67e74705SXin Li // Check the unconverted value is within the range of possible values of
978*67e74705SXin Li // the switch expression.
979*67e74705SXin Li checkCaseValue(*this, Hi->getLocStart(), HiVal,
980*67e74705SXin Li CondWidthBeforePromotion, CondIsSignedBeforePromotion);
981*67e74705SXin Li
982*67e74705SXin Li // Convert the value to the same width/sign as the condition.
983*67e74705SXin Li AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
984*67e74705SXin Li
985*67e74705SXin Li CR->setRHS(Hi);
986*67e74705SXin Li
987*67e74705SXin Li // If the low value is bigger than the high value, the case is empty.
988*67e74705SXin Li if (LoVal > HiVal) {
989*67e74705SXin Li Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
990*67e74705SXin Li << SourceRange(CR->getLHS()->getLocStart(),
991*67e74705SXin Li Hi->getLocEnd());
992*67e74705SXin Li CaseRanges.erase(CaseRanges.begin()+i);
993*67e74705SXin Li --i;
994*67e74705SXin Li --e;
995*67e74705SXin Li continue;
996*67e74705SXin Li }
997*67e74705SXin Li
998*67e74705SXin Li if (ShouldCheckConstantCond &&
999*67e74705SXin Li LoVal <= ConstantCondValue &&
1000*67e74705SXin Li ConstantCondValue <= HiVal)
1001*67e74705SXin Li ShouldCheckConstantCond = false;
1002*67e74705SXin Li
1003*67e74705SXin Li HiVals.push_back(HiVal);
1004*67e74705SXin Li }
1005*67e74705SXin Li
1006*67e74705SXin Li // Rescan the ranges, looking for overlap with singleton values and other
1007*67e74705SXin Li // ranges. Since the range list is sorted, we only need to compare case
1008*67e74705SXin Li // ranges with their neighbors.
1009*67e74705SXin Li for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1010*67e74705SXin Li llvm::APSInt &CRLo = CaseRanges[i].first;
1011*67e74705SXin Li llvm::APSInt &CRHi = HiVals[i];
1012*67e74705SXin Li CaseStmt *CR = CaseRanges[i].second;
1013*67e74705SXin Li
1014*67e74705SXin Li // Check to see whether the case range overlaps with any
1015*67e74705SXin Li // singleton cases.
1016*67e74705SXin Li CaseStmt *OverlapStmt = nullptr;
1017*67e74705SXin Li llvm::APSInt OverlapVal(32);
1018*67e74705SXin Li
1019*67e74705SXin Li // Find the smallest value >= the lower bound. If I is in the
1020*67e74705SXin Li // case range, then we have overlap.
1021*67e74705SXin Li CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1022*67e74705SXin Li CaseVals.end(), CRLo,
1023*67e74705SXin Li CaseCompareFunctor());
1024*67e74705SXin Li if (I != CaseVals.end() && I->first < CRHi) {
1025*67e74705SXin Li OverlapVal = I->first; // Found overlap with scalar.
1026*67e74705SXin Li OverlapStmt = I->second;
1027*67e74705SXin Li }
1028*67e74705SXin Li
1029*67e74705SXin Li // Find the smallest value bigger than the upper bound.
1030*67e74705SXin Li I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1031*67e74705SXin Li if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1032*67e74705SXin Li OverlapVal = (I-1)->first; // Found overlap with scalar.
1033*67e74705SXin Li OverlapStmt = (I-1)->second;
1034*67e74705SXin Li }
1035*67e74705SXin Li
1036*67e74705SXin Li // Check to see if this case stmt overlaps with the subsequent
1037*67e74705SXin Li // case range.
1038*67e74705SXin Li if (i && CRLo <= HiVals[i-1]) {
1039*67e74705SXin Li OverlapVal = HiVals[i-1]; // Found overlap with range.
1040*67e74705SXin Li OverlapStmt = CaseRanges[i-1].second;
1041*67e74705SXin Li }
1042*67e74705SXin Li
1043*67e74705SXin Li if (OverlapStmt) {
1044*67e74705SXin Li // If we have a duplicate, report it.
1045*67e74705SXin Li Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1046*67e74705SXin Li << OverlapVal.toString(10);
1047*67e74705SXin Li Diag(OverlapStmt->getLHS()->getLocStart(),
1048*67e74705SXin Li diag::note_duplicate_case_prev);
1049*67e74705SXin Li // FIXME: We really want to remove the bogus case stmt from the
1050*67e74705SXin Li // substmt, but we have no way to do this right now.
1051*67e74705SXin Li CaseListIsErroneous = true;
1052*67e74705SXin Li }
1053*67e74705SXin Li }
1054*67e74705SXin Li }
1055*67e74705SXin Li
1056*67e74705SXin Li // Complain if we have a constant condition and we didn't find a match.
1057*67e74705SXin Li if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1058*67e74705SXin Li // TODO: it would be nice if we printed enums as enums, chars as
1059*67e74705SXin Li // chars, etc.
1060*67e74705SXin Li Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1061*67e74705SXin Li << ConstantCondValue.toString(10)
1062*67e74705SXin Li << CondExpr->getSourceRange();
1063*67e74705SXin Li }
1064*67e74705SXin Li
1065*67e74705SXin Li // Check to see if switch is over an Enum and handles all of its
1066*67e74705SXin Li // values. We only issue a warning if there is not 'default:', but
1067*67e74705SXin Li // we still do the analysis to preserve this information in the AST
1068*67e74705SXin Li // (which can be used by flow-based analyes).
1069*67e74705SXin Li //
1070*67e74705SXin Li const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1071*67e74705SXin Li
1072*67e74705SXin Li // If switch has default case, then ignore it.
1073*67e74705SXin Li if (!CaseListIsErroneous && !HasConstantCond && ET) {
1074*67e74705SXin Li const EnumDecl *ED = ET->getDecl();
1075*67e74705SXin Li EnumValsTy EnumVals;
1076*67e74705SXin Li
1077*67e74705SXin Li // Gather all enum values, set their type and sort them,
1078*67e74705SXin Li // allowing easier comparison with CaseVals.
1079*67e74705SXin Li for (auto *EDI : ED->enumerators()) {
1080*67e74705SXin Li llvm::APSInt Val = EDI->getInitVal();
1081*67e74705SXin Li AdjustAPSInt(Val, CondWidth, CondIsSigned);
1082*67e74705SXin Li EnumVals.push_back(std::make_pair(Val, EDI));
1083*67e74705SXin Li }
1084*67e74705SXin Li std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1085*67e74705SXin Li auto EI = EnumVals.begin(), EIEnd =
1086*67e74705SXin Li std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1087*67e74705SXin Li
1088*67e74705SXin Li // See which case values aren't in enum.
1089*67e74705SXin Li for (CaseValsTy::const_iterator CI = CaseVals.begin();
1090*67e74705SXin Li CI != CaseVals.end(); CI++) {
1091*67e74705SXin Li Expr *CaseExpr = CI->second->getLHS();
1092*67e74705SXin Li if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1093*67e74705SXin Li CI->first))
1094*67e74705SXin Li Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1095*67e74705SXin Li << CondTypeBeforePromotion;
1096*67e74705SXin Li }
1097*67e74705SXin Li
1098*67e74705SXin Li // See which of case ranges aren't in enum
1099*67e74705SXin Li EI = EnumVals.begin();
1100*67e74705SXin Li for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1101*67e74705SXin Li RI != CaseRanges.end(); RI++) {
1102*67e74705SXin Li Expr *CaseExpr = RI->second->getLHS();
1103*67e74705SXin Li if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1104*67e74705SXin Li RI->first))
1105*67e74705SXin Li Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1106*67e74705SXin Li << CondTypeBeforePromotion;
1107*67e74705SXin Li
1108*67e74705SXin Li llvm::APSInt Hi =
1109*67e74705SXin Li RI->second->getRHS()->EvaluateKnownConstInt(Context);
1110*67e74705SXin Li AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1111*67e74705SXin Li
1112*67e74705SXin Li CaseExpr = RI->second->getRHS();
1113*67e74705SXin Li if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1114*67e74705SXin Li Hi))
1115*67e74705SXin Li Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1116*67e74705SXin Li << CondTypeBeforePromotion;
1117*67e74705SXin Li }
1118*67e74705SXin Li
1119*67e74705SXin Li // Check which enum vals aren't in switch
1120*67e74705SXin Li auto CI = CaseVals.begin();
1121*67e74705SXin Li auto RI = CaseRanges.begin();
1122*67e74705SXin Li bool hasCasesNotInSwitch = false;
1123*67e74705SXin Li
1124*67e74705SXin Li SmallVector<DeclarationName,8> UnhandledNames;
1125*67e74705SXin Li
1126*67e74705SXin Li for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1127*67e74705SXin Li // Drop unneeded case values
1128*67e74705SXin Li while (CI != CaseVals.end() && CI->first < EI->first)
1129*67e74705SXin Li CI++;
1130*67e74705SXin Li
1131*67e74705SXin Li if (CI != CaseVals.end() && CI->first == EI->first)
1132*67e74705SXin Li continue;
1133*67e74705SXin Li
1134*67e74705SXin Li // Drop unneeded case ranges
1135*67e74705SXin Li for (; RI != CaseRanges.end(); RI++) {
1136*67e74705SXin Li llvm::APSInt Hi =
1137*67e74705SXin Li RI->second->getRHS()->EvaluateKnownConstInt(Context);
1138*67e74705SXin Li AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1139*67e74705SXin Li if (EI->first <= Hi)
1140*67e74705SXin Li break;
1141*67e74705SXin Li }
1142*67e74705SXin Li
1143*67e74705SXin Li if (RI == CaseRanges.end() || EI->first < RI->first) {
1144*67e74705SXin Li hasCasesNotInSwitch = true;
1145*67e74705SXin Li UnhandledNames.push_back(EI->second->getDeclName());
1146*67e74705SXin Li }
1147*67e74705SXin Li }
1148*67e74705SXin Li
1149*67e74705SXin Li if (TheDefaultStmt && UnhandledNames.empty())
1150*67e74705SXin Li Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1151*67e74705SXin Li
1152*67e74705SXin Li // Produce a nice diagnostic if multiple values aren't handled.
1153*67e74705SXin Li if (!UnhandledNames.empty()) {
1154*67e74705SXin Li DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1155*67e74705SXin Li TheDefaultStmt ? diag::warn_def_missing_case
1156*67e74705SXin Li : diag::warn_missing_case)
1157*67e74705SXin Li << (int)UnhandledNames.size();
1158*67e74705SXin Li
1159*67e74705SXin Li for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1160*67e74705SXin Li I != E; ++I)
1161*67e74705SXin Li DB << UnhandledNames[I];
1162*67e74705SXin Li }
1163*67e74705SXin Li
1164*67e74705SXin Li if (!hasCasesNotInSwitch)
1165*67e74705SXin Li SS->setAllEnumCasesCovered();
1166*67e74705SXin Li }
1167*67e74705SXin Li }
1168*67e74705SXin Li
1169*67e74705SXin Li if (BodyStmt)
1170*67e74705SXin Li DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1171*67e74705SXin Li diag::warn_empty_switch_body);
1172*67e74705SXin Li
1173*67e74705SXin Li // FIXME: If the case list was broken is some way, we don't have a good system
1174*67e74705SXin Li // to patch it up. Instead, just return the whole substmt as broken.
1175*67e74705SXin Li if (CaseListIsErroneous)
1176*67e74705SXin Li return StmtError();
1177*67e74705SXin Li
1178*67e74705SXin Li return SS;
1179*67e74705SXin Li }
1180*67e74705SXin Li
1181*67e74705SXin Li void
DiagnoseAssignmentEnum(QualType DstType,QualType SrcType,Expr * SrcExpr)1182*67e74705SXin Li Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1183*67e74705SXin Li Expr *SrcExpr) {
1184*67e74705SXin Li if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1185*67e74705SXin Li return;
1186*67e74705SXin Li
1187*67e74705SXin Li if (const EnumType *ET = DstType->getAs<EnumType>())
1188*67e74705SXin Li if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1189*67e74705SXin Li SrcType->isIntegerType()) {
1190*67e74705SXin Li if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1191*67e74705SXin Li SrcExpr->isIntegerConstantExpr(Context)) {
1192*67e74705SXin Li // Get the bitwidth of the enum value before promotions.
1193*67e74705SXin Li unsigned DstWidth = Context.getIntWidth(DstType);
1194*67e74705SXin Li bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1195*67e74705SXin Li
1196*67e74705SXin Li llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1197*67e74705SXin Li AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1198*67e74705SXin Li const EnumDecl *ED = ET->getDecl();
1199*67e74705SXin Li
1200*67e74705SXin Li if (ED->hasAttr<FlagEnumAttr>()) {
1201*67e74705SXin Li if (!IsValueInFlagEnum(ED, RhsVal, true))
1202*67e74705SXin Li Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1203*67e74705SXin Li << DstType.getUnqualifiedType();
1204*67e74705SXin Li } else {
1205*67e74705SXin Li typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1206*67e74705SXin Li EnumValsTy;
1207*67e74705SXin Li EnumValsTy EnumVals;
1208*67e74705SXin Li
1209*67e74705SXin Li // Gather all enum values, set their type and sort them,
1210*67e74705SXin Li // allowing easier comparison with rhs constant.
1211*67e74705SXin Li for (auto *EDI : ED->enumerators()) {
1212*67e74705SXin Li llvm::APSInt Val = EDI->getInitVal();
1213*67e74705SXin Li AdjustAPSInt(Val, DstWidth, DstIsSigned);
1214*67e74705SXin Li EnumVals.push_back(std::make_pair(Val, EDI));
1215*67e74705SXin Li }
1216*67e74705SXin Li if (EnumVals.empty())
1217*67e74705SXin Li return;
1218*67e74705SXin Li std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1219*67e74705SXin Li EnumValsTy::iterator EIend =
1220*67e74705SXin Li std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1221*67e74705SXin Li
1222*67e74705SXin Li // See which values aren't in the enum.
1223*67e74705SXin Li EnumValsTy::const_iterator EI = EnumVals.begin();
1224*67e74705SXin Li while (EI != EIend && EI->first < RhsVal)
1225*67e74705SXin Li EI++;
1226*67e74705SXin Li if (EI == EIend || EI->first != RhsVal) {
1227*67e74705SXin Li Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1228*67e74705SXin Li << DstType.getUnqualifiedType();
1229*67e74705SXin Li }
1230*67e74705SXin Li }
1231*67e74705SXin Li }
1232*67e74705SXin Li }
1233*67e74705SXin Li }
1234*67e74705SXin Li
ActOnWhileStmt(SourceLocation WhileLoc,ConditionResult Cond,Stmt * Body)1235*67e74705SXin Li StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1236*67e74705SXin Li Stmt *Body) {
1237*67e74705SXin Li if (Cond.isInvalid())
1238*67e74705SXin Li return StmtError();
1239*67e74705SXin Li
1240*67e74705SXin Li auto CondVal = Cond.get();
1241*67e74705SXin Li CheckBreakContinueBinding(CondVal.second);
1242*67e74705SXin Li
1243*67e74705SXin Li if (CondVal.second &&
1244*67e74705SXin Li !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1245*67e74705SXin Li CommaVisitor(*this).Visit(CondVal.second);
1246*67e74705SXin Li
1247*67e74705SXin Li DiagnoseUnusedExprResult(Body);
1248*67e74705SXin Li
1249*67e74705SXin Li if (isa<NullStmt>(Body))
1250*67e74705SXin Li getCurCompoundScope().setHasEmptyLoopBodies();
1251*67e74705SXin Li
1252*67e74705SXin Li return new (Context)
1253*67e74705SXin Li WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
1254*67e74705SXin Li }
1255*67e74705SXin Li
1256*67e74705SXin Li StmtResult
ActOnDoStmt(SourceLocation DoLoc,Stmt * Body,SourceLocation WhileLoc,SourceLocation CondLParen,Expr * Cond,SourceLocation CondRParen)1257*67e74705SXin Li Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1258*67e74705SXin Li SourceLocation WhileLoc, SourceLocation CondLParen,
1259*67e74705SXin Li Expr *Cond, SourceLocation CondRParen) {
1260*67e74705SXin Li assert(Cond && "ActOnDoStmt(): missing expression");
1261*67e74705SXin Li
1262*67e74705SXin Li CheckBreakContinueBinding(Cond);
1263*67e74705SXin Li ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1264*67e74705SXin Li if (CondResult.isInvalid())
1265*67e74705SXin Li return StmtError();
1266*67e74705SXin Li Cond = CondResult.get();
1267*67e74705SXin Li
1268*67e74705SXin Li CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1269*67e74705SXin Li if (CondResult.isInvalid())
1270*67e74705SXin Li return StmtError();
1271*67e74705SXin Li Cond = CondResult.get();
1272*67e74705SXin Li
1273*67e74705SXin Li DiagnoseUnusedExprResult(Body);
1274*67e74705SXin Li
1275*67e74705SXin Li return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1276*67e74705SXin Li }
1277*67e74705SXin Li
1278*67e74705SXin Li namespace {
1279*67e74705SXin Li // This visitor will traverse a conditional statement and store all
1280*67e74705SXin Li // the evaluated decls into a vector. Simple is set to true if none
1281*67e74705SXin Li // of the excluded constructs are used.
1282*67e74705SXin Li class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1283*67e74705SXin Li llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1284*67e74705SXin Li SmallVectorImpl<SourceRange> &Ranges;
1285*67e74705SXin Li bool Simple;
1286*67e74705SXin Li public:
1287*67e74705SXin Li typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1288*67e74705SXin Li
DeclExtractor(Sema & S,llvm::SmallPtrSetImpl<VarDecl * > & Decls,SmallVectorImpl<SourceRange> & Ranges)1289*67e74705SXin Li DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1290*67e74705SXin Li SmallVectorImpl<SourceRange> &Ranges) :
1291*67e74705SXin Li Inherited(S.Context),
1292*67e74705SXin Li Decls(Decls),
1293*67e74705SXin Li Ranges(Ranges),
1294*67e74705SXin Li Simple(true) {}
1295*67e74705SXin Li
isSimple()1296*67e74705SXin Li bool isSimple() { return Simple; }
1297*67e74705SXin Li
1298*67e74705SXin Li // Replaces the method in EvaluatedExprVisitor.
VisitMemberExpr(MemberExpr * E)1299*67e74705SXin Li void VisitMemberExpr(MemberExpr* E) {
1300*67e74705SXin Li Simple = false;
1301*67e74705SXin Li }
1302*67e74705SXin Li
1303*67e74705SXin Li // Any Stmt not whitelisted will cause the condition to be marked complex.
VisitStmt(Stmt * S)1304*67e74705SXin Li void VisitStmt(Stmt *S) {
1305*67e74705SXin Li Simple = false;
1306*67e74705SXin Li }
1307*67e74705SXin Li
VisitBinaryOperator(BinaryOperator * E)1308*67e74705SXin Li void VisitBinaryOperator(BinaryOperator *E) {
1309*67e74705SXin Li Visit(E->getLHS());
1310*67e74705SXin Li Visit(E->getRHS());
1311*67e74705SXin Li }
1312*67e74705SXin Li
VisitCastExpr(CastExpr * E)1313*67e74705SXin Li void VisitCastExpr(CastExpr *E) {
1314*67e74705SXin Li Visit(E->getSubExpr());
1315*67e74705SXin Li }
1316*67e74705SXin Li
VisitUnaryOperator(UnaryOperator * E)1317*67e74705SXin Li void VisitUnaryOperator(UnaryOperator *E) {
1318*67e74705SXin Li // Skip checking conditionals with derefernces.
1319*67e74705SXin Li if (E->getOpcode() == UO_Deref)
1320*67e74705SXin Li Simple = false;
1321*67e74705SXin Li else
1322*67e74705SXin Li Visit(E->getSubExpr());
1323*67e74705SXin Li }
1324*67e74705SXin Li
VisitConditionalOperator(ConditionalOperator * E)1325*67e74705SXin Li void VisitConditionalOperator(ConditionalOperator *E) {
1326*67e74705SXin Li Visit(E->getCond());
1327*67e74705SXin Li Visit(E->getTrueExpr());
1328*67e74705SXin Li Visit(E->getFalseExpr());
1329*67e74705SXin Li }
1330*67e74705SXin Li
VisitParenExpr(ParenExpr * E)1331*67e74705SXin Li void VisitParenExpr(ParenExpr *E) {
1332*67e74705SXin Li Visit(E->getSubExpr());
1333*67e74705SXin Li }
1334*67e74705SXin Li
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)1335*67e74705SXin Li void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1336*67e74705SXin Li Visit(E->getOpaqueValue()->getSourceExpr());
1337*67e74705SXin Li Visit(E->getFalseExpr());
1338*67e74705SXin Li }
1339*67e74705SXin Li
VisitIntegerLiteral(IntegerLiteral * E)1340*67e74705SXin Li void VisitIntegerLiteral(IntegerLiteral *E) { }
VisitFloatingLiteral(FloatingLiteral * E)1341*67e74705SXin Li void VisitFloatingLiteral(FloatingLiteral *E) { }
VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr * E)1342*67e74705SXin Li void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
VisitCharacterLiteral(CharacterLiteral * E)1343*67e74705SXin Li void VisitCharacterLiteral(CharacterLiteral *E) { }
VisitGNUNullExpr(GNUNullExpr * E)1344*67e74705SXin Li void VisitGNUNullExpr(GNUNullExpr *E) { }
VisitImaginaryLiteral(ImaginaryLiteral * E)1345*67e74705SXin Li void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1346*67e74705SXin Li
VisitDeclRefExpr(DeclRefExpr * E)1347*67e74705SXin Li void VisitDeclRefExpr(DeclRefExpr *E) {
1348*67e74705SXin Li VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1349*67e74705SXin Li if (!VD) return;
1350*67e74705SXin Li
1351*67e74705SXin Li Ranges.push_back(E->getSourceRange());
1352*67e74705SXin Li
1353*67e74705SXin Li Decls.insert(VD);
1354*67e74705SXin Li }
1355*67e74705SXin Li
1356*67e74705SXin Li }; // end class DeclExtractor
1357*67e74705SXin Li
1358*67e74705SXin Li // DeclMatcher checks to see if the decls are used in a non-evaluated
1359*67e74705SXin Li // context.
1360*67e74705SXin Li class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1361*67e74705SXin Li llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1362*67e74705SXin Li bool FoundDecl;
1363*67e74705SXin Li
1364*67e74705SXin Li public:
1365*67e74705SXin Li typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1366*67e74705SXin Li
DeclMatcher(Sema & S,llvm::SmallPtrSetImpl<VarDecl * > & Decls,Stmt * Statement)1367*67e74705SXin Li DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1368*67e74705SXin Li Stmt *Statement) :
1369*67e74705SXin Li Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1370*67e74705SXin Li if (!Statement) return;
1371*67e74705SXin Li
1372*67e74705SXin Li Visit(Statement);
1373*67e74705SXin Li }
1374*67e74705SXin Li
VisitReturnStmt(ReturnStmt * S)1375*67e74705SXin Li void VisitReturnStmt(ReturnStmt *S) {
1376*67e74705SXin Li FoundDecl = true;
1377*67e74705SXin Li }
1378*67e74705SXin Li
VisitBreakStmt(BreakStmt * S)1379*67e74705SXin Li void VisitBreakStmt(BreakStmt *S) {
1380*67e74705SXin Li FoundDecl = true;
1381*67e74705SXin Li }
1382*67e74705SXin Li
VisitGotoStmt(GotoStmt * S)1383*67e74705SXin Li void VisitGotoStmt(GotoStmt *S) {
1384*67e74705SXin Li FoundDecl = true;
1385*67e74705SXin Li }
1386*67e74705SXin Li
VisitCastExpr(CastExpr * E)1387*67e74705SXin Li void VisitCastExpr(CastExpr *E) {
1388*67e74705SXin Li if (E->getCastKind() == CK_LValueToRValue)
1389*67e74705SXin Li CheckLValueToRValueCast(E->getSubExpr());
1390*67e74705SXin Li else
1391*67e74705SXin Li Visit(E->getSubExpr());
1392*67e74705SXin Li }
1393*67e74705SXin Li
CheckLValueToRValueCast(Expr * E)1394*67e74705SXin Li void CheckLValueToRValueCast(Expr *E) {
1395*67e74705SXin Li E = E->IgnoreParenImpCasts();
1396*67e74705SXin Li
1397*67e74705SXin Li if (isa<DeclRefExpr>(E)) {
1398*67e74705SXin Li return;
1399*67e74705SXin Li }
1400*67e74705SXin Li
1401*67e74705SXin Li if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1402*67e74705SXin Li Visit(CO->getCond());
1403*67e74705SXin Li CheckLValueToRValueCast(CO->getTrueExpr());
1404*67e74705SXin Li CheckLValueToRValueCast(CO->getFalseExpr());
1405*67e74705SXin Li return;
1406*67e74705SXin Li }
1407*67e74705SXin Li
1408*67e74705SXin Li if (BinaryConditionalOperator *BCO =
1409*67e74705SXin Li dyn_cast<BinaryConditionalOperator>(E)) {
1410*67e74705SXin Li CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1411*67e74705SXin Li CheckLValueToRValueCast(BCO->getFalseExpr());
1412*67e74705SXin Li return;
1413*67e74705SXin Li }
1414*67e74705SXin Li
1415*67e74705SXin Li Visit(E);
1416*67e74705SXin Li }
1417*67e74705SXin Li
VisitDeclRefExpr(DeclRefExpr * E)1418*67e74705SXin Li void VisitDeclRefExpr(DeclRefExpr *E) {
1419*67e74705SXin Li if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1420*67e74705SXin Li if (Decls.count(VD))
1421*67e74705SXin Li FoundDecl = true;
1422*67e74705SXin Li }
1423*67e74705SXin Li
VisitPseudoObjectExpr(PseudoObjectExpr * POE)1424*67e74705SXin Li void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1425*67e74705SXin Li // Only need to visit the semantics for POE.
1426*67e74705SXin Li // SyntaticForm doesn't really use the Decal.
1427*67e74705SXin Li for (auto *S : POE->semantics()) {
1428*67e74705SXin Li if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1429*67e74705SXin Li // Look past the OVE into the expression it binds.
1430*67e74705SXin Li Visit(OVE->getSourceExpr());
1431*67e74705SXin Li else
1432*67e74705SXin Li Visit(S);
1433*67e74705SXin Li }
1434*67e74705SXin Li }
1435*67e74705SXin Li
FoundDeclInUse()1436*67e74705SXin Li bool FoundDeclInUse() { return FoundDecl; }
1437*67e74705SXin Li
1438*67e74705SXin Li }; // end class DeclMatcher
1439*67e74705SXin Li
CheckForLoopConditionalStatement(Sema & S,Expr * Second,Expr * Third,Stmt * Body)1440*67e74705SXin Li void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1441*67e74705SXin Li Expr *Third, Stmt *Body) {
1442*67e74705SXin Li // Condition is empty
1443*67e74705SXin Li if (!Second) return;
1444*67e74705SXin Li
1445*67e74705SXin Li if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1446*67e74705SXin Li Second->getLocStart()))
1447*67e74705SXin Li return;
1448*67e74705SXin Li
1449*67e74705SXin Li PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1450*67e74705SXin Li llvm::SmallPtrSet<VarDecl*, 8> Decls;
1451*67e74705SXin Li SmallVector<SourceRange, 10> Ranges;
1452*67e74705SXin Li DeclExtractor DE(S, Decls, Ranges);
1453*67e74705SXin Li DE.Visit(Second);
1454*67e74705SXin Li
1455*67e74705SXin Li // Don't analyze complex conditionals.
1456*67e74705SXin Li if (!DE.isSimple()) return;
1457*67e74705SXin Li
1458*67e74705SXin Li // No decls found.
1459*67e74705SXin Li if (Decls.size() == 0) return;
1460*67e74705SXin Li
1461*67e74705SXin Li // Don't warn on volatile, static, or global variables.
1462*67e74705SXin Li for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1463*67e74705SXin Li E = Decls.end();
1464*67e74705SXin Li I != E; ++I)
1465*67e74705SXin Li if ((*I)->getType().isVolatileQualified() ||
1466*67e74705SXin Li (*I)->hasGlobalStorage()) return;
1467*67e74705SXin Li
1468*67e74705SXin Li if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1469*67e74705SXin Li DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1470*67e74705SXin Li DeclMatcher(S, Decls, Body).FoundDeclInUse())
1471*67e74705SXin Li return;
1472*67e74705SXin Li
1473*67e74705SXin Li // Load decl names into diagnostic.
1474*67e74705SXin Li if (Decls.size() > 4)
1475*67e74705SXin Li PDiag << 0;
1476*67e74705SXin Li else {
1477*67e74705SXin Li PDiag << Decls.size();
1478*67e74705SXin Li for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1479*67e74705SXin Li E = Decls.end();
1480*67e74705SXin Li I != E; ++I)
1481*67e74705SXin Li PDiag << (*I)->getDeclName();
1482*67e74705SXin Li }
1483*67e74705SXin Li
1484*67e74705SXin Li // Load SourceRanges into diagnostic if there is room.
1485*67e74705SXin Li // Otherwise, load the SourceRange of the conditional expression.
1486*67e74705SXin Li if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1487*67e74705SXin Li for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1488*67e74705SXin Li E = Ranges.end();
1489*67e74705SXin Li I != E; ++I)
1490*67e74705SXin Li PDiag << *I;
1491*67e74705SXin Li else
1492*67e74705SXin Li PDiag << Second->getSourceRange();
1493*67e74705SXin Li
1494*67e74705SXin Li S.Diag(Ranges.begin()->getBegin(), PDiag);
1495*67e74705SXin Li }
1496*67e74705SXin Li
1497*67e74705SXin Li // If Statement is an incemement or decrement, return true and sets the
1498*67e74705SXin Li // variables Increment and DRE.
ProcessIterationStmt(Sema & S,Stmt * Statement,bool & Increment,DeclRefExpr * & DRE)1499*67e74705SXin Li bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1500*67e74705SXin Li DeclRefExpr *&DRE) {
1501*67e74705SXin Li if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1502*67e74705SXin Li if (!Cleanups->cleanupsHaveSideEffects())
1503*67e74705SXin Li Statement = Cleanups->getSubExpr();
1504*67e74705SXin Li
1505*67e74705SXin Li if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1506*67e74705SXin Li switch (UO->getOpcode()) {
1507*67e74705SXin Li default: return false;
1508*67e74705SXin Li case UO_PostInc:
1509*67e74705SXin Li case UO_PreInc:
1510*67e74705SXin Li Increment = true;
1511*67e74705SXin Li break;
1512*67e74705SXin Li case UO_PostDec:
1513*67e74705SXin Li case UO_PreDec:
1514*67e74705SXin Li Increment = false;
1515*67e74705SXin Li break;
1516*67e74705SXin Li }
1517*67e74705SXin Li DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1518*67e74705SXin Li return DRE;
1519*67e74705SXin Li }
1520*67e74705SXin Li
1521*67e74705SXin Li if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1522*67e74705SXin Li FunctionDecl *FD = Call->getDirectCallee();
1523*67e74705SXin Li if (!FD || !FD->isOverloadedOperator()) return false;
1524*67e74705SXin Li switch (FD->getOverloadedOperator()) {
1525*67e74705SXin Li default: return false;
1526*67e74705SXin Li case OO_PlusPlus:
1527*67e74705SXin Li Increment = true;
1528*67e74705SXin Li break;
1529*67e74705SXin Li case OO_MinusMinus:
1530*67e74705SXin Li Increment = false;
1531*67e74705SXin Li break;
1532*67e74705SXin Li }
1533*67e74705SXin Li DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1534*67e74705SXin Li return DRE;
1535*67e74705SXin Li }
1536*67e74705SXin Li
1537*67e74705SXin Li return false;
1538*67e74705SXin Li }
1539*67e74705SXin Li
1540*67e74705SXin Li // A visitor to determine if a continue or break statement is a
1541*67e74705SXin Li // subexpression.
1542*67e74705SXin Li class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1543*67e74705SXin Li SourceLocation BreakLoc;
1544*67e74705SXin Li SourceLocation ContinueLoc;
1545*67e74705SXin Li public:
BreakContinueFinder(Sema & S,Stmt * Body)1546*67e74705SXin Li BreakContinueFinder(Sema &S, Stmt* Body) :
1547*67e74705SXin Li Inherited(S.Context) {
1548*67e74705SXin Li Visit(Body);
1549*67e74705SXin Li }
1550*67e74705SXin Li
1551*67e74705SXin Li typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1552*67e74705SXin Li
VisitContinueStmt(ContinueStmt * E)1553*67e74705SXin Li void VisitContinueStmt(ContinueStmt* E) {
1554*67e74705SXin Li ContinueLoc = E->getContinueLoc();
1555*67e74705SXin Li }
1556*67e74705SXin Li
VisitBreakStmt(BreakStmt * E)1557*67e74705SXin Li void VisitBreakStmt(BreakStmt* E) {
1558*67e74705SXin Li BreakLoc = E->getBreakLoc();
1559*67e74705SXin Li }
1560*67e74705SXin Li
ContinueFound()1561*67e74705SXin Li bool ContinueFound() { return ContinueLoc.isValid(); }
BreakFound()1562*67e74705SXin Li bool BreakFound() { return BreakLoc.isValid(); }
GetContinueLoc()1563*67e74705SXin Li SourceLocation GetContinueLoc() { return ContinueLoc; }
GetBreakLoc()1564*67e74705SXin Li SourceLocation GetBreakLoc() { return BreakLoc; }
1565*67e74705SXin Li
1566*67e74705SXin Li }; // end class BreakContinueFinder
1567*67e74705SXin Li
1568*67e74705SXin Li // Emit a warning when a loop increment/decrement appears twice per loop
1569*67e74705SXin Li // iteration. The conditions which trigger this warning are:
1570*67e74705SXin Li // 1) The last statement in the loop body and the third expression in the
1571*67e74705SXin Li // for loop are both increment or both decrement of the same variable
1572*67e74705SXin Li // 2) No continue statements in the loop body.
CheckForRedundantIteration(Sema & S,Expr * Third,Stmt * Body)1573*67e74705SXin Li void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1574*67e74705SXin Li // Return when there is nothing to check.
1575*67e74705SXin Li if (!Body || !Third) return;
1576*67e74705SXin Li
1577*67e74705SXin Li if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1578*67e74705SXin Li Third->getLocStart()))
1579*67e74705SXin Li return;
1580*67e74705SXin Li
1581*67e74705SXin Li // Get the last statement from the loop body.
1582*67e74705SXin Li CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1583*67e74705SXin Li if (!CS || CS->body_empty()) return;
1584*67e74705SXin Li Stmt *LastStmt = CS->body_back();
1585*67e74705SXin Li if (!LastStmt) return;
1586*67e74705SXin Li
1587*67e74705SXin Li bool LoopIncrement, LastIncrement;
1588*67e74705SXin Li DeclRefExpr *LoopDRE, *LastDRE;
1589*67e74705SXin Li
1590*67e74705SXin Li if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1591*67e74705SXin Li if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1592*67e74705SXin Li
1593*67e74705SXin Li // Check that the two statements are both increments or both decrements
1594*67e74705SXin Li // on the same variable.
1595*67e74705SXin Li if (LoopIncrement != LastIncrement ||
1596*67e74705SXin Li LoopDRE->getDecl() != LastDRE->getDecl()) return;
1597*67e74705SXin Li
1598*67e74705SXin Li if (BreakContinueFinder(S, Body).ContinueFound()) return;
1599*67e74705SXin Li
1600*67e74705SXin Li S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1601*67e74705SXin Li << LastDRE->getDecl() << LastIncrement;
1602*67e74705SXin Li S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1603*67e74705SXin Li << LoopIncrement;
1604*67e74705SXin Li }
1605*67e74705SXin Li
1606*67e74705SXin Li } // end namespace
1607*67e74705SXin Li
1608*67e74705SXin Li
CheckBreakContinueBinding(Expr * E)1609*67e74705SXin Li void Sema::CheckBreakContinueBinding(Expr *E) {
1610*67e74705SXin Li if (!E || getLangOpts().CPlusPlus)
1611*67e74705SXin Li return;
1612*67e74705SXin Li BreakContinueFinder BCFinder(*this, E);
1613*67e74705SXin Li Scope *BreakParent = CurScope->getBreakParent();
1614*67e74705SXin Li if (BCFinder.BreakFound() && BreakParent) {
1615*67e74705SXin Li if (BreakParent->getFlags() & Scope::SwitchScope) {
1616*67e74705SXin Li Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1617*67e74705SXin Li } else {
1618*67e74705SXin Li Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1619*67e74705SXin Li << "break";
1620*67e74705SXin Li }
1621*67e74705SXin Li } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1622*67e74705SXin Li Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1623*67e74705SXin Li << "continue";
1624*67e74705SXin Li }
1625*67e74705SXin Li }
1626*67e74705SXin Li
ActOnForStmt(SourceLocation ForLoc,SourceLocation LParenLoc,Stmt * First,ConditionResult Second,FullExprArg third,SourceLocation RParenLoc,Stmt * Body)1627*67e74705SXin Li StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1628*67e74705SXin Li Stmt *First, ConditionResult Second,
1629*67e74705SXin Li FullExprArg third, SourceLocation RParenLoc,
1630*67e74705SXin Li Stmt *Body) {
1631*67e74705SXin Li if (Second.isInvalid())
1632*67e74705SXin Li return StmtError();
1633*67e74705SXin Li
1634*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
1635*67e74705SXin Li if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1636*67e74705SXin Li // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1637*67e74705SXin Li // declare identifiers for objects having storage class 'auto' or
1638*67e74705SXin Li // 'register'.
1639*67e74705SXin Li for (auto *DI : DS->decls()) {
1640*67e74705SXin Li VarDecl *VD = dyn_cast<VarDecl>(DI);
1641*67e74705SXin Li if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1642*67e74705SXin Li VD = nullptr;
1643*67e74705SXin Li if (!VD) {
1644*67e74705SXin Li Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1645*67e74705SXin Li DI->setInvalidDecl();
1646*67e74705SXin Li }
1647*67e74705SXin Li }
1648*67e74705SXin Li }
1649*67e74705SXin Li }
1650*67e74705SXin Li
1651*67e74705SXin Li CheckBreakContinueBinding(Second.get().second);
1652*67e74705SXin Li CheckBreakContinueBinding(third.get());
1653*67e74705SXin Li
1654*67e74705SXin Li if (!Second.get().first)
1655*67e74705SXin Li CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1656*67e74705SXin Li Body);
1657*67e74705SXin Li CheckForRedundantIteration(*this, third.get(), Body);
1658*67e74705SXin Li
1659*67e74705SXin Li if (Second.get().second &&
1660*67e74705SXin Li !Diags.isIgnored(diag::warn_comma_operator,
1661*67e74705SXin Li Second.get().second->getExprLoc()))
1662*67e74705SXin Li CommaVisitor(*this).Visit(Second.get().second);
1663*67e74705SXin Li
1664*67e74705SXin Li Expr *Third = third.release().getAs<Expr>();
1665*67e74705SXin Li
1666*67e74705SXin Li DiagnoseUnusedExprResult(First);
1667*67e74705SXin Li DiagnoseUnusedExprResult(Third);
1668*67e74705SXin Li DiagnoseUnusedExprResult(Body);
1669*67e74705SXin Li
1670*67e74705SXin Li if (isa<NullStmt>(Body))
1671*67e74705SXin Li getCurCompoundScope().setHasEmptyLoopBodies();
1672*67e74705SXin Li
1673*67e74705SXin Li return new (Context)
1674*67e74705SXin Li ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1675*67e74705SXin Li Body, ForLoc, LParenLoc, RParenLoc);
1676*67e74705SXin Li }
1677*67e74705SXin Li
1678*67e74705SXin Li /// In an Objective C collection iteration statement:
1679*67e74705SXin Li /// for (x in y)
1680*67e74705SXin Li /// x can be an arbitrary l-value expression. Bind it up as a
1681*67e74705SXin Li /// full-expression.
ActOnForEachLValueExpr(Expr * E)1682*67e74705SXin Li StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1683*67e74705SXin Li // Reduce placeholder expressions here. Note that this rejects the
1684*67e74705SXin Li // use of pseudo-object l-values in this position.
1685*67e74705SXin Li ExprResult result = CheckPlaceholderExpr(E);
1686*67e74705SXin Li if (result.isInvalid()) return StmtError();
1687*67e74705SXin Li E = result.get();
1688*67e74705SXin Li
1689*67e74705SXin Li ExprResult FullExpr = ActOnFinishFullExpr(E);
1690*67e74705SXin Li if (FullExpr.isInvalid())
1691*67e74705SXin Li return StmtError();
1692*67e74705SXin Li return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1693*67e74705SXin Li }
1694*67e74705SXin Li
1695*67e74705SXin Li ExprResult
CheckObjCForCollectionOperand(SourceLocation forLoc,Expr * collection)1696*67e74705SXin Li Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1697*67e74705SXin Li if (!collection)
1698*67e74705SXin Li return ExprError();
1699*67e74705SXin Li
1700*67e74705SXin Li ExprResult result = CorrectDelayedTyposInExpr(collection);
1701*67e74705SXin Li if (!result.isUsable())
1702*67e74705SXin Li return ExprError();
1703*67e74705SXin Li collection = result.get();
1704*67e74705SXin Li
1705*67e74705SXin Li // Bail out early if we've got a type-dependent expression.
1706*67e74705SXin Li if (collection->isTypeDependent()) return collection;
1707*67e74705SXin Li
1708*67e74705SXin Li // Perform normal l-value conversion.
1709*67e74705SXin Li result = DefaultFunctionArrayLvalueConversion(collection);
1710*67e74705SXin Li if (result.isInvalid())
1711*67e74705SXin Li return ExprError();
1712*67e74705SXin Li collection = result.get();
1713*67e74705SXin Li
1714*67e74705SXin Li // The operand needs to have object-pointer type.
1715*67e74705SXin Li // TODO: should we do a contextual conversion?
1716*67e74705SXin Li const ObjCObjectPointerType *pointerType =
1717*67e74705SXin Li collection->getType()->getAs<ObjCObjectPointerType>();
1718*67e74705SXin Li if (!pointerType)
1719*67e74705SXin Li return Diag(forLoc, diag::err_collection_expr_type)
1720*67e74705SXin Li << collection->getType() << collection->getSourceRange();
1721*67e74705SXin Li
1722*67e74705SXin Li // Check that the operand provides
1723*67e74705SXin Li // - countByEnumeratingWithState:objects:count:
1724*67e74705SXin Li const ObjCObjectType *objectType = pointerType->getObjectType();
1725*67e74705SXin Li ObjCInterfaceDecl *iface = objectType->getInterface();
1726*67e74705SXin Li
1727*67e74705SXin Li // If we have a forward-declared type, we can't do this check.
1728*67e74705SXin Li // Under ARC, it is an error not to have a forward-declared class.
1729*67e74705SXin Li if (iface &&
1730*67e74705SXin Li (getLangOpts().ObjCAutoRefCount
1731*67e74705SXin Li ? RequireCompleteType(forLoc, QualType(objectType, 0),
1732*67e74705SXin Li diag::err_arc_collection_forward, collection)
1733*67e74705SXin Li : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1734*67e74705SXin Li // Otherwise, if we have any useful type information, check that
1735*67e74705SXin Li // the type declares the appropriate method.
1736*67e74705SXin Li } else if (iface || !objectType->qual_empty()) {
1737*67e74705SXin Li IdentifierInfo *selectorIdents[] = {
1738*67e74705SXin Li &Context.Idents.get("countByEnumeratingWithState"),
1739*67e74705SXin Li &Context.Idents.get("objects"),
1740*67e74705SXin Li &Context.Idents.get("count")
1741*67e74705SXin Li };
1742*67e74705SXin Li Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1743*67e74705SXin Li
1744*67e74705SXin Li ObjCMethodDecl *method = nullptr;
1745*67e74705SXin Li
1746*67e74705SXin Li // If there's an interface, look in both the public and private APIs.
1747*67e74705SXin Li if (iface) {
1748*67e74705SXin Li method = iface->lookupInstanceMethod(selector);
1749*67e74705SXin Li if (!method) method = iface->lookupPrivateMethod(selector);
1750*67e74705SXin Li }
1751*67e74705SXin Li
1752*67e74705SXin Li // Also check protocol qualifiers.
1753*67e74705SXin Li if (!method)
1754*67e74705SXin Li method = LookupMethodInQualifiedType(selector, pointerType,
1755*67e74705SXin Li /*instance*/ true);
1756*67e74705SXin Li
1757*67e74705SXin Li // If we didn't find it anywhere, give up.
1758*67e74705SXin Li if (!method) {
1759*67e74705SXin Li Diag(forLoc, diag::warn_collection_expr_type)
1760*67e74705SXin Li << collection->getType() << selector << collection->getSourceRange();
1761*67e74705SXin Li }
1762*67e74705SXin Li
1763*67e74705SXin Li // TODO: check for an incompatible signature?
1764*67e74705SXin Li }
1765*67e74705SXin Li
1766*67e74705SXin Li // Wrap up any cleanups in the expression.
1767*67e74705SXin Li return collection;
1768*67e74705SXin Li }
1769*67e74705SXin Li
1770*67e74705SXin Li StmtResult
ActOnObjCForCollectionStmt(SourceLocation ForLoc,Stmt * First,Expr * collection,SourceLocation RParenLoc)1771*67e74705SXin Li Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1772*67e74705SXin Li Stmt *First, Expr *collection,
1773*67e74705SXin Li SourceLocation RParenLoc) {
1774*67e74705SXin Li
1775*67e74705SXin Li ExprResult CollectionExprResult =
1776*67e74705SXin Li CheckObjCForCollectionOperand(ForLoc, collection);
1777*67e74705SXin Li
1778*67e74705SXin Li if (First) {
1779*67e74705SXin Li QualType FirstType;
1780*67e74705SXin Li if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1781*67e74705SXin Li if (!DS->isSingleDecl())
1782*67e74705SXin Li return StmtError(Diag((*DS->decl_begin())->getLocation(),
1783*67e74705SXin Li diag::err_toomany_element_decls));
1784*67e74705SXin Li
1785*67e74705SXin Li VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1786*67e74705SXin Li if (!D || D->isInvalidDecl())
1787*67e74705SXin Li return StmtError();
1788*67e74705SXin Li
1789*67e74705SXin Li FirstType = D->getType();
1790*67e74705SXin Li // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1791*67e74705SXin Li // declare identifiers for objects having storage class 'auto' or
1792*67e74705SXin Li // 'register'.
1793*67e74705SXin Li if (!D->hasLocalStorage())
1794*67e74705SXin Li return StmtError(Diag(D->getLocation(),
1795*67e74705SXin Li diag::err_non_local_variable_decl_in_for));
1796*67e74705SXin Li
1797*67e74705SXin Li // If the type contained 'auto', deduce the 'auto' to 'id'.
1798*67e74705SXin Li if (FirstType->getContainedAutoType()) {
1799*67e74705SXin Li OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1800*67e74705SXin Li VK_RValue);
1801*67e74705SXin Li Expr *DeducedInit = &OpaqueId;
1802*67e74705SXin Li if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1803*67e74705SXin Li DAR_Failed)
1804*67e74705SXin Li DiagnoseAutoDeductionFailure(D, DeducedInit);
1805*67e74705SXin Li if (FirstType.isNull()) {
1806*67e74705SXin Li D->setInvalidDecl();
1807*67e74705SXin Li return StmtError();
1808*67e74705SXin Li }
1809*67e74705SXin Li
1810*67e74705SXin Li D->setType(FirstType);
1811*67e74705SXin Li
1812*67e74705SXin Li if (ActiveTemplateInstantiations.empty()) {
1813*67e74705SXin Li SourceLocation Loc =
1814*67e74705SXin Li D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1815*67e74705SXin Li Diag(Loc, diag::warn_auto_var_is_id)
1816*67e74705SXin Li << D->getDeclName();
1817*67e74705SXin Li }
1818*67e74705SXin Li }
1819*67e74705SXin Li
1820*67e74705SXin Li } else {
1821*67e74705SXin Li Expr *FirstE = cast<Expr>(First);
1822*67e74705SXin Li if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1823*67e74705SXin Li return StmtError(Diag(First->getLocStart(),
1824*67e74705SXin Li diag::err_selector_element_not_lvalue)
1825*67e74705SXin Li << First->getSourceRange());
1826*67e74705SXin Li
1827*67e74705SXin Li FirstType = static_cast<Expr*>(First)->getType();
1828*67e74705SXin Li if (FirstType.isConstQualified())
1829*67e74705SXin Li Diag(ForLoc, diag::err_selector_element_const_type)
1830*67e74705SXin Li << FirstType << First->getSourceRange();
1831*67e74705SXin Li }
1832*67e74705SXin Li if (!FirstType->isDependentType() &&
1833*67e74705SXin Li !FirstType->isObjCObjectPointerType() &&
1834*67e74705SXin Li !FirstType->isBlockPointerType())
1835*67e74705SXin Li return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1836*67e74705SXin Li << FirstType << First->getSourceRange());
1837*67e74705SXin Li }
1838*67e74705SXin Li
1839*67e74705SXin Li if (CollectionExprResult.isInvalid())
1840*67e74705SXin Li return StmtError();
1841*67e74705SXin Li
1842*67e74705SXin Li CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1843*67e74705SXin Li if (CollectionExprResult.isInvalid())
1844*67e74705SXin Li return StmtError();
1845*67e74705SXin Li
1846*67e74705SXin Li return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1847*67e74705SXin Li nullptr, ForLoc, RParenLoc);
1848*67e74705SXin Li }
1849*67e74705SXin Li
1850*67e74705SXin Li /// Finish building a variable declaration for a for-range statement.
1851*67e74705SXin Li /// \return true if an error occurs.
FinishForRangeVarDecl(Sema & SemaRef,VarDecl * Decl,Expr * Init,SourceLocation Loc,int DiagID)1852*67e74705SXin Li static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1853*67e74705SXin Li SourceLocation Loc, int DiagID) {
1854*67e74705SXin Li if (Decl->getType()->isUndeducedType()) {
1855*67e74705SXin Li ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1856*67e74705SXin Li if (!Res.isUsable()) {
1857*67e74705SXin Li Decl->setInvalidDecl();
1858*67e74705SXin Li return true;
1859*67e74705SXin Li }
1860*67e74705SXin Li Init = Res.get();
1861*67e74705SXin Li }
1862*67e74705SXin Li
1863*67e74705SXin Li // Deduce the type for the iterator variable now rather than leaving it to
1864*67e74705SXin Li // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1865*67e74705SXin Li QualType InitType;
1866*67e74705SXin Li if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1867*67e74705SXin Li SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1868*67e74705SXin Li Sema::DAR_Failed)
1869*67e74705SXin Li SemaRef.Diag(Loc, DiagID) << Init->getType();
1870*67e74705SXin Li if (InitType.isNull()) {
1871*67e74705SXin Li Decl->setInvalidDecl();
1872*67e74705SXin Li return true;
1873*67e74705SXin Li }
1874*67e74705SXin Li Decl->setType(InitType);
1875*67e74705SXin Li
1876*67e74705SXin Li // In ARC, infer lifetime.
1877*67e74705SXin Li // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1878*67e74705SXin Li // we're doing the equivalent of fast iteration.
1879*67e74705SXin Li if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1880*67e74705SXin Li SemaRef.inferObjCARCLifetime(Decl))
1881*67e74705SXin Li Decl->setInvalidDecl();
1882*67e74705SXin Li
1883*67e74705SXin Li SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1884*67e74705SXin Li /*TypeMayContainAuto=*/false);
1885*67e74705SXin Li SemaRef.FinalizeDeclaration(Decl);
1886*67e74705SXin Li SemaRef.CurContext->addHiddenDecl(Decl);
1887*67e74705SXin Li return false;
1888*67e74705SXin Li }
1889*67e74705SXin Li
1890*67e74705SXin Li namespace {
1891*67e74705SXin Li // An enum to represent whether something is dealing with a call to begin()
1892*67e74705SXin Li // or a call to end() in a range-based for loop.
1893*67e74705SXin Li enum BeginEndFunction {
1894*67e74705SXin Li BEF_begin,
1895*67e74705SXin Li BEF_end
1896*67e74705SXin Li };
1897*67e74705SXin Li
1898*67e74705SXin Li /// Produce a note indicating which begin/end function was implicitly called
1899*67e74705SXin Li /// by a C++11 for-range statement. This is often not obvious from the code,
1900*67e74705SXin Li /// nor from the diagnostics produced when analysing the implicit expressions
1901*67e74705SXin Li /// required in a for-range statement.
NoteForRangeBeginEndFunction(Sema & SemaRef,Expr * E,BeginEndFunction BEF)1902*67e74705SXin Li void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1903*67e74705SXin Li BeginEndFunction BEF) {
1904*67e74705SXin Li CallExpr *CE = dyn_cast<CallExpr>(E);
1905*67e74705SXin Li if (!CE)
1906*67e74705SXin Li return;
1907*67e74705SXin Li FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1908*67e74705SXin Li if (!D)
1909*67e74705SXin Li return;
1910*67e74705SXin Li SourceLocation Loc = D->getLocation();
1911*67e74705SXin Li
1912*67e74705SXin Li std::string Description;
1913*67e74705SXin Li bool IsTemplate = false;
1914*67e74705SXin Li if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1915*67e74705SXin Li Description = SemaRef.getTemplateArgumentBindingsText(
1916*67e74705SXin Li FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1917*67e74705SXin Li IsTemplate = true;
1918*67e74705SXin Li }
1919*67e74705SXin Li
1920*67e74705SXin Li SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1921*67e74705SXin Li << BEF << IsTemplate << Description << E->getType();
1922*67e74705SXin Li }
1923*67e74705SXin Li
1924*67e74705SXin Li /// Build a variable declaration for a for-range statement.
BuildForRangeVarDecl(Sema & SemaRef,SourceLocation Loc,QualType Type,const char * Name)1925*67e74705SXin Li VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1926*67e74705SXin Li QualType Type, const char *Name) {
1927*67e74705SXin Li DeclContext *DC = SemaRef.CurContext;
1928*67e74705SXin Li IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1929*67e74705SXin Li TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1930*67e74705SXin Li VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1931*67e74705SXin Li TInfo, SC_None);
1932*67e74705SXin Li Decl->setImplicit();
1933*67e74705SXin Li return Decl;
1934*67e74705SXin Li }
1935*67e74705SXin Li
1936*67e74705SXin Li }
1937*67e74705SXin Li
ObjCEnumerationCollection(Expr * Collection)1938*67e74705SXin Li static bool ObjCEnumerationCollection(Expr *Collection) {
1939*67e74705SXin Li return !Collection->isTypeDependent()
1940*67e74705SXin Li && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1941*67e74705SXin Li }
1942*67e74705SXin Li
1943*67e74705SXin Li /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1944*67e74705SXin Li ///
1945*67e74705SXin Li /// C++11 [stmt.ranged]:
1946*67e74705SXin Li /// A range-based for statement is equivalent to
1947*67e74705SXin Li ///
1948*67e74705SXin Li /// {
1949*67e74705SXin Li /// auto && __range = range-init;
1950*67e74705SXin Li /// for ( auto __begin = begin-expr,
1951*67e74705SXin Li /// __end = end-expr;
1952*67e74705SXin Li /// __begin != __end;
1953*67e74705SXin Li /// ++__begin ) {
1954*67e74705SXin Li /// for-range-declaration = *__begin;
1955*67e74705SXin Li /// statement
1956*67e74705SXin Li /// }
1957*67e74705SXin Li /// }
1958*67e74705SXin Li ///
1959*67e74705SXin Li /// The body of the loop is not available yet, since it cannot be analysed until
1960*67e74705SXin Li /// we have determined the type of the for-range-declaration.
ActOnCXXForRangeStmt(Scope * S,SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * First,SourceLocation ColonLoc,Expr * Range,SourceLocation RParenLoc,BuildForRangeKind Kind)1961*67e74705SXin Li StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1962*67e74705SXin Li SourceLocation CoawaitLoc, Stmt *First,
1963*67e74705SXin Li SourceLocation ColonLoc, Expr *Range,
1964*67e74705SXin Li SourceLocation RParenLoc,
1965*67e74705SXin Li BuildForRangeKind Kind) {
1966*67e74705SXin Li if (!First)
1967*67e74705SXin Li return StmtError();
1968*67e74705SXin Li
1969*67e74705SXin Li if (Range && ObjCEnumerationCollection(Range))
1970*67e74705SXin Li return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1971*67e74705SXin Li
1972*67e74705SXin Li DeclStmt *DS = dyn_cast<DeclStmt>(First);
1973*67e74705SXin Li assert(DS && "first part of for range not a decl stmt");
1974*67e74705SXin Li
1975*67e74705SXin Li if (!DS->isSingleDecl()) {
1976*67e74705SXin Li Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1977*67e74705SXin Li return StmtError();
1978*67e74705SXin Li }
1979*67e74705SXin Li
1980*67e74705SXin Li Decl *LoopVar = DS->getSingleDecl();
1981*67e74705SXin Li if (LoopVar->isInvalidDecl() || !Range ||
1982*67e74705SXin Li DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1983*67e74705SXin Li LoopVar->setInvalidDecl();
1984*67e74705SXin Li return StmtError();
1985*67e74705SXin Li }
1986*67e74705SXin Li
1987*67e74705SXin Li // Coroutines: 'for co_await' implicitly co_awaits its range.
1988*67e74705SXin Li if (CoawaitLoc.isValid()) {
1989*67e74705SXin Li ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
1990*67e74705SXin Li if (Coawait.isInvalid()) return StmtError();
1991*67e74705SXin Li Range = Coawait.get();
1992*67e74705SXin Li }
1993*67e74705SXin Li
1994*67e74705SXin Li // Build auto && __range = range-init
1995*67e74705SXin Li SourceLocation RangeLoc = Range->getLocStart();
1996*67e74705SXin Li VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1997*67e74705SXin Li Context.getAutoRRefDeductType(),
1998*67e74705SXin Li "__range");
1999*67e74705SXin Li if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2000*67e74705SXin Li diag::err_for_range_deduction_failure)) {
2001*67e74705SXin Li LoopVar->setInvalidDecl();
2002*67e74705SXin Li return StmtError();
2003*67e74705SXin Li }
2004*67e74705SXin Li
2005*67e74705SXin Li // Claim the type doesn't contain auto: we've already done the checking.
2006*67e74705SXin Li DeclGroupPtrTy RangeGroup =
2007*67e74705SXin Li BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
2008*67e74705SXin Li /*TypeMayContainAuto=*/ false);
2009*67e74705SXin Li StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2010*67e74705SXin Li if (RangeDecl.isInvalid()) {
2011*67e74705SXin Li LoopVar->setInvalidDecl();
2012*67e74705SXin Li return StmtError();
2013*67e74705SXin Li }
2014*67e74705SXin Li
2015*67e74705SXin Li return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
2016*67e74705SXin Li /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2017*67e74705SXin Li /*Cond=*/nullptr, /*Inc=*/nullptr,
2018*67e74705SXin Li DS, RParenLoc, Kind);
2019*67e74705SXin Li }
2020*67e74705SXin Li
2021*67e74705SXin Li /// \brief Create the initialization, compare, and increment steps for
2022*67e74705SXin Li /// the range-based for loop expression.
2023*67e74705SXin Li /// This function does not handle array-based for loops,
2024*67e74705SXin Li /// which are created in Sema::BuildCXXForRangeStmt.
2025*67e74705SXin Li ///
2026*67e74705SXin Li /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2027*67e74705SXin Li /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2028*67e74705SXin Li /// CandidateSet and BEF are set and some non-success value is returned on
2029*67e74705SXin Li /// failure.
BuildNonArrayForRange(Sema & SemaRef,Expr * BeginRange,Expr * EndRange,QualType RangeType,VarDecl * BeginVar,VarDecl * EndVar,SourceLocation ColonLoc,OverloadCandidateSet * CandidateSet,ExprResult * BeginExpr,ExprResult * EndExpr,BeginEndFunction * BEF)2030*67e74705SXin Li static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
2031*67e74705SXin Li Expr *BeginRange, Expr *EndRange,
2032*67e74705SXin Li QualType RangeType,
2033*67e74705SXin Li VarDecl *BeginVar,
2034*67e74705SXin Li VarDecl *EndVar,
2035*67e74705SXin Li SourceLocation ColonLoc,
2036*67e74705SXin Li OverloadCandidateSet *CandidateSet,
2037*67e74705SXin Li ExprResult *BeginExpr,
2038*67e74705SXin Li ExprResult *EndExpr,
2039*67e74705SXin Li BeginEndFunction *BEF) {
2040*67e74705SXin Li DeclarationNameInfo BeginNameInfo(
2041*67e74705SXin Li &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2042*67e74705SXin Li DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2043*67e74705SXin Li ColonLoc);
2044*67e74705SXin Li
2045*67e74705SXin Li LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2046*67e74705SXin Li Sema::LookupMemberName);
2047*67e74705SXin Li LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2048*67e74705SXin Li
2049*67e74705SXin Li if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2050*67e74705SXin Li // - if _RangeT is a class type, the unqualified-ids begin and end are
2051*67e74705SXin Li // looked up in the scope of class _RangeT as if by class member access
2052*67e74705SXin Li // lookup (3.4.5), and if either (or both) finds at least one
2053*67e74705SXin Li // declaration, begin-expr and end-expr are __range.begin() and
2054*67e74705SXin Li // __range.end(), respectively;
2055*67e74705SXin Li SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2056*67e74705SXin Li SemaRef.LookupQualifiedName(EndMemberLookup, D);
2057*67e74705SXin Li
2058*67e74705SXin Li if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2059*67e74705SXin Li SourceLocation RangeLoc = BeginVar->getLocation();
2060*67e74705SXin Li *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
2061*67e74705SXin Li
2062*67e74705SXin Li SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2063*67e74705SXin Li << RangeLoc << BeginRange->getType() << *BEF;
2064*67e74705SXin Li return Sema::FRS_DiagnosticIssued;
2065*67e74705SXin Li }
2066*67e74705SXin Li } else {
2067*67e74705SXin Li // - otherwise, begin-expr and end-expr are begin(__range) and
2068*67e74705SXin Li // end(__range), respectively, where begin and end are looked up with
2069*67e74705SXin Li // argument-dependent lookup (3.4.2). For the purposes of this name
2070*67e74705SXin Li // lookup, namespace std is an associated namespace.
2071*67e74705SXin Li
2072*67e74705SXin Li }
2073*67e74705SXin Li
2074*67e74705SXin Li *BEF = BEF_begin;
2075*67e74705SXin Li Sema::ForRangeStatus RangeStatus =
2076*67e74705SXin Li SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2077*67e74705SXin Li BeginMemberLookup, CandidateSet,
2078*67e74705SXin Li BeginRange, BeginExpr);
2079*67e74705SXin Li
2080*67e74705SXin Li if (RangeStatus != Sema::FRS_Success) {
2081*67e74705SXin Li if (RangeStatus == Sema::FRS_DiagnosticIssued)
2082*67e74705SXin Li SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2083*67e74705SXin Li << ColonLoc << BEF_begin << BeginRange->getType();
2084*67e74705SXin Li return RangeStatus;
2085*67e74705SXin Li }
2086*67e74705SXin Li if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2087*67e74705SXin Li diag::err_for_range_iter_deduction_failure)) {
2088*67e74705SXin Li NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2089*67e74705SXin Li return Sema::FRS_DiagnosticIssued;
2090*67e74705SXin Li }
2091*67e74705SXin Li
2092*67e74705SXin Li *BEF = BEF_end;
2093*67e74705SXin Li RangeStatus =
2094*67e74705SXin Li SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2095*67e74705SXin Li EndMemberLookup, CandidateSet,
2096*67e74705SXin Li EndRange, EndExpr);
2097*67e74705SXin Li if (RangeStatus != Sema::FRS_Success) {
2098*67e74705SXin Li if (RangeStatus == Sema::FRS_DiagnosticIssued)
2099*67e74705SXin Li SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2100*67e74705SXin Li << ColonLoc << BEF_end << EndRange->getType();
2101*67e74705SXin Li return RangeStatus;
2102*67e74705SXin Li }
2103*67e74705SXin Li if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2104*67e74705SXin Li diag::err_for_range_iter_deduction_failure)) {
2105*67e74705SXin Li NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2106*67e74705SXin Li return Sema::FRS_DiagnosticIssued;
2107*67e74705SXin Li }
2108*67e74705SXin Li return Sema::FRS_Success;
2109*67e74705SXin Li }
2110*67e74705SXin Li
2111*67e74705SXin Li /// Speculatively attempt to dereference an invalid range expression.
2112*67e74705SXin Li /// If the attempt fails, this function will return a valid, null StmtResult
2113*67e74705SXin Li /// and emit no diagnostics.
RebuildForRangeWithDereference(Sema & SemaRef,Scope * S,SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * LoopVarDecl,SourceLocation ColonLoc,Expr * Range,SourceLocation RangeLoc,SourceLocation RParenLoc)2114*67e74705SXin Li static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2115*67e74705SXin Li SourceLocation ForLoc,
2116*67e74705SXin Li SourceLocation CoawaitLoc,
2117*67e74705SXin Li Stmt *LoopVarDecl,
2118*67e74705SXin Li SourceLocation ColonLoc,
2119*67e74705SXin Li Expr *Range,
2120*67e74705SXin Li SourceLocation RangeLoc,
2121*67e74705SXin Li SourceLocation RParenLoc) {
2122*67e74705SXin Li // Determine whether we can rebuild the for-range statement with a
2123*67e74705SXin Li // dereferenced range expression.
2124*67e74705SXin Li ExprResult AdjustedRange;
2125*67e74705SXin Li {
2126*67e74705SXin Li Sema::SFINAETrap Trap(SemaRef);
2127*67e74705SXin Li
2128*67e74705SXin Li AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2129*67e74705SXin Li if (AdjustedRange.isInvalid())
2130*67e74705SXin Li return StmtResult();
2131*67e74705SXin Li
2132*67e74705SXin Li StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2133*67e74705SXin Li S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2134*67e74705SXin Li RParenLoc, Sema::BFRK_Check);
2135*67e74705SXin Li if (SR.isInvalid())
2136*67e74705SXin Li return StmtResult();
2137*67e74705SXin Li }
2138*67e74705SXin Li
2139*67e74705SXin Li // The attempt to dereference worked well enough that it could produce a valid
2140*67e74705SXin Li // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2141*67e74705SXin Li // case there are any other (non-fatal) problems with it.
2142*67e74705SXin Li SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2143*67e74705SXin Li << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2144*67e74705SXin Li return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2145*67e74705SXin Li ColonLoc, AdjustedRange.get(), RParenLoc,
2146*67e74705SXin Li Sema::BFRK_Rebuild);
2147*67e74705SXin Li }
2148*67e74705SXin Li
2149*67e74705SXin Li namespace {
2150*67e74705SXin Li /// RAII object to automatically invalidate a declaration if an error occurs.
2151*67e74705SXin Li struct InvalidateOnErrorScope {
InvalidateOnErrorScope__anonececbb350611::InvalidateOnErrorScope2152*67e74705SXin Li InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2153*67e74705SXin Li : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
~InvalidateOnErrorScope__anonececbb350611::InvalidateOnErrorScope2154*67e74705SXin Li ~InvalidateOnErrorScope() {
2155*67e74705SXin Li if (Enabled && Trap.hasErrorOccurred())
2156*67e74705SXin Li D->setInvalidDecl();
2157*67e74705SXin Li }
2158*67e74705SXin Li
2159*67e74705SXin Li DiagnosticErrorTrap Trap;
2160*67e74705SXin Li Decl *D;
2161*67e74705SXin Li bool Enabled;
2162*67e74705SXin Li };
2163*67e74705SXin Li }
2164*67e74705SXin Li
2165*67e74705SXin Li /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2166*67e74705SXin Li StmtResult
BuildCXXForRangeStmt(SourceLocation ForLoc,SourceLocation CoawaitLoc,SourceLocation ColonLoc,Stmt * RangeDecl,Stmt * Begin,Stmt * End,Expr * Cond,Expr * Inc,Stmt * LoopVarDecl,SourceLocation RParenLoc,BuildForRangeKind Kind)2167*67e74705SXin Li Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2168*67e74705SXin Li SourceLocation ColonLoc, Stmt *RangeDecl,
2169*67e74705SXin Li Stmt *Begin, Stmt *End, Expr *Cond,
2170*67e74705SXin Li Expr *Inc, Stmt *LoopVarDecl,
2171*67e74705SXin Li SourceLocation RParenLoc, BuildForRangeKind Kind) {
2172*67e74705SXin Li // FIXME: This should not be used during template instantiation. We should
2173*67e74705SXin Li // pick up the set of unqualified lookup results for the != and + operators
2174*67e74705SXin Li // in the initial parse.
2175*67e74705SXin Li //
2176*67e74705SXin Li // Testcase (accepts-invalid):
2177*67e74705SXin Li // template<typename T> void f() { for (auto x : T()) {} }
2178*67e74705SXin Li // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2179*67e74705SXin Li // bool operator!=(N::X, N::X); void operator++(N::X);
2180*67e74705SXin Li // void g() { f<N::X>(); }
2181*67e74705SXin Li Scope *S = getCurScope();
2182*67e74705SXin Li
2183*67e74705SXin Li DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2184*67e74705SXin Li VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2185*67e74705SXin Li QualType RangeVarType = RangeVar->getType();
2186*67e74705SXin Li
2187*67e74705SXin Li DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2188*67e74705SXin Li VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2189*67e74705SXin Li
2190*67e74705SXin Li // If we hit any errors, mark the loop variable as invalid if its type
2191*67e74705SXin Li // contains 'auto'.
2192*67e74705SXin Li InvalidateOnErrorScope Invalidate(*this, LoopVar,
2193*67e74705SXin Li LoopVar->getType()->isUndeducedType());
2194*67e74705SXin Li
2195*67e74705SXin Li StmtResult BeginDeclStmt = Begin;
2196*67e74705SXin Li StmtResult EndDeclStmt = End;
2197*67e74705SXin Li ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2198*67e74705SXin Li
2199*67e74705SXin Li if (RangeVarType->isDependentType()) {
2200*67e74705SXin Li // The range is implicitly used as a placeholder when it is dependent.
2201*67e74705SXin Li RangeVar->markUsed(Context);
2202*67e74705SXin Li
2203*67e74705SXin Li // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2204*67e74705SXin Li // them in properly when we instantiate the loop.
2205*67e74705SXin Li if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2206*67e74705SXin Li LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2207*67e74705SXin Li } else if (!BeginDeclStmt.get()) {
2208*67e74705SXin Li SourceLocation RangeLoc = RangeVar->getLocation();
2209*67e74705SXin Li
2210*67e74705SXin Li const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2211*67e74705SXin Li
2212*67e74705SXin Li ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2213*67e74705SXin Li VK_LValue, ColonLoc);
2214*67e74705SXin Li if (BeginRangeRef.isInvalid())
2215*67e74705SXin Li return StmtError();
2216*67e74705SXin Li
2217*67e74705SXin Li ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2218*67e74705SXin Li VK_LValue, ColonLoc);
2219*67e74705SXin Li if (EndRangeRef.isInvalid())
2220*67e74705SXin Li return StmtError();
2221*67e74705SXin Li
2222*67e74705SXin Li QualType AutoType = Context.getAutoDeductType();
2223*67e74705SXin Li Expr *Range = RangeVar->getInit();
2224*67e74705SXin Li if (!Range)
2225*67e74705SXin Li return StmtError();
2226*67e74705SXin Li QualType RangeType = Range->getType();
2227*67e74705SXin Li
2228*67e74705SXin Li if (RequireCompleteType(RangeLoc, RangeType,
2229*67e74705SXin Li diag::err_for_range_incomplete_type))
2230*67e74705SXin Li return StmtError();
2231*67e74705SXin Li
2232*67e74705SXin Li // Build auto __begin = begin-expr, __end = end-expr.
2233*67e74705SXin Li VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2234*67e74705SXin Li "__begin");
2235*67e74705SXin Li VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2236*67e74705SXin Li "__end");
2237*67e74705SXin Li
2238*67e74705SXin Li // Build begin-expr and end-expr and attach to __begin and __end variables.
2239*67e74705SXin Li ExprResult BeginExpr, EndExpr;
2240*67e74705SXin Li if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2241*67e74705SXin Li // - if _RangeT is an array type, begin-expr and end-expr are __range and
2242*67e74705SXin Li // __range + __bound, respectively, where __bound is the array bound. If
2243*67e74705SXin Li // _RangeT is an array of unknown size or an array of incomplete type,
2244*67e74705SXin Li // the program is ill-formed;
2245*67e74705SXin Li
2246*67e74705SXin Li // begin-expr is __range.
2247*67e74705SXin Li BeginExpr = BeginRangeRef;
2248*67e74705SXin Li if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2249*67e74705SXin Li diag::err_for_range_iter_deduction_failure)) {
2250*67e74705SXin Li NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2251*67e74705SXin Li return StmtError();
2252*67e74705SXin Li }
2253*67e74705SXin Li
2254*67e74705SXin Li // Find the array bound.
2255*67e74705SXin Li ExprResult BoundExpr;
2256*67e74705SXin Li if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2257*67e74705SXin Li BoundExpr = IntegerLiteral::Create(
2258*67e74705SXin Li Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2259*67e74705SXin Li else if (const VariableArrayType *VAT =
2260*67e74705SXin Li dyn_cast<VariableArrayType>(UnqAT))
2261*67e74705SXin Li BoundExpr = VAT->getSizeExpr();
2262*67e74705SXin Li else {
2263*67e74705SXin Li // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2264*67e74705SXin Li // UnqAT is not incomplete and Range is not type-dependent.
2265*67e74705SXin Li llvm_unreachable("Unexpected array type in for-range");
2266*67e74705SXin Li }
2267*67e74705SXin Li
2268*67e74705SXin Li // end-expr is __range + __bound.
2269*67e74705SXin Li EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2270*67e74705SXin Li BoundExpr.get());
2271*67e74705SXin Li if (EndExpr.isInvalid())
2272*67e74705SXin Li return StmtError();
2273*67e74705SXin Li if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2274*67e74705SXin Li diag::err_for_range_iter_deduction_failure)) {
2275*67e74705SXin Li NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2276*67e74705SXin Li return StmtError();
2277*67e74705SXin Li }
2278*67e74705SXin Li } else {
2279*67e74705SXin Li OverloadCandidateSet CandidateSet(RangeLoc,
2280*67e74705SXin Li OverloadCandidateSet::CSK_Normal);
2281*67e74705SXin Li BeginEndFunction BEFFailure;
2282*67e74705SXin Li ForRangeStatus RangeStatus =
2283*67e74705SXin Li BuildNonArrayForRange(*this, BeginRangeRef.get(),
2284*67e74705SXin Li EndRangeRef.get(), RangeType,
2285*67e74705SXin Li BeginVar, EndVar, ColonLoc, &CandidateSet,
2286*67e74705SXin Li &BeginExpr, &EndExpr, &BEFFailure);
2287*67e74705SXin Li
2288*67e74705SXin Li if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2289*67e74705SXin Li BEFFailure == BEF_begin) {
2290*67e74705SXin Li // If the range is being built from an array parameter, emit a
2291*67e74705SXin Li // a diagnostic that it is being treated as a pointer.
2292*67e74705SXin Li if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2293*67e74705SXin Li if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2294*67e74705SXin Li QualType ArrayTy = PVD->getOriginalType();
2295*67e74705SXin Li QualType PointerTy = PVD->getType();
2296*67e74705SXin Li if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2297*67e74705SXin Li Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2298*67e74705SXin Li << RangeLoc << PVD << ArrayTy << PointerTy;
2299*67e74705SXin Li Diag(PVD->getLocation(), diag::note_declared_at);
2300*67e74705SXin Li return StmtError();
2301*67e74705SXin Li }
2302*67e74705SXin Li }
2303*67e74705SXin Li }
2304*67e74705SXin Li
2305*67e74705SXin Li // If building the range failed, try dereferencing the range expression
2306*67e74705SXin Li // unless a diagnostic was issued or the end function is problematic.
2307*67e74705SXin Li StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2308*67e74705SXin Li CoawaitLoc,
2309*67e74705SXin Li LoopVarDecl, ColonLoc,
2310*67e74705SXin Li Range, RangeLoc,
2311*67e74705SXin Li RParenLoc);
2312*67e74705SXin Li if (SR.isInvalid() || SR.isUsable())
2313*67e74705SXin Li return SR;
2314*67e74705SXin Li }
2315*67e74705SXin Li
2316*67e74705SXin Li // Otherwise, emit diagnostics if we haven't already.
2317*67e74705SXin Li if (RangeStatus == FRS_NoViableFunction) {
2318*67e74705SXin Li Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2319*67e74705SXin Li Diag(Range->getLocStart(), diag::err_for_range_invalid)
2320*67e74705SXin Li << RangeLoc << Range->getType() << BEFFailure;
2321*67e74705SXin Li CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2322*67e74705SXin Li }
2323*67e74705SXin Li // Return an error if no fix was discovered.
2324*67e74705SXin Li if (RangeStatus != FRS_Success)
2325*67e74705SXin Li return StmtError();
2326*67e74705SXin Li }
2327*67e74705SXin Li
2328*67e74705SXin Li assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2329*67e74705SXin Li "invalid range expression in for loop");
2330*67e74705SXin Li
2331*67e74705SXin Li // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2332*67e74705SXin Li // C++1z removes this restriction.
2333*67e74705SXin Li QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2334*67e74705SXin Li if (!Context.hasSameType(BeginType, EndType)) {
2335*67e74705SXin Li Diag(RangeLoc, getLangOpts().CPlusPlus1z
2336*67e74705SXin Li ? diag::warn_for_range_begin_end_types_differ
2337*67e74705SXin Li : diag::ext_for_range_begin_end_types_differ)
2338*67e74705SXin Li << BeginType << EndType;
2339*67e74705SXin Li NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2340*67e74705SXin Li NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2341*67e74705SXin Li }
2342*67e74705SXin Li
2343*67e74705SXin Li BeginDeclStmt =
2344*67e74705SXin Li ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2345*67e74705SXin Li EndDeclStmt =
2346*67e74705SXin Li ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2347*67e74705SXin Li
2348*67e74705SXin Li const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2349*67e74705SXin Li ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2350*67e74705SXin Li VK_LValue, ColonLoc);
2351*67e74705SXin Li if (BeginRef.isInvalid())
2352*67e74705SXin Li return StmtError();
2353*67e74705SXin Li
2354*67e74705SXin Li ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2355*67e74705SXin Li VK_LValue, ColonLoc);
2356*67e74705SXin Li if (EndRef.isInvalid())
2357*67e74705SXin Li return StmtError();
2358*67e74705SXin Li
2359*67e74705SXin Li // Build and check __begin != __end expression.
2360*67e74705SXin Li NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2361*67e74705SXin Li BeginRef.get(), EndRef.get());
2362*67e74705SXin Li if (!NotEqExpr.isInvalid())
2363*67e74705SXin Li NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2364*67e74705SXin Li if (!NotEqExpr.isInvalid())
2365*67e74705SXin Li NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2366*67e74705SXin Li if (NotEqExpr.isInvalid()) {
2367*67e74705SXin Li Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2368*67e74705SXin Li << RangeLoc << 0 << BeginRangeRef.get()->getType();
2369*67e74705SXin Li NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2370*67e74705SXin Li if (!Context.hasSameType(BeginType, EndType))
2371*67e74705SXin Li NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2372*67e74705SXin Li return StmtError();
2373*67e74705SXin Li }
2374*67e74705SXin Li
2375*67e74705SXin Li // Build and check ++__begin expression.
2376*67e74705SXin Li BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2377*67e74705SXin Li VK_LValue, ColonLoc);
2378*67e74705SXin Li if (BeginRef.isInvalid())
2379*67e74705SXin Li return StmtError();
2380*67e74705SXin Li
2381*67e74705SXin Li IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2382*67e74705SXin Li if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2383*67e74705SXin Li IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2384*67e74705SXin Li if (!IncrExpr.isInvalid())
2385*67e74705SXin Li IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2386*67e74705SXin Li if (IncrExpr.isInvalid()) {
2387*67e74705SXin Li Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2388*67e74705SXin Li << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2389*67e74705SXin Li NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2390*67e74705SXin Li return StmtError();
2391*67e74705SXin Li }
2392*67e74705SXin Li
2393*67e74705SXin Li // Build and check *__begin expression.
2394*67e74705SXin Li BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2395*67e74705SXin Li VK_LValue, ColonLoc);
2396*67e74705SXin Li if (BeginRef.isInvalid())
2397*67e74705SXin Li return StmtError();
2398*67e74705SXin Li
2399*67e74705SXin Li ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2400*67e74705SXin Li if (DerefExpr.isInvalid()) {
2401*67e74705SXin Li Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2402*67e74705SXin Li << RangeLoc << 1 << BeginRangeRef.get()->getType();
2403*67e74705SXin Li NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2404*67e74705SXin Li return StmtError();
2405*67e74705SXin Li }
2406*67e74705SXin Li
2407*67e74705SXin Li // Attach *__begin as initializer for VD. Don't touch it if we're just
2408*67e74705SXin Li // trying to determine whether this would be a valid range.
2409*67e74705SXin Li if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2410*67e74705SXin Li AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2411*67e74705SXin Li /*TypeMayContainAuto=*/true);
2412*67e74705SXin Li if (LoopVar->isInvalidDecl())
2413*67e74705SXin Li NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2414*67e74705SXin Li }
2415*67e74705SXin Li }
2416*67e74705SXin Li
2417*67e74705SXin Li // Don't bother to actually allocate the result if we're just trying to
2418*67e74705SXin Li // determine whether it would be valid.
2419*67e74705SXin Li if (Kind == BFRK_Check)
2420*67e74705SXin Li return StmtResult();
2421*67e74705SXin Li
2422*67e74705SXin Li return new (Context) CXXForRangeStmt(
2423*67e74705SXin Li RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2424*67e74705SXin Li cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2425*67e74705SXin Li IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2426*67e74705SXin Li ColonLoc, RParenLoc);
2427*67e74705SXin Li }
2428*67e74705SXin Li
2429*67e74705SXin Li /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2430*67e74705SXin Li /// statement.
FinishObjCForCollectionStmt(Stmt * S,Stmt * B)2431*67e74705SXin Li StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2432*67e74705SXin Li if (!S || !B)
2433*67e74705SXin Li return StmtError();
2434*67e74705SXin Li ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2435*67e74705SXin Li
2436*67e74705SXin Li ForStmt->setBody(B);
2437*67e74705SXin Li return S;
2438*67e74705SXin Li }
2439*67e74705SXin Li
2440*67e74705SXin Li // Warn when the loop variable is a const reference that creates a copy.
2441*67e74705SXin Li // Suggest using the non-reference type for copies. If a copy can be prevented
2442*67e74705SXin Li // suggest the const reference type that would do so.
2443*67e74705SXin Li // For instance, given "for (const &Foo : Range)", suggest
2444*67e74705SXin Li // "for (const Foo : Range)" to denote a copy is made for the loop. If
2445*67e74705SXin Li // possible, also suggest "for (const &Bar : Range)" if this type prevents
2446*67e74705SXin Li // the copy altogether.
DiagnoseForRangeReferenceVariableCopies(Sema & SemaRef,const VarDecl * VD,QualType RangeInitType)2447*67e74705SXin Li static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2448*67e74705SXin Li const VarDecl *VD,
2449*67e74705SXin Li QualType RangeInitType) {
2450*67e74705SXin Li const Expr *InitExpr = VD->getInit();
2451*67e74705SXin Li if (!InitExpr)
2452*67e74705SXin Li return;
2453*67e74705SXin Li
2454*67e74705SXin Li QualType VariableType = VD->getType();
2455*67e74705SXin Li
2456*67e74705SXin Li if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2457*67e74705SXin Li if (!Cleanups->cleanupsHaveSideEffects())
2458*67e74705SXin Li InitExpr = Cleanups->getSubExpr();
2459*67e74705SXin Li
2460*67e74705SXin Li const MaterializeTemporaryExpr *MTE =
2461*67e74705SXin Li dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2462*67e74705SXin Li
2463*67e74705SXin Li // No copy made.
2464*67e74705SXin Li if (!MTE)
2465*67e74705SXin Li return;
2466*67e74705SXin Li
2467*67e74705SXin Li const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2468*67e74705SXin Li
2469*67e74705SXin Li // Searching for either UnaryOperator for dereference of a pointer or
2470*67e74705SXin Li // CXXOperatorCallExpr for handling iterators.
2471*67e74705SXin Li while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2472*67e74705SXin Li if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2473*67e74705SXin Li E = CCE->getArg(0);
2474*67e74705SXin Li } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2475*67e74705SXin Li const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2476*67e74705SXin Li E = ME->getBase();
2477*67e74705SXin Li } else {
2478*67e74705SXin Li const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2479*67e74705SXin Li E = MTE->GetTemporaryExpr();
2480*67e74705SXin Li }
2481*67e74705SXin Li E = E->IgnoreImpCasts();
2482*67e74705SXin Li }
2483*67e74705SXin Li
2484*67e74705SXin Li bool ReturnsReference = false;
2485*67e74705SXin Li if (isa<UnaryOperator>(E)) {
2486*67e74705SXin Li ReturnsReference = true;
2487*67e74705SXin Li } else {
2488*67e74705SXin Li const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2489*67e74705SXin Li const FunctionDecl *FD = Call->getDirectCallee();
2490*67e74705SXin Li QualType ReturnType = FD->getReturnType();
2491*67e74705SXin Li ReturnsReference = ReturnType->isReferenceType();
2492*67e74705SXin Li }
2493*67e74705SXin Li
2494*67e74705SXin Li if (ReturnsReference) {
2495*67e74705SXin Li // Loop variable creates a temporary. Suggest either to go with
2496*67e74705SXin Li // non-reference loop variable to indiciate a copy is made, or
2497*67e74705SXin Li // the correct time to bind a const reference.
2498*67e74705SXin Li SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2499*67e74705SXin Li << VD << VariableType << E->getType();
2500*67e74705SXin Li QualType NonReferenceType = VariableType.getNonReferenceType();
2501*67e74705SXin Li NonReferenceType.removeLocalConst();
2502*67e74705SXin Li QualType NewReferenceType =
2503*67e74705SXin Li SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2504*67e74705SXin Li SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2505*67e74705SXin Li << NonReferenceType << NewReferenceType << VD->getSourceRange();
2506*67e74705SXin Li } else {
2507*67e74705SXin Li // The range always returns a copy, so a temporary is always created.
2508*67e74705SXin Li // Suggest removing the reference from the loop variable.
2509*67e74705SXin Li SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2510*67e74705SXin Li << VD << RangeInitType;
2511*67e74705SXin Li QualType NonReferenceType = VariableType.getNonReferenceType();
2512*67e74705SXin Li NonReferenceType.removeLocalConst();
2513*67e74705SXin Li SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2514*67e74705SXin Li << NonReferenceType << VD->getSourceRange();
2515*67e74705SXin Li }
2516*67e74705SXin Li }
2517*67e74705SXin Li
2518*67e74705SXin Li // Warns when the loop variable can be changed to a reference type to
2519*67e74705SXin Li // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2520*67e74705SXin Li // "for (const Foo &x : Range)" if this form does not make a copy.
DiagnoseForRangeConstVariableCopies(Sema & SemaRef,const VarDecl * VD)2521*67e74705SXin Li static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2522*67e74705SXin Li const VarDecl *VD) {
2523*67e74705SXin Li const Expr *InitExpr = VD->getInit();
2524*67e74705SXin Li if (!InitExpr)
2525*67e74705SXin Li return;
2526*67e74705SXin Li
2527*67e74705SXin Li QualType VariableType = VD->getType();
2528*67e74705SXin Li
2529*67e74705SXin Li if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2530*67e74705SXin Li if (!CE->getConstructor()->isCopyConstructor())
2531*67e74705SXin Li return;
2532*67e74705SXin Li } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2533*67e74705SXin Li if (CE->getCastKind() != CK_LValueToRValue)
2534*67e74705SXin Li return;
2535*67e74705SXin Li } else {
2536*67e74705SXin Li return;
2537*67e74705SXin Li }
2538*67e74705SXin Li
2539*67e74705SXin Li // TODO: Determine a maximum size that a POD type can be before a diagnostic
2540*67e74705SXin Li // should be emitted. Also, only ignore POD types with trivial copy
2541*67e74705SXin Li // constructors.
2542*67e74705SXin Li if (VariableType.isPODType(SemaRef.Context))
2543*67e74705SXin Li return;
2544*67e74705SXin Li
2545*67e74705SXin Li // Suggest changing from a const variable to a const reference variable
2546*67e74705SXin Li // if doing so will prevent a copy.
2547*67e74705SXin Li SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2548*67e74705SXin Li << VD << VariableType << InitExpr->getType();
2549*67e74705SXin Li SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2550*67e74705SXin Li << SemaRef.Context.getLValueReferenceType(VariableType)
2551*67e74705SXin Li << VD->getSourceRange();
2552*67e74705SXin Li }
2553*67e74705SXin Li
2554*67e74705SXin Li /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2555*67e74705SXin Li /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2556*67e74705SXin Li /// using "const foo x" to show that a copy is made
2557*67e74705SXin Li /// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2558*67e74705SXin Li /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2559*67e74705SXin Li /// prevent the copy.
2560*67e74705SXin Li /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2561*67e74705SXin Li /// Suggest "const foo &x" to prevent the copy.
DiagnoseForRangeVariableCopies(Sema & SemaRef,const CXXForRangeStmt * ForStmt)2562*67e74705SXin Li static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2563*67e74705SXin Li const CXXForRangeStmt *ForStmt) {
2564*67e74705SXin Li if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2565*67e74705SXin Li ForStmt->getLocStart()) &&
2566*67e74705SXin Li SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2567*67e74705SXin Li ForStmt->getLocStart()) &&
2568*67e74705SXin Li SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2569*67e74705SXin Li ForStmt->getLocStart())) {
2570*67e74705SXin Li return;
2571*67e74705SXin Li }
2572*67e74705SXin Li
2573*67e74705SXin Li const VarDecl *VD = ForStmt->getLoopVariable();
2574*67e74705SXin Li if (!VD)
2575*67e74705SXin Li return;
2576*67e74705SXin Li
2577*67e74705SXin Li QualType VariableType = VD->getType();
2578*67e74705SXin Li
2579*67e74705SXin Li if (VariableType->isIncompleteType())
2580*67e74705SXin Li return;
2581*67e74705SXin Li
2582*67e74705SXin Li const Expr *InitExpr = VD->getInit();
2583*67e74705SXin Li if (!InitExpr)
2584*67e74705SXin Li return;
2585*67e74705SXin Li
2586*67e74705SXin Li if (VariableType->isReferenceType()) {
2587*67e74705SXin Li DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2588*67e74705SXin Li ForStmt->getRangeInit()->getType());
2589*67e74705SXin Li } else if (VariableType.isConstQualified()) {
2590*67e74705SXin Li DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2591*67e74705SXin Li }
2592*67e74705SXin Li }
2593*67e74705SXin Li
2594*67e74705SXin Li /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2595*67e74705SXin Li /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2596*67e74705SXin Li /// body cannot be performed until after the type of the range variable is
2597*67e74705SXin Li /// determined.
FinishCXXForRangeStmt(Stmt * S,Stmt * B)2598*67e74705SXin Li StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2599*67e74705SXin Li if (!S || !B)
2600*67e74705SXin Li return StmtError();
2601*67e74705SXin Li
2602*67e74705SXin Li if (isa<ObjCForCollectionStmt>(S))
2603*67e74705SXin Li return FinishObjCForCollectionStmt(S, B);
2604*67e74705SXin Li
2605*67e74705SXin Li CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2606*67e74705SXin Li ForStmt->setBody(B);
2607*67e74705SXin Li
2608*67e74705SXin Li DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2609*67e74705SXin Li diag::warn_empty_range_based_for_body);
2610*67e74705SXin Li
2611*67e74705SXin Li DiagnoseForRangeVariableCopies(*this, ForStmt);
2612*67e74705SXin Li
2613*67e74705SXin Li return S;
2614*67e74705SXin Li }
2615*67e74705SXin Li
ActOnGotoStmt(SourceLocation GotoLoc,SourceLocation LabelLoc,LabelDecl * TheDecl)2616*67e74705SXin Li StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2617*67e74705SXin Li SourceLocation LabelLoc,
2618*67e74705SXin Li LabelDecl *TheDecl) {
2619*67e74705SXin Li getCurFunction()->setHasBranchIntoScope();
2620*67e74705SXin Li TheDecl->markUsed(Context);
2621*67e74705SXin Li return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2622*67e74705SXin Li }
2623*67e74705SXin Li
2624*67e74705SXin Li StmtResult
ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,Expr * E)2625*67e74705SXin Li Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2626*67e74705SXin Li Expr *E) {
2627*67e74705SXin Li // Convert operand to void*
2628*67e74705SXin Li if (!E->isTypeDependent()) {
2629*67e74705SXin Li QualType ETy = E->getType();
2630*67e74705SXin Li QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2631*67e74705SXin Li ExprResult ExprRes = E;
2632*67e74705SXin Li AssignConvertType ConvTy =
2633*67e74705SXin Li CheckSingleAssignmentConstraints(DestTy, ExprRes);
2634*67e74705SXin Li if (ExprRes.isInvalid())
2635*67e74705SXin Li return StmtError();
2636*67e74705SXin Li E = ExprRes.get();
2637*67e74705SXin Li if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2638*67e74705SXin Li return StmtError();
2639*67e74705SXin Li }
2640*67e74705SXin Li
2641*67e74705SXin Li ExprResult ExprRes = ActOnFinishFullExpr(E);
2642*67e74705SXin Li if (ExprRes.isInvalid())
2643*67e74705SXin Li return StmtError();
2644*67e74705SXin Li E = ExprRes.get();
2645*67e74705SXin Li
2646*67e74705SXin Li getCurFunction()->setHasIndirectGoto();
2647*67e74705SXin Li
2648*67e74705SXin Li return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2649*67e74705SXin Li }
2650*67e74705SXin Li
CheckJumpOutOfSEHFinally(Sema & S,SourceLocation Loc,const Scope & DestScope)2651*67e74705SXin Li static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2652*67e74705SXin Li const Scope &DestScope) {
2653*67e74705SXin Li if (!S.CurrentSEHFinally.empty() &&
2654*67e74705SXin Li DestScope.Contains(*S.CurrentSEHFinally.back())) {
2655*67e74705SXin Li S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2656*67e74705SXin Li }
2657*67e74705SXin Li }
2658*67e74705SXin Li
2659*67e74705SXin Li StmtResult
ActOnContinueStmt(SourceLocation ContinueLoc,Scope * CurScope)2660*67e74705SXin Li Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2661*67e74705SXin Li Scope *S = CurScope->getContinueParent();
2662*67e74705SXin Li if (!S) {
2663*67e74705SXin Li // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2664*67e74705SXin Li return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2665*67e74705SXin Li }
2666*67e74705SXin Li CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2667*67e74705SXin Li
2668*67e74705SXin Li return new (Context) ContinueStmt(ContinueLoc);
2669*67e74705SXin Li }
2670*67e74705SXin Li
2671*67e74705SXin Li StmtResult
ActOnBreakStmt(SourceLocation BreakLoc,Scope * CurScope)2672*67e74705SXin Li Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2673*67e74705SXin Li Scope *S = CurScope->getBreakParent();
2674*67e74705SXin Li if (!S) {
2675*67e74705SXin Li // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2676*67e74705SXin Li return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2677*67e74705SXin Li }
2678*67e74705SXin Li if (S->isOpenMPLoopScope())
2679*67e74705SXin Li return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2680*67e74705SXin Li << "break");
2681*67e74705SXin Li CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2682*67e74705SXin Li
2683*67e74705SXin Li return new (Context) BreakStmt(BreakLoc);
2684*67e74705SXin Li }
2685*67e74705SXin Li
2686*67e74705SXin Li /// \brief Determine whether the given expression is a candidate for
2687*67e74705SXin Li /// copy elision in either a return statement or a throw expression.
2688*67e74705SXin Li ///
2689*67e74705SXin Li /// \param ReturnType If we're determining the copy elision candidate for
2690*67e74705SXin Li /// a return statement, this is the return type of the function. If we're
2691*67e74705SXin Li /// determining the copy elision candidate for a throw expression, this will
2692*67e74705SXin Li /// be a NULL type.
2693*67e74705SXin Li ///
2694*67e74705SXin Li /// \param E The expression being returned from the function or block, or
2695*67e74705SXin Li /// being thrown.
2696*67e74705SXin Li ///
2697*67e74705SXin Li /// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2698*67e74705SXin Li /// id-expressions that could be moved out of the function to be considered NRVO
2699*67e74705SXin Li /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2700*67e74705SXin Li /// determine whether we should try to move as part of a return or throw (which
2701*67e74705SXin Li /// does allow function parameters).
2702*67e74705SXin Li ///
2703*67e74705SXin Li /// \returns The NRVO candidate variable, if the return statement may use the
2704*67e74705SXin Li /// NRVO, or NULL if there is no such candidate.
getCopyElisionCandidate(QualType ReturnType,Expr * E,bool AllowParamOrMoveConstructible)2705*67e74705SXin Li VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2706*67e74705SXin Li bool AllowParamOrMoveConstructible) {
2707*67e74705SXin Li if (!getLangOpts().CPlusPlus)
2708*67e74705SXin Li return nullptr;
2709*67e74705SXin Li
2710*67e74705SXin Li // - in a return statement in a function [where] ...
2711*67e74705SXin Li // ... the expression is the name of a non-volatile automatic object ...
2712*67e74705SXin Li DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2713*67e74705SXin Li if (!DR || DR->refersToEnclosingVariableOrCapture())
2714*67e74705SXin Li return nullptr;
2715*67e74705SXin Li VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2716*67e74705SXin Li if (!VD)
2717*67e74705SXin Li return nullptr;
2718*67e74705SXin Li
2719*67e74705SXin Li if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
2720*67e74705SXin Li return VD;
2721*67e74705SXin Li return nullptr;
2722*67e74705SXin Li }
2723*67e74705SXin Li
isCopyElisionCandidate(QualType ReturnType,const VarDecl * VD,bool AllowParamOrMoveConstructible)2724*67e74705SXin Li bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2725*67e74705SXin Li bool AllowParamOrMoveConstructible) {
2726*67e74705SXin Li QualType VDType = VD->getType();
2727*67e74705SXin Li // - in a return statement in a function with ...
2728*67e74705SXin Li // ... a class return type ...
2729*67e74705SXin Li if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2730*67e74705SXin Li if (!ReturnType->isRecordType())
2731*67e74705SXin Li return false;
2732*67e74705SXin Li // ... the same cv-unqualified type as the function return type ...
2733*67e74705SXin Li // When considering moving this expression out, allow dissimilar types.
2734*67e74705SXin Li if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
2735*67e74705SXin Li !Context.hasSameUnqualifiedType(ReturnType, VDType))
2736*67e74705SXin Li return false;
2737*67e74705SXin Li }
2738*67e74705SXin Li
2739*67e74705SXin Li // ...object (other than a function or catch-clause parameter)...
2740*67e74705SXin Li if (VD->getKind() != Decl::Var &&
2741*67e74705SXin Li !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
2742*67e74705SXin Li return false;
2743*67e74705SXin Li if (VD->isExceptionVariable()) return false;
2744*67e74705SXin Li
2745*67e74705SXin Li // ...automatic...
2746*67e74705SXin Li if (!VD->hasLocalStorage()) return false;
2747*67e74705SXin Li
2748*67e74705SXin Li if (AllowParamOrMoveConstructible)
2749*67e74705SXin Li return true;
2750*67e74705SXin Li
2751*67e74705SXin Li // ...non-volatile...
2752*67e74705SXin Li if (VD->getType().isVolatileQualified()) return false;
2753*67e74705SXin Li
2754*67e74705SXin Li // __block variables can't be allocated in a way that permits NRVO.
2755*67e74705SXin Li if (VD->hasAttr<BlocksAttr>()) return false;
2756*67e74705SXin Li
2757*67e74705SXin Li // Variables with higher required alignment than their type's ABI
2758*67e74705SXin Li // alignment cannot use NRVO.
2759*67e74705SXin Li if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2760*67e74705SXin Li Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2761*67e74705SXin Li return false;
2762*67e74705SXin Li
2763*67e74705SXin Li return true;
2764*67e74705SXin Li }
2765*67e74705SXin Li
2766*67e74705SXin Li /// \brief Perform the initialization of a potentially-movable value, which
2767*67e74705SXin Li /// is the result of return value.
2768*67e74705SXin Li ///
2769*67e74705SXin Li /// This routine implements C++14 [class.copy]p32, which attempts to treat
2770*67e74705SXin Li /// returned lvalues as rvalues in certain cases (to prefer move construction),
2771*67e74705SXin Li /// then falls back to treating them as lvalues if that failed.
2772*67e74705SXin Li ExprResult
PerformMoveOrCopyInitialization(const InitializedEntity & Entity,const VarDecl * NRVOCandidate,QualType ResultType,Expr * Value,bool AllowNRVO)2773*67e74705SXin Li Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2774*67e74705SXin Li const VarDecl *NRVOCandidate,
2775*67e74705SXin Li QualType ResultType,
2776*67e74705SXin Li Expr *Value,
2777*67e74705SXin Li bool AllowNRVO) {
2778*67e74705SXin Li // C++14 [class.copy]p32:
2779*67e74705SXin Li // When the criteria for elision of a copy/move operation are met, but not for
2780*67e74705SXin Li // an exception-declaration, and the object to be copied is designated by an
2781*67e74705SXin Li // lvalue, or when the expression in a return statement is a (possibly
2782*67e74705SXin Li // parenthesized) id-expression that names an object with automatic storage
2783*67e74705SXin Li // duration declared in the body or parameter-declaration-clause of the
2784*67e74705SXin Li // innermost enclosing function or lambda-expression, overload resolution to
2785*67e74705SXin Li // select the constructor for the copy is first performed as if the object
2786*67e74705SXin Li // were designated by an rvalue.
2787*67e74705SXin Li ExprResult Res = ExprError();
2788*67e74705SXin Li
2789*67e74705SXin Li if (AllowNRVO && !NRVOCandidate)
2790*67e74705SXin Li NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2791*67e74705SXin Li
2792*67e74705SXin Li if (AllowNRVO && NRVOCandidate) {
2793*67e74705SXin Li ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2794*67e74705SXin Li CK_NoOp, Value, VK_XValue);
2795*67e74705SXin Li
2796*67e74705SXin Li Expr *InitExpr = &AsRvalue;
2797*67e74705SXin Li
2798*67e74705SXin Li InitializationKind Kind = InitializationKind::CreateCopy(
2799*67e74705SXin Li Value->getLocStart(), Value->getLocStart());
2800*67e74705SXin Li
2801*67e74705SXin Li InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2802*67e74705SXin Li if (Seq) {
2803*67e74705SXin Li for (const InitializationSequence::Step &Step : Seq.steps()) {
2804*67e74705SXin Li if (!(Step.Kind ==
2805*67e74705SXin Li InitializationSequence::SK_ConstructorInitialization ||
2806*67e74705SXin Li (Step.Kind == InitializationSequence::SK_UserConversion &&
2807*67e74705SXin Li isa<CXXConstructorDecl>(Step.Function.Function))))
2808*67e74705SXin Li continue;
2809*67e74705SXin Li
2810*67e74705SXin Li CXXConstructorDecl *Constructor =
2811*67e74705SXin Li cast<CXXConstructorDecl>(Step.Function.Function);
2812*67e74705SXin Li
2813*67e74705SXin Li const RValueReferenceType *RRefType
2814*67e74705SXin Li = Constructor->getParamDecl(0)->getType()
2815*67e74705SXin Li ->getAs<RValueReferenceType>();
2816*67e74705SXin Li
2817*67e74705SXin Li // [...] If the first overload resolution fails or was not performed, or
2818*67e74705SXin Li // if the type of the first parameter of the selected constructor is not
2819*67e74705SXin Li // an rvalue reference to the object’s type (possibly cv-qualified),
2820*67e74705SXin Li // overload resolution is performed again, considering the object as an
2821*67e74705SXin Li // lvalue.
2822*67e74705SXin Li if (!RRefType ||
2823*67e74705SXin Li !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2824*67e74705SXin Li NRVOCandidate->getType()))
2825*67e74705SXin Li break;
2826*67e74705SXin Li
2827*67e74705SXin Li // Promote "AsRvalue" to the heap, since we now need this
2828*67e74705SXin Li // expression node to persist.
2829*67e74705SXin Li Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2830*67e74705SXin Li Value, nullptr, VK_XValue);
2831*67e74705SXin Li
2832*67e74705SXin Li // Complete type-checking the initialization of the return type
2833*67e74705SXin Li // using the constructor we found.
2834*67e74705SXin Li Res = Seq.Perform(*this, Entity, Kind, Value);
2835*67e74705SXin Li }
2836*67e74705SXin Li }
2837*67e74705SXin Li }
2838*67e74705SXin Li
2839*67e74705SXin Li // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2840*67e74705SXin Li // above, or overload resolution failed. Either way, we need to try
2841*67e74705SXin Li // (again) now with the return value expression as written.
2842*67e74705SXin Li if (Res.isInvalid())
2843*67e74705SXin Li Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2844*67e74705SXin Li
2845*67e74705SXin Li return Res;
2846*67e74705SXin Li }
2847*67e74705SXin Li
2848*67e74705SXin Li /// \brief Determine whether the declared return type of the specified function
2849*67e74705SXin Li /// contains 'auto'.
hasDeducedReturnType(FunctionDecl * FD)2850*67e74705SXin Li static bool hasDeducedReturnType(FunctionDecl *FD) {
2851*67e74705SXin Li const FunctionProtoType *FPT =
2852*67e74705SXin Li FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2853*67e74705SXin Li return FPT->getReturnType()->isUndeducedType();
2854*67e74705SXin Li }
2855*67e74705SXin Li
2856*67e74705SXin Li /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2857*67e74705SXin Li /// for capturing scopes.
2858*67e74705SXin Li ///
2859*67e74705SXin Li StmtResult
ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp)2860*67e74705SXin Li Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2861*67e74705SXin Li // If this is the first return we've seen, infer the return type.
2862*67e74705SXin Li // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2863*67e74705SXin Li CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2864*67e74705SXin Li QualType FnRetType = CurCap->ReturnType;
2865*67e74705SXin Li LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2866*67e74705SXin Li bool HasDeducedReturnType =
2867*67e74705SXin Li CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
2868*67e74705SXin Li
2869*67e74705SXin Li if (ExprEvalContexts.back().Context == DiscardedStatement &&
2870*67e74705SXin Li (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
2871*67e74705SXin Li if (RetValExp) {
2872*67e74705SXin Li ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2873*67e74705SXin Li if (ER.isInvalid())
2874*67e74705SXin Li return StmtError();
2875*67e74705SXin Li RetValExp = ER.get();
2876*67e74705SXin Li }
2877*67e74705SXin Li return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2878*67e74705SXin Li }
2879*67e74705SXin Li
2880*67e74705SXin Li if (HasDeducedReturnType) {
2881*67e74705SXin Li // In C++1y, the return type may involve 'auto'.
2882*67e74705SXin Li // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2883*67e74705SXin Li FunctionDecl *FD = CurLambda->CallOperator;
2884*67e74705SXin Li if (CurCap->ReturnType.isNull())
2885*67e74705SXin Li CurCap->ReturnType = FD->getReturnType();
2886*67e74705SXin Li
2887*67e74705SXin Li AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2888*67e74705SXin Li assert(AT && "lost auto type from lambda return type");
2889*67e74705SXin Li if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2890*67e74705SXin Li FD->setInvalidDecl();
2891*67e74705SXin Li return StmtError();
2892*67e74705SXin Li }
2893*67e74705SXin Li CurCap->ReturnType = FnRetType = FD->getReturnType();
2894*67e74705SXin Li } else if (CurCap->HasImplicitReturnType) {
2895*67e74705SXin Li // For blocks/lambdas with implicit return types, we check each return
2896*67e74705SXin Li // statement individually, and deduce the common return type when the block
2897*67e74705SXin Li // or lambda is completed.
2898*67e74705SXin Li // FIXME: Fold this into the 'auto' codepath above.
2899*67e74705SXin Li if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2900*67e74705SXin Li ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2901*67e74705SXin Li if (Result.isInvalid())
2902*67e74705SXin Li return StmtError();
2903*67e74705SXin Li RetValExp = Result.get();
2904*67e74705SXin Li
2905*67e74705SXin Li // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2906*67e74705SXin Li // when deducing a return type for a lambda-expression (or by extension
2907*67e74705SXin Li // for a block). These rules differ from the stated C++11 rules only in
2908*67e74705SXin Li // that they remove top-level cv-qualifiers.
2909*67e74705SXin Li if (!CurContext->isDependentContext())
2910*67e74705SXin Li FnRetType = RetValExp->getType().getUnqualifiedType();
2911*67e74705SXin Li else
2912*67e74705SXin Li FnRetType = CurCap->ReturnType = Context.DependentTy;
2913*67e74705SXin Li } else {
2914*67e74705SXin Li if (RetValExp) {
2915*67e74705SXin Li // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2916*67e74705SXin Li // initializer list, because it is not an expression (even
2917*67e74705SXin Li // though we represent it as one). We still deduce 'void'.
2918*67e74705SXin Li Diag(ReturnLoc, diag::err_lambda_return_init_list)
2919*67e74705SXin Li << RetValExp->getSourceRange();
2920*67e74705SXin Li }
2921*67e74705SXin Li
2922*67e74705SXin Li FnRetType = Context.VoidTy;
2923*67e74705SXin Li }
2924*67e74705SXin Li
2925*67e74705SXin Li // Although we'll properly infer the type of the block once it's completed,
2926*67e74705SXin Li // make sure we provide a return type now for better error recovery.
2927*67e74705SXin Li if (CurCap->ReturnType.isNull())
2928*67e74705SXin Li CurCap->ReturnType = FnRetType;
2929*67e74705SXin Li }
2930*67e74705SXin Li assert(!FnRetType.isNull());
2931*67e74705SXin Li
2932*67e74705SXin Li if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2933*67e74705SXin Li if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2934*67e74705SXin Li Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2935*67e74705SXin Li return StmtError();
2936*67e74705SXin Li }
2937*67e74705SXin Li } else if (CapturedRegionScopeInfo *CurRegion =
2938*67e74705SXin Li dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2939*67e74705SXin Li Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2940*67e74705SXin Li return StmtError();
2941*67e74705SXin Li } else {
2942*67e74705SXin Li assert(CurLambda && "unknown kind of captured scope");
2943*67e74705SXin Li if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2944*67e74705SXin Li ->getNoReturnAttr()) {
2945*67e74705SXin Li Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2946*67e74705SXin Li return StmtError();
2947*67e74705SXin Li }
2948*67e74705SXin Li }
2949*67e74705SXin Li
2950*67e74705SXin Li // Otherwise, verify that this result type matches the previous one. We are
2951*67e74705SXin Li // pickier with blocks than for normal functions because we don't have GCC
2952*67e74705SXin Li // compatibility to worry about here.
2953*67e74705SXin Li const VarDecl *NRVOCandidate = nullptr;
2954*67e74705SXin Li if (FnRetType->isDependentType()) {
2955*67e74705SXin Li // Delay processing for now. TODO: there are lots of dependent
2956*67e74705SXin Li // types we can conclusively prove aren't void.
2957*67e74705SXin Li } else if (FnRetType->isVoidType()) {
2958*67e74705SXin Li if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2959*67e74705SXin Li !(getLangOpts().CPlusPlus &&
2960*67e74705SXin Li (RetValExp->isTypeDependent() ||
2961*67e74705SXin Li RetValExp->getType()->isVoidType()))) {
2962*67e74705SXin Li if (!getLangOpts().CPlusPlus &&
2963*67e74705SXin Li RetValExp->getType()->isVoidType())
2964*67e74705SXin Li Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2965*67e74705SXin Li else {
2966*67e74705SXin Li Diag(ReturnLoc, diag::err_return_block_has_expr);
2967*67e74705SXin Li RetValExp = nullptr;
2968*67e74705SXin Li }
2969*67e74705SXin Li }
2970*67e74705SXin Li } else if (!RetValExp) {
2971*67e74705SXin Li return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2972*67e74705SXin Li } else if (!RetValExp->isTypeDependent()) {
2973*67e74705SXin Li // we have a non-void block with an expression, continue checking
2974*67e74705SXin Li
2975*67e74705SXin Li // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2976*67e74705SXin Li // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2977*67e74705SXin Li // function return.
2978*67e74705SXin Li
2979*67e74705SXin Li // In C++ the return statement is handled via a copy initialization.
2980*67e74705SXin Li // the C version of which boils down to CheckSingleAssignmentConstraints.
2981*67e74705SXin Li NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2982*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2983*67e74705SXin Li FnRetType,
2984*67e74705SXin Li NRVOCandidate != nullptr);
2985*67e74705SXin Li ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2986*67e74705SXin Li FnRetType, RetValExp);
2987*67e74705SXin Li if (Res.isInvalid()) {
2988*67e74705SXin Li // FIXME: Cleanup temporaries here, anyway?
2989*67e74705SXin Li return StmtError();
2990*67e74705SXin Li }
2991*67e74705SXin Li RetValExp = Res.get();
2992*67e74705SXin Li CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2993*67e74705SXin Li } else {
2994*67e74705SXin Li NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2995*67e74705SXin Li }
2996*67e74705SXin Li
2997*67e74705SXin Li if (RetValExp) {
2998*67e74705SXin Li ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2999*67e74705SXin Li if (ER.isInvalid())
3000*67e74705SXin Li return StmtError();
3001*67e74705SXin Li RetValExp = ER.get();
3002*67e74705SXin Li }
3003*67e74705SXin Li ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3004*67e74705SXin Li NRVOCandidate);
3005*67e74705SXin Li
3006*67e74705SXin Li // If we need to check for the named return value optimization,
3007*67e74705SXin Li // or if we need to infer the return type,
3008*67e74705SXin Li // save the return statement in our scope for later processing.
3009*67e74705SXin Li if (CurCap->HasImplicitReturnType || NRVOCandidate)
3010*67e74705SXin Li FunctionScopes.back()->Returns.push_back(Result);
3011*67e74705SXin Li
3012*67e74705SXin Li if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3013*67e74705SXin Li FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3014*67e74705SXin Li
3015*67e74705SXin Li return Result;
3016*67e74705SXin Li }
3017*67e74705SXin Li
3018*67e74705SXin Li namespace {
3019*67e74705SXin Li /// \brief Marks all typedefs in all local classes in a type referenced.
3020*67e74705SXin Li ///
3021*67e74705SXin Li /// In a function like
3022*67e74705SXin Li /// auto f() {
3023*67e74705SXin Li /// struct S { typedef int a; };
3024*67e74705SXin Li /// return S();
3025*67e74705SXin Li /// }
3026*67e74705SXin Li ///
3027*67e74705SXin Li /// the local type escapes and could be referenced in some TUs but not in
3028*67e74705SXin Li /// others. Pretend that all local typedefs are always referenced, to not warn
3029*67e74705SXin Li /// on this. This isn't necessary if f has internal linkage, or the typedef
3030*67e74705SXin Li /// is private.
3031*67e74705SXin Li class LocalTypedefNameReferencer
3032*67e74705SXin Li : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3033*67e74705SXin Li public:
LocalTypedefNameReferencer(Sema & S)3034*67e74705SXin Li LocalTypedefNameReferencer(Sema &S) : S(S) {}
3035*67e74705SXin Li bool VisitRecordType(const RecordType *RT);
3036*67e74705SXin Li private:
3037*67e74705SXin Li Sema &S;
3038*67e74705SXin Li };
VisitRecordType(const RecordType * RT)3039*67e74705SXin Li bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3040*67e74705SXin Li auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3041*67e74705SXin Li if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3042*67e74705SXin Li R->isDependentType())
3043*67e74705SXin Li return true;
3044*67e74705SXin Li for (auto *TmpD : R->decls())
3045*67e74705SXin Li if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3046*67e74705SXin Li if (T->getAccess() != AS_private || R->hasFriends())
3047*67e74705SXin Li S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3048*67e74705SXin Li return true;
3049*67e74705SXin Li }
3050*67e74705SXin Li }
3051*67e74705SXin Li
getReturnTypeLoc(FunctionDecl * FD) const3052*67e74705SXin Li TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3053*67e74705SXin Li TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3054*67e74705SXin Li while (auto ATL = TL.getAs<AttributedTypeLoc>())
3055*67e74705SXin Li TL = ATL.getModifiedLoc().IgnoreParens();
3056*67e74705SXin Li return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3057*67e74705SXin Li }
3058*67e74705SXin Li
3059*67e74705SXin Li /// Deduce the return type for a function from a returned expression, per
3060*67e74705SXin Li /// C++1y [dcl.spec.auto]p6.
DeduceFunctionTypeFromReturnExpr(FunctionDecl * FD,SourceLocation ReturnLoc,Expr * & RetExpr,AutoType * AT)3061*67e74705SXin Li bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3062*67e74705SXin Li SourceLocation ReturnLoc,
3063*67e74705SXin Li Expr *&RetExpr,
3064*67e74705SXin Li AutoType *AT) {
3065*67e74705SXin Li TypeLoc OrigResultType = getReturnTypeLoc(FD);
3066*67e74705SXin Li QualType Deduced;
3067*67e74705SXin Li
3068*67e74705SXin Li if (RetExpr && isa<InitListExpr>(RetExpr)) {
3069*67e74705SXin Li // If the deduction is for a return statement and the initializer is
3070*67e74705SXin Li // a braced-init-list, the program is ill-formed.
3071*67e74705SXin Li Diag(RetExpr->getExprLoc(),
3072*67e74705SXin Li getCurLambda() ? diag::err_lambda_return_init_list
3073*67e74705SXin Li : diag::err_auto_fn_return_init_list)
3074*67e74705SXin Li << RetExpr->getSourceRange();
3075*67e74705SXin Li return true;
3076*67e74705SXin Li }
3077*67e74705SXin Li
3078*67e74705SXin Li if (FD->isDependentContext()) {
3079*67e74705SXin Li // C++1y [dcl.spec.auto]p12:
3080*67e74705SXin Li // Return type deduction [...] occurs when the definition is
3081*67e74705SXin Li // instantiated even if the function body contains a return
3082*67e74705SXin Li // statement with a non-type-dependent operand.
3083*67e74705SXin Li assert(AT->isDeduced() && "should have deduced to dependent type");
3084*67e74705SXin Li return false;
3085*67e74705SXin Li }
3086*67e74705SXin Li
3087*67e74705SXin Li if (RetExpr) {
3088*67e74705SXin Li // Otherwise, [...] deduce a value for U using the rules of template
3089*67e74705SXin Li // argument deduction.
3090*67e74705SXin Li DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3091*67e74705SXin Li
3092*67e74705SXin Li if (DAR == DAR_Failed && !FD->isInvalidDecl())
3093*67e74705SXin Li Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3094*67e74705SXin Li << OrigResultType.getType() << RetExpr->getType();
3095*67e74705SXin Li
3096*67e74705SXin Li if (DAR != DAR_Succeeded)
3097*67e74705SXin Li return true;
3098*67e74705SXin Li
3099*67e74705SXin Li // If a local type is part of the returned type, mark its fields as
3100*67e74705SXin Li // referenced.
3101*67e74705SXin Li LocalTypedefNameReferencer Referencer(*this);
3102*67e74705SXin Li Referencer.TraverseType(RetExpr->getType());
3103*67e74705SXin Li } else {
3104*67e74705SXin Li // In the case of a return with no operand, the initializer is considered
3105*67e74705SXin Li // to be void().
3106*67e74705SXin Li //
3107*67e74705SXin Li // Deduction here can only succeed if the return type is exactly 'cv auto'
3108*67e74705SXin Li // or 'decltype(auto)', so just check for that case directly.
3109*67e74705SXin Li if (!OrigResultType.getType()->getAs<AutoType>()) {
3110*67e74705SXin Li Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3111*67e74705SXin Li << OrigResultType.getType();
3112*67e74705SXin Li return true;
3113*67e74705SXin Li }
3114*67e74705SXin Li // We always deduce U = void in this case.
3115*67e74705SXin Li Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3116*67e74705SXin Li if (Deduced.isNull())
3117*67e74705SXin Li return true;
3118*67e74705SXin Li }
3119*67e74705SXin Li
3120*67e74705SXin Li // If a function with a declared return type that contains a placeholder type
3121*67e74705SXin Li // has multiple return statements, the return type is deduced for each return
3122*67e74705SXin Li // statement. [...] if the type deduced is not the same in each deduction,
3123*67e74705SXin Li // the program is ill-formed.
3124*67e74705SXin Li QualType DeducedT = AT->getDeducedType();
3125*67e74705SXin Li if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3126*67e74705SXin Li AutoType *NewAT = Deduced->getContainedAutoType();
3127*67e74705SXin Li // It is possible that NewAT->getDeducedType() is null. When that happens,
3128*67e74705SXin Li // we should not crash, instead we ignore this deduction.
3129*67e74705SXin Li if (NewAT->getDeducedType().isNull())
3130*67e74705SXin Li return false;
3131*67e74705SXin Li
3132*67e74705SXin Li CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3133*67e74705SXin Li DeducedT);
3134*67e74705SXin Li CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3135*67e74705SXin Li NewAT->getDeducedType());
3136*67e74705SXin Li if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3137*67e74705SXin Li const LambdaScopeInfo *LambdaSI = getCurLambda();
3138*67e74705SXin Li if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3139*67e74705SXin Li Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3140*67e74705SXin Li << NewAT->getDeducedType() << DeducedT
3141*67e74705SXin Li << true /*IsLambda*/;
3142*67e74705SXin Li } else {
3143*67e74705SXin Li Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3144*67e74705SXin Li << (AT->isDecltypeAuto() ? 1 : 0)
3145*67e74705SXin Li << NewAT->getDeducedType() << DeducedT;
3146*67e74705SXin Li }
3147*67e74705SXin Li return true;
3148*67e74705SXin Li }
3149*67e74705SXin Li } else if (!FD->isInvalidDecl()) {
3150*67e74705SXin Li // Update all declarations of the function to have the deduced return type.
3151*67e74705SXin Li Context.adjustDeducedFunctionResultType(FD, Deduced);
3152*67e74705SXin Li }
3153*67e74705SXin Li
3154*67e74705SXin Li return false;
3155*67e74705SXin Li }
3156*67e74705SXin Li
3157*67e74705SXin Li StmtResult
ActOnReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,Scope * CurScope)3158*67e74705SXin Li Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3159*67e74705SXin Li Scope *CurScope) {
3160*67e74705SXin Li StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3161*67e74705SXin Li if (R.isInvalid() || ExprEvalContexts.back().Context == DiscardedStatement)
3162*67e74705SXin Li return R;
3163*67e74705SXin Li
3164*67e74705SXin Li if (VarDecl *VD =
3165*67e74705SXin Li const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3166*67e74705SXin Li CurScope->addNRVOCandidate(VD);
3167*67e74705SXin Li } else {
3168*67e74705SXin Li CurScope->setNoNRVO();
3169*67e74705SXin Li }
3170*67e74705SXin Li
3171*67e74705SXin Li CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3172*67e74705SXin Li
3173*67e74705SXin Li return R;
3174*67e74705SXin Li }
3175*67e74705SXin Li
BuildReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp)3176*67e74705SXin Li StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3177*67e74705SXin Li // Check for unexpanded parameter packs.
3178*67e74705SXin Li if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3179*67e74705SXin Li return StmtError();
3180*67e74705SXin Li
3181*67e74705SXin Li if (isa<CapturingScopeInfo>(getCurFunction()))
3182*67e74705SXin Li return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3183*67e74705SXin Li
3184*67e74705SXin Li QualType FnRetType;
3185*67e74705SXin Li QualType RelatedRetType;
3186*67e74705SXin Li const AttrVec *Attrs = nullptr;
3187*67e74705SXin Li bool isObjCMethod = false;
3188*67e74705SXin Li
3189*67e74705SXin Li if (const FunctionDecl *FD = getCurFunctionDecl()) {
3190*67e74705SXin Li FnRetType = FD->getReturnType();
3191*67e74705SXin Li if (FD->hasAttrs())
3192*67e74705SXin Li Attrs = &FD->getAttrs();
3193*67e74705SXin Li if (FD->isNoReturn())
3194*67e74705SXin Li Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3195*67e74705SXin Li << FD->getDeclName();
3196*67e74705SXin Li } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3197*67e74705SXin Li FnRetType = MD->getReturnType();
3198*67e74705SXin Li isObjCMethod = true;
3199*67e74705SXin Li if (MD->hasAttrs())
3200*67e74705SXin Li Attrs = &MD->getAttrs();
3201*67e74705SXin Li if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3202*67e74705SXin Li // In the implementation of a method with a related return type, the
3203*67e74705SXin Li // type used to type-check the validity of return statements within the
3204*67e74705SXin Li // method body is a pointer to the type of the class being implemented.
3205*67e74705SXin Li RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3206*67e74705SXin Li RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3207*67e74705SXin Li }
3208*67e74705SXin Li } else // If we don't have a function/method context, bail.
3209*67e74705SXin Li return StmtError();
3210*67e74705SXin Li
3211*67e74705SXin Li // C++1z: discarded return statements are not considered when deducing a
3212*67e74705SXin Li // return type.
3213*67e74705SXin Li if (ExprEvalContexts.back().Context == DiscardedStatement &&
3214*67e74705SXin Li FnRetType->getContainedAutoType()) {
3215*67e74705SXin Li if (RetValExp) {
3216*67e74705SXin Li ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3217*67e74705SXin Li if (ER.isInvalid())
3218*67e74705SXin Li return StmtError();
3219*67e74705SXin Li RetValExp = ER.get();
3220*67e74705SXin Li }
3221*67e74705SXin Li return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3222*67e74705SXin Li }
3223*67e74705SXin Li
3224*67e74705SXin Li // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3225*67e74705SXin Li // deduction.
3226*67e74705SXin Li if (getLangOpts().CPlusPlus14) {
3227*67e74705SXin Li if (AutoType *AT = FnRetType->getContainedAutoType()) {
3228*67e74705SXin Li FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3229*67e74705SXin Li if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3230*67e74705SXin Li FD->setInvalidDecl();
3231*67e74705SXin Li return StmtError();
3232*67e74705SXin Li } else {
3233*67e74705SXin Li FnRetType = FD->getReturnType();
3234*67e74705SXin Li }
3235*67e74705SXin Li }
3236*67e74705SXin Li }
3237*67e74705SXin Li
3238*67e74705SXin Li bool HasDependentReturnType = FnRetType->isDependentType();
3239*67e74705SXin Li
3240*67e74705SXin Li ReturnStmt *Result = nullptr;
3241*67e74705SXin Li if (FnRetType->isVoidType()) {
3242*67e74705SXin Li if (RetValExp) {
3243*67e74705SXin Li if (isa<InitListExpr>(RetValExp)) {
3244*67e74705SXin Li // We simply never allow init lists as the return value of void
3245*67e74705SXin Li // functions. This is compatible because this was never allowed before,
3246*67e74705SXin Li // so there's no legacy code to deal with.
3247*67e74705SXin Li NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3248*67e74705SXin Li int FunctionKind = 0;
3249*67e74705SXin Li if (isa<ObjCMethodDecl>(CurDecl))
3250*67e74705SXin Li FunctionKind = 1;
3251*67e74705SXin Li else if (isa<CXXConstructorDecl>(CurDecl))
3252*67e74705SXin Li FunctionKind = 2;
3253*67e74705SXin Li else if (isa<CXXDestructorDecl>(CurDecl))
3254*67e74705SXin Li FunctionKind = 3;
3255*67e74705SXin Li
3256*67e74705SXin Li Diag(ReturnLoc, diag::err_return_init_list)
3257*67e74705SXin Li << CurDecl->getDeclName() << FunctionKind
3258*67e74705SXin Li << RetValExp->getSourceRange();
3259*67e74705SXin Li
3260*67e74705SXin Li // Drop the expression.
3261*67e74705SXin Li RetValExp = nullptr;
3262*67e74705SXin Li } else if (!RetValExp->isTypeDependent()) {
3263*67e74705SXin Li // C99 6.8.6.4p1 (ext_ since GCC warns)
3264*67e74705SXin Li unsigned D = diag::ext_return_has_expr;
3265*67e74705SXin Li if (RetValExp->getType()->isVoidType()) {
3266*67e74705SXin Li NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3267*67e74705SXin Li if (isa<CXXConstructorDecl>(CurDecl) ||
3268*67e74705SXin Li isa<CXXDestructorDecl>(CurDecl))
3269*67e74705SXin Li D = diag::err_ctor_dtor_returns_void;
3270*67e74705SXin Li else
3271*67e74705SXin Li D = diag::ext_return_has_void_expr;
3272*67e74705SXin Li }
3273*67e74705SXin Li else {
3274*67e74705SXin Li ExprResult Result = RetValExp;
3275*67e74705SXin Li Result = IgnoredValueConversions(Result.get());
3276*67e74705SXin Li if (Result.isInvalid())
3277*67e74705SXin Li return StmtError();
3278*67e74705SXin Li RetValExp = Result.get();
3279*67e74705SXin Li RetValExp = ImpCastExprToType(RetValExp,
3280*67e74705SXin Li Context.VoidTy, CK_ToVoid).get();
3281*67e74705SXin Li }
3282*67e74705SXin Li // return of void in constructor/destructor is illegal in C++.
3283*67e74705SXin Li if (D == diag::err_ctor_dtor_returns_void) {
3284*67e74705SXin Li NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3285*67e74705SXin Li Diag(ReturnLoc, D)
3286*67e74705SXin Li << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3287*67e74705SXin Li << RetValExp->getSourceRange();
3288*67e74705SXin Li }
3289*67e74705SXin Li // return (some void expression); is legal in C++.
3290*67e74705SXin Li else if (D != diag::ext_return_has_void_expr ||
3291*67e74705SXin Li !getLangOpts().CPlusPlus) {
3292*67e74705SXin Li NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3293*67e74705SXin Li
3294*67e74705SXin Li int FunctionKind = 0;
3295*67e74705SXin Li if (isa<ObjCMethodDecl>(CurDecl))
3296*67e74705SXin Li FunctionKind = 1;
3297*67e74705SXin Li else if (isa<CXXConstructorDecl>(CurDecl))
3298*67e74705SXin Li FunctionKind = 2;
3299*67e74705SXin Li else if (isa<CXXDestructorDecl>(CurDecl))
3300*67e74705SXin Li FunctionKind = 3;
3301*67e74705SXin Li
3302*67e74705SXin Li Diag(ReturnLoc, D)
3303*67e74705SXin Li << CurDecl->getDeclName() << FunctionKind
3304*67e74705SXin Li << RetValExp->getSourceRange();
3305*67e74705SXin Li }
3306*67e74705SXin Li }
3307*67e74705SXin Li
3308*67e74705SXin Li if (RetValExp) {
3309*67e74705SXin Li ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3310*67e74705SXin Li if (ER.isInvalid())
3311*67e74705SXin Li return StmtError();
3312*67e74705SXin Li RetValExp = ER.get();
3313*67e74705SXin Li }
3314*67e74705SXin Li }
3315*67e74705SXin Li
3316*67e74705SXin Li Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3317*67e74705SXin Li } else if (!RetValExp && !HasDependentReturnType) {
3318*67e74705SXin Li FunctionDecl *FD = getCurFunctionDecl();
3319*67e74705SXin Li
3320*67e74705SXin Li unsigned DiagID;
3321*67e74705SXin Li if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3322*67e74705SXin Li // C++11 [stmt.return]p2
3323*67e74705SXin Li DiagID = diag::err_constexpr_return_missing_expr;
3324*67e74705SXin Li FD->setInvalidDecl();
3325*67e74705SXin Li } else if (getLangOpts().C99) {
3326*67e74705SXin Li // C99 6.8.6.4p1 (ext_ since GCC warns)
3327*67e74705SXin Li DiagID = diag::ext_return_missing_expr;
3328*67e74705SXin Li } else {
3329*67e74705SXin Li // C90 6.6.6.4p4
3330*67e74705SXin Li DiagID = diag::warn_return_missing_expr;
3331*67e74705SXin Li }
3332*67e74705SXin Li
3333*67e74705SXin Li if (FD)
3334*67e74705SXin Li Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3335*67e74705SXin Li else
3336*67e74705SXin Li Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3337*67e74705SXin Li
3338*67e74705SXin Li Result = new (Context) ReturnStmt(ReturnLoc);
3339*67e74705SXin Li } else {
3340*67e74705SXin Li assert(RetValExp || HasDependentReturnType);
3341*67e74705SXin Li const VarDecl *NRVOCandidate = nullptr;
3342*67e74705SXin Li
3343*67e74705SXin Li QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3344*67e74705SXin Li
3345*67e74705SXin Li // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3346*67e74705SXin Li // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3347*67e74705SXin Li // function return.
3348*67e74705SXin Li
3349*67e74705SXin Li // In C++ the return statement is handled via a copy initialization,
3350*67e74705SXin Li // the C version of which boils down to CheckSingleAssignmentConstraints.
3351*67e74705SXin Li if (RetValExp)
3352*67e74705SXin Li NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3353*67e74705SXin Li if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3354*67e74705SXin Li // we have a non-void function with an expression, continue checking
3355*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3356*67e74705SXin Li RetType,
3357*67e74705SXin Li NRVOCandidate != nullptr);
3358*67e74705SXin Li ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3359*67e74705SXin Li RetType, RetValExp);
3360*67e74705SXin Li if (Res.isInvalid()) {
3361*67e74705SXin Li // FIXME: Clean up temporaries here anyway?
3362*67e74705SXin Li return StmtError();
3363*67e74705SXin Li }
3364*67e74705SXin Li RetValExp = Res.getAs<Expr>();
3365*67e74705SXin Li
3366*67e74705SXin Li // If we have a related result type, we need to implicitly
3367*67e74705SXin Li // convert back to the formal result type. We can't pretend to
3368*67e74705SXin Li // initialize the result again --- we might end double-retaining
3369*67e74705SXin Li // --- so instead we initialize a notional temporary.
3370*67e74705SXin Li if (!RelatedRetType.isNull()) {
3371*67e74705SXin Li Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3372*67e74705SXin Li FnRetType);
3373*67e74705SXin Li Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3374*67e74705SXin Li if (Res.isInvalid()) {
3375*67e74705SXin Li // FIXME: Clean up temporaries here anyway?
3376*67e74705SXin Li return StmtError();
3377*67e74705SXin Li }
3378*67e74705SXin Li RetValExp = Res.getAs<Expr>();
3379*67e74705SXin Li }
3380*67e74705SXin Li
3381*67e74705SXin Li CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3382*67e74705SXin Li getCurFunctionDecl());
3383*67e74705SXin Li }
3384*67e74705SXin Li
3385*67e74705SXin Li if (RetValExp) {
3386*67e74705SXin Li ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3387*67e74705SXin Li if (ER.isInvalid())
3388*67e74705SXin Li return StmtError();
3389*67e74705SXin Li RetValExp = ER.get();
3390*67e74705SXin Li }
3391*67e74705SXin Li Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3392*67e74705SXin Li }
3393*67e74705SXin Li
3394*67e74705SXin Li // If we need to check for the named return value optimization, save the
3395*67e74705SXin Li // return statement in our scope for later processing.
3396*67e74705SXin Li if (Result->getNRVOCandidate())
3397*67e74705SXin Li FunctionScopes.back()->Returns.push_back(Result);
3398*67e74705SXin Li
3399*67e74705SXin Li if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3400*67e74705SXin Li FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3401*67e74705SXin Li
3402*67e74705SXin Li return Result;
3403*67e74705SXin Li }
3404*67e74705SXin Li
3405*67e74705SXin Li StmtResult
ActOnObjCAtCatchStmt(SourceLocation AtLoc,SourceLocation RParen,Decl * Parm,Stmt * Body)3406*67e74705SXin Li Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3407*67e74705SXin Li SourceLocation RParen, Decl *Parm,
3408*67e74705SXin Li Stmt *Body) {
3409*67e74705SXin Li VarDecl *Var = cast_or_null<VarDecl>(Parm);
3410*67e74705SXin Li if (Var && Var->isInvalidDecl())
3411*67e74705SXin Li return StmtError();
3412*67e74705SXin Li
3413*67e74705SXin Li return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3414*67e74705SXin Li }
3415*67e74705SXin Li
3416*67e74705SXin Li StmtResult
ActOnObjCAtFinallyStmt(SourceLocation AtLoc,Stmt * Body)3417*67e74705SXin Li Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3418*67e74705SXin Li return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3419*67e74705SXin Li }
3420*67e74705SXin Li
3421*67e74705SXin Li StmtResult
ActOnObjCAtTryStmt(SourceLocation AtLoc,Stmt * Try,MultiStmtArg CatchStmts,Stmt * Finally)3422*67e74705SXin Li Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3423*67e74705SXin Li MultiStmtArg CatchStmts, Stmt *Finally) {
3424*67e74705SXin Li if (!getLangOpts().ObjCExceptions)
3425*67e74705SXin Li Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3426*67e74705SXin Li
3427*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
3428*67e74705SXin Li unsigned NumCatchStmts = CatchStmts.size();
3429*67e74705SXin Li return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3430*67e74705SXin Li NumCatchStmts, Finally);
3431*67e74705SXin Li }
3432*67e74705SXin Li
BuildObjCAtThrowStmt(SourceLocation AtLoc,Expr * Throw)3433*67e74705SXin Li StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3434*67e74705SXin Li if (Throw) {
3435*67e74705SXin Li ExprResult Result = DefaultLvalueConversion(Throw);
3436*67e74705SXin Li if (Result.isInvalid())
3437*67e74705SXin Li return StmtError();
3438*67e74705SXin Li
3439*67e74705SXin Li Result = ActOnFinishFullExpr(Result.get());
3440*67e74705SXin Li if (Result.isInvalid())
3441*67e74705SXin Li return StmtError();
3442*67e74705SXin Li Throw = Result.get();
3443*67e74705SXin Li
3444*67e74705SXin Li QualType ThrowType = Throw->getType();
3445*67e74705SXin Li // Make sure the expression type is an ObjC pointer or "void *".
3446*67e74705SXin Li if (!ThrowType->isDependentType() &&
3447*67e74705SXin Li !ThrowType->isObjCObjectPointerType()) {
3448*67e74705SXin Li const PointerType *PT = ThrowType->getAs<PointerType>();
3449*67e74705SXin Li if (!PT || !PT->getPointeeType()->isVoidType())
3450*67e74705SXin Li return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3451*67e74705SXin Li << Throw->getType() << Throw->getSourceRange());
3452*67e74705SXin Li }
3453*67e74705SXin Li }
3454*67e74705SXin Li
3455*67e74705SXin Li return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3456*67e74705SXin Li }
3457*67e74705SXin Li
3458*67e74705SXin Li StmtResult
ActOnObjCAtThrowStmt(SourceLocation AtLoc,Expr * Throw,Scope * CurScope)3459*67e74705SXin Li Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3460*67e74705SXin Li Scope *CurScope) {
3461*67e74705SXin Li if (!getLangOpts().ObjCExceptions)
3462*67e74705SXin Li Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3463*67e74705SXin Li
3464*67e74705SXin Li if (!Throw) {
3465*67e74705SXin Li // @throw without an expression designates a rethrow (which must occur
3466*67e74705SXin Li // in the context of an @catch clause).
3467*67e74705SXin Li Scope *AtCatchParent = CurScope;
3468*67e74705SXin Li while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3469*67e74705SXin Li AtCatchParent = AtCatchParent->getParent();
3470*67e74705SXin Li if (!AtCatchParent)
3471*67e74705SXin Li return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3472*67e74705SXin Li }
3473*67e74705SXin Li return BuildObjCAtThrowStmt(AtLoc, Throw);
3474*67e74705SXin Li }
3475*67e74705SXin Li
3476*67e74705SXin Li ExprResult
ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,Expr * operand)3477*67e74705SXin Li Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3478*67e74705SXin Li ExprResult result = DefaultLvalueConversion(operand);
3479*67e74705SXin Li if (result.isInvalid())
3480*67e74705SXin Li return ExprError();
3481*67e74705SXin Li operand = result.get();
3482*67e74705SXin Li
3483*67e74705SXin Li // Make sure the expression type is an ObjC pointer or "void *".
3484*67e74705SXin Li QualType type = operand->getType();
3485*67e74705SXin Li if (!type->isDependentType() &&
3486*67e74705SXin Li !type->isObjCObjectPointerType()) {
3487*67e74705SXin Li const PointerType *pointerType = type->getAs<PointerType>();
3488*67e74705SXin Li if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3489*67e74705SXin Li if (getLangOpts().CPlusPlus) {
3490*67e74705SXin Li if (RequireCompleteType(atLoc, type,
3491*67e74705SXin Li diag::err_incomplete_receiver_type))
3492*67e74705SXin Li return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3493*67e74705SXin Li << type << operand->getSourceRange();
3494*67e74705SXin Li
3495*67e74705SXin Li ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3496*67e74705SXin Li if (!result.isUsable())
3497*67e74705SXin Li return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3498*67e74705SXin Li << type << operand->getSourceRange();
3499*67e74705SXin Li
3500*67e74705SXin Li operand = result.get();
3501*67e74705SXin Li } else {
3502*67e74705SXin Li return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3503*67e74705SXin Li << type << operand->getSourceRange();
3504*67e74705SXin Li }
3505*67e74705SXin Li }
3506*67e74705SXin Li }
3507*67e74705SXin Li
3508*67e74705SXin Li // The operand to @synchronized is a full-expression.
3509*67e74705SXin Li return ActOnFinishFullExpr(operand);
3510*67e74705SXin Li }
3511*67e74705SXin Li
3512*67e74705SXin Li StmtResult
ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,Expr * SyncExpr,Stmt * SyncBody)3513*67e74705SXin Li Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3514*67e74705SXin Li Stmt *SyncBody) {
3515*67e74705SXin Li // We can't jump into or indirect-jump out of a @synchronized block.
3516*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
3517*67e74705SXin Li return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3518*67e74705SXin Li }
3519*67e74705SXin Li
3520*67e74705SXin Li /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3521*67e74705SXin Li /// and creates a proper catch handler from them.
3522*67e74705SXin Li StmtResult
ActOnCXXCatchBlock(SourceLocation CatchLoc,Decl * ExDecl,Stmt * HandlerBlock)3523*67e74705SXin Li Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3524*67e74705SXin Li Stmt *HandlerBlock) {
3525*67e74705SXin Li // There's nothing to test that ActOnExceptionDecl didn't already test.
3526*67e74705SXin Li return new (Context)
3527*67e74705SXin Li CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3528*67e74705SXin Li }
3529*67e74705SXin Li
3530*67e74705SXin Li StmtResult
ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc,Stmt * Body)3531*67e74705SXin Li Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3532*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
3533*67e74705SXin Li return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3534*67e74705SXin Li }
3535*67e74705SXin Li
3536*67e74705SXin Li namespace {
3537*67e74705SXin Li class CatchHandlerType {
3538*67e74705SXin Li QualType QT;
3539*67e74705SXin Li unsigned IsPointer : 1;
3540*67e74705SXin Li
3541*67e74705SXin Li // This is a special constructor to be used only with DenseMapInfo's
3542*67e74705SXin Li // getEmptyKey() and getTombstoneKey() functions.
3543*67e74705SXin Li friend struct llvm::DenseMapInfo<CatchHandlerType>;
3544*67e74705SXin Li enum Unique { ForDenseMap };
CatchHandlerType(QualType QT,Unique)3545*67e74705SXin Li CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3546*67e74705SXin Li
3547*67e74705SXin Li public:
3548*67e74705SXin Li /// Used when creating a CatchHandlerType from a handler type; will determine
3549*67e74705SXin Li /// whether the type is a pointer or reference and will strip off the top
3550*67e74705SXin Li /// level pointer and cv-qualifiers.
CatchHandlerType(QualType Q)3551*67e74705SXin Li CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3552*67e74705SXin Li if (QT->isPointerType())
3553*67e74705SXin Li IsPointer = true;
3554*67e74705SXin Li
3555*67e74705SXin Li if (IsPointer || QT->isReferenceType())
3556*67e74705SXin Li QT = QT->getPointeeType();
3557*67e74705SXin Li QT = QT.getUnqualifiedType();
3558*67e74705SXin Li }
3559*67e74705SXin Li
3560*67e74705SXin Li /// Used when creating a CatchHandlerType from a base class type; pretends the
3561*67e74705SXin Li /// type passed in had the pointer qualifier, does not need to get an
3562*67e74705SXin Li /// unqualified type.
CatchHandlerType(QualType QT,bool IsPointer)3563*67e74705SXin Li CatchHandlerType(QualType QT, bool IsPointer)
3564*67e74705SXin Li : QT(QT), IsPointer(IsPointer) {}
3565*67e74705SXin Li
underlying() const3566*67e74705SXin Li QualType underlying() const { return QT; }
isPointer() const3567*67e74705SXin Li bool isPointer() const { return IsPointer; }
3568*67e74705SXin Li
operator ==(const CatchHandlerType & LHS,const CatchHandlerType & RHS)3569*67e74705SXin Li friend bool operator==(const CatchHandlerType &LHS,
3570*67e74705SXin Li const CatchHandlerType &RHS) {
3571*67e74705SXin Li // If the pointer qualification does not match, we can return early.
3572*67e74705SXin Li if (LHS.IsPointer != RHS.IsPointer)
3573*67e74705SXin Li return false;
3574*67e74705SXin Li // Otherwise, check the underlying type without cv-qualifiers.
3575*67e74705SXin Li return LHS.QT == RHS.QT;
3576*67e74705SXin Li }
3577*67e74705SXin Li };
3578*67e74705SXin Li } // namespace
3579*67e74705SXin Li
3580*67e74705SXin Li namespace llvm {
3581*67e74705SXin Li template <> struct DenseMapInfo<CatchHandlerType> {
getEmptyKeyllvm::DenseMapInfo3582*67e74705SXin Li static CatchHandlerType getEmptyKey() {
3583*67e74705SXin Li return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3584*67e74705SXin Li CatchHandlerType::ForDenseMap);
3585*67e74705SXin Li }
3586*67e74705SXin Li
getTombstoneKeyllvm::DenseMapInfo3587*67e74705SXin Li static CatchHandlerType getTombstoneKey() {
3588*67e74705SXin Li return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3589*67e74705SXin Li CatchHandlerType::ForDenseMap);
3590*67e74705SXin Li }
3591*67e74705SXin Li
getHashValuellvm::DenseMapInfo3592*67e74705SXin Li static unsigned getHashValue(const CatchHandlerType &Base) {
3593*67e74705SXin Li return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3594*67e74705SXin Li }
3595*67e74705SXin Li
isEqualllvm::DenseMapInfo3596*67e74705SXin Li static bool isEqual(const CatchHandlerType &LHS,
3597*67e74705SXin Li const CatchHandlerType &RHS) {
3598*67e74705SXin Li return LHS == RHS;
3599*67e74705SXin Li }
3600*67e74705SXin Li };
3601*67e74705SXin Li }
3602*67e74705SXin Li
3603*67e74705SXin Li namespace {
3604*67e74705SXin Li class CatchTypePublicBases {
3605*67e74705SXin Li ASTContext &Ctx;
3606*67e74705SXin Li const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3607*67e74705SXin Li const bool CheckAgainstPointer;
3608*67e74705SXin Li
3609*67e74705SXin Li CXXCatchStmt *FoundHandler;
3610*67e74705SXin Li CanQualType FoundHandlerType;
3611*67e74705SXin Li
3612*67e74705SXin Li public:
CatchTypePublicBases(ASTContext & Ctx,const llvm::DenseMap<CatchHandlerType,CXXCatchStmt * > & T,bool C)3613*67e74705SXin Li CatchTypePublicBases(
3614*67e74705SXin Li ASTContext &Ctx,
3615*67e74705SXin Li const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3616*67e74705SXin Li : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3617*67e74705SXin Li FoundHandler(nullptr) {}
3618*67e74705SXin Li
getFoundHandler() const3619*67e74705SXin Li CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
getFoundHandlerType() const3620*67e74705SXin Li CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3621*67e74705SXin Li
operator ()(const CXXBaseSpecifier * S,CXXBasePath &)3622*67e74705SXin Li bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3623*67e74705SXin Li if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3624*67e74705SXin Li CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3625*67e74705SXin Li const auto &M = TypesToCheck;
3626*67e74705SXin Li auto I = M.find(Check);
3627*67e74705SXin Li if (I != M.end()) {
3628*67e74705SXin Li FoundHandler = I->second;
3629*67e74705SXin Li FoundHandlerType = Ctx.getCanonicalType(S->getType());
3630*67e74705SXin Li return true;
3631*67e74705SXin Li }
3632*67e74705SXin Li }
3633*67e74705SXin Li return false;
3634*67e74705SXin Li }
3635*67e74705SXin Li };
3636*67e74705SXin Li }
3637*67e74705SXin Li
3638*67e74705SXin Li /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3639*67e74705SXin Li /// handlers and creates a try statement from them.
ActOnCXXTryBlock(SourceLocation TryLoc,Stmt * TryBlock,ArrayRef<Stmt * > Handlers)3640*67e74705SXin Li StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3641*67e74705SXin Li ArrayRef<Stmt *> Handlers) {
3642*67e74705SXin Li // Don't report an error if 'try' is used in system headers.
3643*67e74705SXin Li if (!getLangOpts().CXXExceptions &&
3644*67e74705SXin Li !getSourceManager().isInSystemHeader(TryLoc))
3645*67e74705SXin Li Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3646*67e74705SXin Li
3647*67e74705SXin Li if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3648*67e74705SXin Li Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3649*67e74705SXin Li
3650*67e74705SXin Li sema::FunctionScopeInfo *FSI = getCurFunction();
3651*67e74705SXin Li
3652*67e74705SXin Li // C++ try is incompatible with SEH __try.
3653*67e74705SXin Li if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3654*67e74705SXin Li Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3655*67e74705SXin Li Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3656*67e74705SXin Li }
3657*67e74705SXin Li
3658*67e74705SXin Li const unsigned NumHandlers = Handlers.size();
3659*67e74705SXin Li assert(!Handlers.empty() &&
3660*67e74705SXin Li "The parser shouldn't call this if there are no handlers.");
3661*67e74705SXin Li
3662*67e74705SXin Li llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3663*67e74705SXin Li for (unsigned i = 0; i < NumHandlers; ++i) {
3664*67e74705SXin Li CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3665*67e74705SXin Li
3666*67e74705SXin Li // Diagnose when the handler is a catch-all handler, but it isn't the last
3667*67e74705SXin Li // handler for the try block. [except.handle]p5. Also, skip exception
3668*67e74705SXin Li // declarations that are invalid, since we can't usefully report on them.
3669*67e74705SXin Li if (!H->getExceptionDecl()) {
3670*67e74705SXin Li if (i < NumHandlers - 1)
3671*67e74705SXin Li return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3672*67e74705SXin Li continue;
3673*67e74705SXin Li } else if (H->getExceptionDecl()->isInvalidDecl())
3674*67e74705SXin Li continue;
3675*67e74705SXin Li
3676*67e74705SXin Li // Walk the type hierarchy to diagnose when this type has already been
3677*67e74705SXin Li // handled (duplication), or cannot be handled (derivation inversion). We
3678*67e74705SXin Li // ignore top-level cv-qualifiers, per [except.handle]p3
3679*67e74705SXin Li CatchHandlerType HandlerCHT =
3680*67e74705SXin Li (QualType)Context.getCanonicalType(H->getCaughtType());
3681*67e74705SXin Li
3682*67e74705SXin Li // We can ignore whether the type is a reference or a pointer; we need the
3683*67e74705SXin Li // underlying declaration type in order to get at the underlying record
3684*67e74705SXin Li // decl, if there is one.
3685*67e74705SXin Li QualType Underlying = HandlerCHT.underlying();
3686*67e74705SXin Li if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3687*67e74705SXin Li if (!RD->hasDefinition())
3688*67e74705SXin Li continue;
3689*67e74705SXin Li // Check that none of the public, unambiguous base classes are in the
3690*67e74705SXin Li // map ([except.handle]p1). Give the base classes the same pointer
3691*67e74705SXin Li // qualification as the original type we are basing off of. This allows
3692*67e74705SXin Li // comparison against the handler type using the same top-level pointer
3693*67e74705SXin Li // as the original type.
3694*67e74705SXin Li CXXBasePaths Paths;
3695*67e74705SXin Li Paths.setOrigin(RD);
3696*67e74705SXin Li CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3697*67e74705SXin Li if (RD->lookupInBases(CTPB, Paths)) {
3698*67e74705SXin Li const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3699*67e74705SXin Li if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3700*67e74705SXin Li Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3701*67e74705SXin Li diag::warn_exception_caught_by_earlier_handler)
3702*67e74705SXin Li << H->getCaughtType();
3703*67e74705SXin Li Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3704*67e74705SXin Li diag::note_previous_exception_handler)
3705*67e74705SXin Li << Problem->getCaughtType();
3706*67e74705SXin Li }
3707*67e74705SXin Li }
3708*67e74705SXin Li }
3709*67e74705SXin Li
3710*67e74705SXin Li // Add the type the list of ones we have handled; diagnose if we've already
3711*67e74705SXin Li // handled it.
3712*67e74705SXin Li auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3713*67e74705SXin Li if (!R.second) {
3714*67e74705SXin Li const CXXCatchStmt *Problem = R.first->second;
3715*67e74705SXin Li Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3716*67e74705SXin Li diag::warn_exception_caught_by_earlier_handler)
3717*67e74705SXin Li << H->getCaughtType();
3718*67e74705SXin Li Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3719*67e74705SXin Li diag::note_previous_exception_handler)
3720*67e74705SXin Li << Problem->getCaughtType();
3721*67e74705SXin Li }
3722*67e74705SXin Li }
3723*67e74705SXin Li
3724*67e74705SXin Li FSI->setHasCXXTry(TryLoc);
3725*67e74705SXin Li
3726*67e74705SXin Li return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3727*67e74705SXin Li }
3728*67e74705SXin Li
ActOnSEHTryBlock(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)3729*67e74705SXin Li StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3730*67e74705SXin Li Stmt *TryBlock, Stmt *Handler) {
3731*67e74705SXin Li assert(TryBlock && Handler);
3732*67e74705SXin Li
3733*67e74705SXin Li sema::FunctionScopeInfo *FSI = getCurFunction();
3734*67e74705SXin Li
3735*67e74705SXin Li // SEH __try is incompatible with C++ try. Borland appears to support this,
3736*67e74705SXin Li // however.
3737*67e74705SXin Li if (!getLangOpts().Borland) {
3738*67e74705SXin Li if (FSI->FirstCXXTryLoc.isValid()) {
3739*67e74705SXin Li Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3740*67e74705SXin Li Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3741*67e74705SXin Li }
3742*67e74705SXin Li }
3743*67e74705SXin Li
3744*67e74705SXin Li FSI->setHasSEHTry(TryLoc);
3745*67e74705SXin Li
3746*67e74705SXin Li // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3747*67e74705SXin Li // track if they use SEH.
3748*67e74705SXin Li DeclContext *DC = CurContext;
3749*67e74705SXin Li while (DC && !DC->isFunctionOrMethod())
3750*67e74705SXin Li DC = DC->getParent();
3751*67e74705SXin Li FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3752*67e74705SXin Li if (FD)
3753*67e74705SXin Li FD->setUsesSEHTry(true);
3754*67e74705SXin Li else
3755*67e74705SXin Li Diag(TryLoc, diag::err_seh_try_outside_functions);
3756*67e74705SXin Li
3757*67e74705SXin Li // Reject __try on unsupported targets.
3758*67e74705SXin Li if (!Context.getTargetInfo().isSEHTrySupported())
3759*67e74705SXin Li Diag(TryLoc, diag::err_seh_try_unsupported);
3760*67e74705SXin Li
3761*67e74705SXin Li return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
3762*67e74705SXin Li }
3763*67e74705SXin Li
3764*67e74705SXin Li StmtResult
ActOnSEHExceptBlock(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)3765*67e74705SXin Li Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3766*67e74705SXin Li Expr *FilterExpr,
3767*67e74705SXin Li Stmt *Block) {
3768*67e74705SXin Li assert(FilterExpr && Block);
3769*67e74705SXin Li
3770*67e74705SXin Li if(!FilterExpr->getType()->isIntegerType()) {
3771*67e74705SXin Li return StmtError(Diag(FilterExpr->getExprLoc(),
3772*67e74705SXin Li diag::err_filter_expression_integral)
3773*67e74705SXin Li << FilterExpr->getType());
3774*67e74705SXin Li }
3775*67e74705SXin Li
3776*67e74705SXin Li return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3777*67e74705SXin Li }
3778*67e74705SXin Li
ActOnStartSEHFinallyBlock()3779*67e74705SXin Li void Sema::ActOnStartSEHFinallyBlock() {
3780*67e74705SXin Li CurrentSEHFinally.push_back(CurScope);
3781*67e74705SXin Li }
3782*67e74705SXin Li
ActOnAbortSEHFinallyBlock()3783*67e74705SXin Li void Sema::ActOnAbortSEHFinallyBlock() {
3784*67e74705SXin Li CurrentSEHFinally.pop_back();
3785*67e74705SXin Li }
3786*67e74705SXin Li
ActOnFinishSEHFinallyBlock(SourceLocation Loc,Stmt * Block)3787*67e74705SXin Li StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
3788*67e74705SXin Li assert(Block);
3789*67e74705SXin Li CurrentSEHFinally.pop_back();
3790*67e74705SXin Li return SEHFinallyStmt::Create(Context, Loc, Block);
3791*67e74705SXin Li }
3792*67e74705SXin Li
3793*67e74705SXin Li StmtResult
ActOnSEHLeaveStmt(SourceLocation Loc,Scope * CurScope)3794*67e74705SXin Li Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3795*67e74705SXin Li Scope *SEHTryParent = CurScope;
3796*67e74705SXin Li while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3797*67e74705SXin Li SEHTryParent = SEHTryParent->getParent();
3798*67e74705SXin Li if (!SEHTryParent)
3799*67e74705SXin Li return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3800*67e74705SXin Li CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
3801*67e74705SXin Li
3802*67e74705SXin Li return new (Context) SEHLeaveStmt(Loc);
3803*67e74705SXin Li }
3804*67e74705SXin Li
BuildMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,NestedNameSpecifierLoc QualifierLoc,DeclarationNameInfo NameInfo,Stmt * Nested)3805*67e74705SXin Li StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3806*67e74705SXin Li bool IsIfExists,
3807*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc,
3808*67e74705SXin Li DeclarationNameInfo NameInfo,
3809*67e74705SXin Li Stmt *Nested)
3810*67e74705SXin Li {
3811*67e74705SXin Li return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3812*67e74705SXin Li QualifierLoc, NameInfo,
3813*67e74705SXin Li cast<CompoundStmt>(Nested));
3814*67e74705SXin Li }
3815*67e74705SXin Li
3816*67e74705SXin Li
ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name,Stmt * Nested)3817*67e74705SXin Li StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3818*67e74705SXin Li bool IsIfExists,
3819*67e74705SXin Li CXXScopeSpec &SS,
3820*67e74705SXin Li UnqualifiedId &Name,
3821*67e74705SXin Li Stmt *Nested) {
3822*67e74705SXin Li return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3823*67e74705SXin Li SS.getWithLocInContext(Context),
3824*67e74705SXin Li GetNameFromUnqualifiedId(Name),
3825*67e74705SXin Li Nested);
3826*67e74705SXin Li }
3827*67e74705SXin Li
3828*67e74705SXin Li RecordDecl*
CreateCapturedStmtRecordDecl(CapturedDecl * & CD,SourceLocation Loc,unsigned NumParams)3829*67e74705SXin Li Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3830*67e74705SXin Li unsigned NumParams) {
3831*67e74705SXin Li DeclContext *DC = CurContext;
3832*67e74705SXin Li while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3833*67e74705SXin Li DC = DC->getParent();
3834*67e74705SXin Li
3835*67e74705SXin Li RecordDecl *RD = nullptr;
3836*67e74705SXin Li if (getLangOpts().CPlusPlus)
3837*67e74705SXin Li RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3838*67e74705SXin Li /*Id=*/nullptr);
3839*67e74705SXin Li else
3840*67e74705SXin Li RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3841*67e74705SXin Li
3842*67e74705SXin Li RD->setCapturedRecord();
3843*67e74705SXin Li DC->addDecl(RD);
3844*67e74705SXin Li RD->setImplicit();
3845*67e74705SXin Li RD->startDefinition();
3846*67e74705SXin Li
3847*67e74705SXin Li assert(NumParams > 0 && "CapturedStmt requires context parameter");
3848*67e74705SXin Li CD = CapturedDecl::Create(Context, CurContext, NumParams);
3849*67e74705SXin Li DC->addDecl(CD);
3850*67e74705SXin Li return RD;
3851*67e74705SXin Li }
3852*67e74705SXin Li
buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> & Captures,SmallVectorImpl<Expr * > & CaptureInits,ArrayRef<CapturingScopeInfo::Capture> Candidates)3853*67e74705SXin Li static void buildCapturedStmtCaptureList(
3854*67e74705SXin Li SmallVectorImpl<CapturedStmt::Capture> &Captures,
3855*67e74705SXin Li SmallVectorImpl<Expr *> &CaptureInits,
3856*67e74705SXin Li ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3857*67e74705SXin Li
3858*67e74705SXin Li typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3859*67e74705SXin Li for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3860*67e74705SXin Li
3861*67e74705SXin Li if (Cap->isThisCapture()) {
3862*67e74705SXin Li Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3863*67e74705SXin Li CapturedStmt::VCK_This));
3864*67e74705SXin Li CaptureInits.push_back(Cap->getInitExpr());
3865*67e74705SXin Li continue;
3866*67e74705SXin Li } else if (Cap->isVLATypeCapture()) {
3867*67e74705SXin Li Captures.push_back(
3868*67e74705SXin Li CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3869*67e74705SXin Li CaptureInits.push_back(nullptr);
3870*67e74705SXin Li continue;
3871*67e74705SXin Li }
3872*67e74705SXin Li
3873*67e74705SXin Li Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3874*67e74705SXin Li Cap->isReferenceCapture()
3875*67e74705SXin Li ? CapturedStmt::VCK_ByRef
3876*67e74705SXin Li : CapturedStmt::VCK_ByCopy,
3877*67e74705SXin Li Cap->getVariable()));
3878*67e74705SXin Li CaptureInits.push_back(Cap->getInitExpr());
3879*67e74705SXin Li }
3880*67e74705SXin Li }
3881*67e74705SXin Li
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,unsigned NumParams)3882*67e74705SXin Li void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3883*67e74705SXin Li CapturedRegionKind Kind,
3884*67e74705SXin Li unsigned NumParams) {
3885*67e74705SXin Li CapturedDecl *CD = nullptr;
3886*67e74705SXin Li RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3887*67e74705SXin Li
3888*67e74705SXin Li // Build the context parameter
3889*67e74705SXin Li DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3890*67e74705SXin Li IdentifierInfo *ParamName = &Context.Idents.get("__context");
3891*67e74705SXin Li QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3892*67e74705SXin Li ImplicitParamDecl *Param
3893*67e74705SXin Li = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3894*67e74705SXin Li DC->addDecl(Param);
3895*67e74705SXin Li
3896*67e74705SXin Li CD->setContextParam(0, Param);
3897*67e74705SXin Li
3898*67e74705SXin Li // Enter the capturing scope for this captured region.
3899*67e74705SXin Li PushCapturedRegionScope(CurScope, CD, RD, Kind);
3900*67e74705SXin Li
3901*67e74705SXin Li if (CurScope)
3902*67e74705SXin Li PushDeclContext(CurScope, CD);
3903*67e74705SXin Li else
3904*67e74705SXin Li CurContext = CD;
3905*67e74705SXin Li
3906*67e74705SXin Li PushExpressionEvaluationContext(PotentiallyEvaluated);
3907*67e74705SXin Li }
3908*67e74705SXin Li
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,ArrayRef<CapturedParamNameType> Params)3909*67e74705SXin Li void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3910*67e74705SXin Li CapturedRegionKind Kind,
3911*67e74705SXin Li ArrayRef<CapturedParamNameType> Params) {
3912*67e74705SXin Li CapturedDecl *CD = nullptr;
3913*67e74705SXin Li RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3914*67e74705SXin Li
3915*67e74705SXin Li // Build the context parameter
3916*67e74705SXin Li DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3917*67e74705SXin Li bool ContextIsFound = false;
3918*67e74705SXin Li unsigned ParamNum = 0;
3919*67e74705SXin Li for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3920*67e74705SXin Li E = Params.end();
3921*67e74705SXin Li I != E; ++I, ++ParamNum) {
3922*67e74705SXin Li if (I->second.isNull()) {
3923*67e74705SXin Li assert(!ContextIsFound &&
3924*67e74705SXin Li "null type has been found already for '__context' parameter");
3925*67e74705SXin Li IdentifierInfo *ParamName = &Context.Idents.get("__context");
3926*67e74705SXin Li QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3927*67e74705SXin Li ImplicitParamDecl *Param
3928*67e74705SXin Li = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3929*67e74705SXin Li DC->addDecl(Param);
3930*67e74705SXin Li CD->setContextParam(ParamNum, Param);
3931*67e74705SXin Li ContextIsFound = true;
3932*67e74705SXin Li } else {
3933*67e74705SXin Li IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3934*67e74705SXin Li ImplicitParamDecl *Param
3935*67e74705SXin Li = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3936*67e74705SXin Li DC->addDecl(Param);
3937*67e74705SXin Li CD->setParam(ParamNum, Param);
3938*67e74705SXin Li }
3939*67e74705SXin Li }
3940*67e74705SXin Li assert(ContextIsFound && "no null type for '__context' parameter");
3941*67e74705SXin Li if (!ContextIsFound) {
3942*67e74705SXin Li // Add __context implicitly if it is not specified.
3943*67e74705SXin Li IdentifierInfo *ParamName = &Context.Idents.get("__context");
3944*67e74705SXin Li QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3945*67e74705SXin Li ImplicitParamDecl *Param =
3946*67e74705SXin Li ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3947*67e74705SXin Li DC->addDecl(Param);
3948*67e74705SXin Li CD->setContextParam(ParamNum, Param);
3949*67e74705SXin Li }
3950*67e74705SXin Li // Enter the capturing scope for this captured region.
3951*67e74705SXin Li PushCapturedRegionScope(CurScope, CD, RD, Kind);
3952*67e74705SXin Li
3953*67e74705SXin Li if (CurScope)
3954*67e74705SXin Li PushDeclContext(CurScope, CD);
3955*67e74705SXin Li else
3956*67e74705SXin Li CurContext = CD;
3957*67e74705SXin Li
3958*67e74705SXin Li PushExpressionEvaluationContext(PotentiallyEvaluated);
3959*67e74705SXin Li }
3960*67e74705SXin Li
ActOnCapturedRegionError()3961*67e74705SXin Li void Sema::ActOnCapturedRegionError() {
3962*67e74705SXin Li DiscardCleanupsInEvaluationContext();
3963*67e74705SXin Li PopExpressionEvaluationContext();
3964*67e74705SXin Li
3965*67e74705SXin Li CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3966*67e74705SXin Li RecordDecl *Record = RSI->TheRecordDecl;
3967*67e74705SXin Li Record->setInvalidDecl();
3968*67e74705SXin Li
3969*67e74705SXin Li SmallVector<Decl*, 4> Fields(Record->fields());
3970*67e74705SXin Li ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3971*67e74705SXin Li SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3972*67e74705SXin Li
3973*67e74705SXin Li PopDeclContext();
3974*67e74705SXin Li PopFunctionScopeInfo();
3975*67e74705SXin Li }
3976*67e74705SXin Li
ActOnCapturedRegionEnd(Stmt * S)3977*67e74705SXin Li StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3978*67e74705SXin Li CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3979*67e74705SXin Li
3980*67e74705SXin Li SmallVector<CapturedStmt::Capture, 4> Captures;
3981*67e74705SXin Li SmallVector<Expr *, 4> CaptureInits;
3982*67e74705SXin Li buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3983*67e74705SXin Li
3984*67e74705SXin Li CapturedDecl *CD = RSI->TheCapturedDecl;
3985*67e74705SXin Li RecordDecl *RD = RSI->TheRecordDecl;
3986*67e74705SXin Li
3987*67e74705SXin Li CapturedStmt *Res = CapturedStmt::Create(
3988*67e74705SXin Li getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
3989*67e74705SXin Li Captures, CaptureInits, CD, RD);
3990*67e74705SXin Li
3991*67e74705SXin Li CD->setBody(Res->getCapturedStmt());
3992*67e74705SXin Li RD->completeDefinition();
3993*67e74705SXin Li
3994*67e74705SXin Li DiscardCleanupsInEvaluationContext();
3995*67e74705SXin Li PopExpressionEvaluationContext();
3996*67e74705SXin Li
3997*67e74705SXin Li PopDeclContext();
3998*67e74705SXin Li PopFunctionScopeInfo();
3999*67e74705SXin Li
4000*67e74705SXin Li return Res;
4001*67e74705SXin Li }
4002